code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
# tool_extrude.py
# Extrusion tool.
# Copyright (c) 2015, Lennart Riecken
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
from PySide import QtGui, QtCore
from tool import Tool, EventData, MouseButtons, KeyModifiers, Face
from plugin_api import register_plugin
class ExtrudeTool(Tool):
def __init__(self, api):
super(ExtrudeTool, self).__init__(api)
# Create our action / icon
self.action = QtGui.QAction(QtGui.QPixmap(":/images/gfx/icons/border-bottom-thick.png"), "Extrude", None)
self.action.setStatusTip("Extude region")
self.action.setCheckable(True)
self.action.setShortcut(QtGui.QKeySequence("Ctrl+0"))
# Register the tool
self.priority = 10
self.api.register_tool(self)
# Area tool helper
self._mouse = None
self._stamp = []
self.xdir = True
self.ydir = True
self.zdir = True
self.pastoffset = 0
self.fixeddirection = False
def drawstamp(self, data, dx, dy, dz):
for x, y, z, col in self._stamp:
tgt = data.voxels.get(x + dx, y + dy, z + dz)
if tgt == 0:
data.voxels.set(x + dx, y + dy, z + dz, col, True, 1)
data.voxels.completeUndoFill()
def on_drag_start(self, data):
if len(data.voxels._selection) > 0:
self._stamp = []
for x, y, z in data.voxels._selection:
col = data.voxels.get(x, y, z)
self._stamp.append((x, y, z, col))
self._mouse = (data.mouse_x, data.mouse_y)
if QtCore.Qt.Key_X in data.keys:
self.xdir = True
self.ydir = False
self.zdir = False
self.fixeddirection = True
elif QtCore.Qt.Key_Y in data.keys:
self.xdir = False
self.ydir = True
self.zdir = False
self.fixeddirection = True
elif QtCore.Qt.Key_Z in data.keys:
self.xdir = False
self.ydir = False
self.zdir = True
self.fixeddirection = True
else:
self.xdir = True
self.ydir = True
self.zdir = True
self.fixeddirection = False
self.pastoffset = 0
# When dragging, create the selection
def on_drag(self, data):
# In case the first click has missed a valid target.
if self._mouse is None or len(self._stamp) == 0:
return
dx = data.mouse_x - self._mouse[0]
dy = data.mouse_y - self._mouse[1]
# Work out some sort of vague translation between screen and voxels
sx = self.api.mainwindow.width() / data.voxels.width
sy = self.api.mainwindow.height() / data.voxels.height
dx = int(round(dx / float(sx)))
dy = int(round(dy / float(sy)))
if dx == 0 and dy == 0:
return
# Work out translation for x,y
ax, ay = self.api.mainwindow.display.view_axis()
tx = 0
ty = 0
tz = 0
tdx = 0
tdy = 0
tdz = 0
if ax == self.api.mainwindow.display.X_AXIS:
tdx = dx
if dx > 0:
tx = 1
elif dx < 0:
tx = -1
elif ax == self.api.mainwindow.display.Y_AXIS:
tdy = dx
if dx > 0:
ty = 1
elif dx < 0:
ty = -1
elif ax == self.api.mainwindow.display.Z_AXIS:
tdz = dx
if dx > 0:
tz = 1
elif dx < 0:
tz = -1
if ay == self.api.mainwindow.display.X_AXIS:
tdx = dy
if dy > 0:
tx = 1
elif dy < 0:
tx = -1
elif ay == self.api.mainwindow.display.Y_AXIS:
tdy = dy
if dy > 0:
ty = -1
elif dy < 0:
ty = 1
elif ay == self.api.mainwindow.display.Z_AXIS:
tdz = dy
if dy > 0:
tz = 1
elif dy < 0:
tz = -1
if self.fixeddirection:
if self.xdir:
if tx != 0:
self._mouse = (data.mouse_x, data.mouse_y)
self.pastoffset += tx
self.drawstamp(data, self.pastoffset, 0, 0)
elif self.ydir:
if ty != 0:
self._mouse = (data.mouse_x, data.mouse_y)
self.pastoffset += ty
self.drawstamp(data, 0, self.pastoffset, 0)
elif self.zdir:
if tz != 0:
self._mouse = (data.mouse_x, data.mouse_y)
self.pastoffset += tz
self.drawstamp(data, 0, 0, self.pastoffset)
else:
if tx != 0 and self.xdir and (not self.ydir or (abs(tdx) > abs(tdy) and abs(tdx) > abs(tdz))):
self._mouse = (data.mouse_x, data.mouse_y)
self.ydir = False
self.zdir = False
self.pastoffset += tx
self.drawstamp(data, self.pastoffset, 0, 0)
elif ty != 0 and self.ydir and (not self.zdir or abs(tdy) > abs(tdz)):
self._mouse = (data.mouse_x, data.mouse_y)
self.xdir = False
self.zdir = False
self.pastoffset += ty
self.drawstamp(data, 0, self.pastoffset, 0)
elif tz != 0 and self.zdir:
self._mouse = (data.mouse_x, data.mouse_y)
self.xdir = False
self.ydir = False
self.pastoffset += tz
self.drawstamp(data, 0, 0, self.pastoffset)
def on_drag_end(self, data):
data.voxels.clear_selection()
dx = self.pastoffset if self.xdir else 0
dy = self.pastoffset if self.ydir else 0
dz = self.pastoffset if self.zdir else 0
for x, y, z, col in self._stamp:
data.voxels.select(x + dx, y + dy, z + dz)
register_plugin(ExtrudeTool, "Extrude Tool", "1.0")
| chrmoritz/zoxel | src/plugins/tool_extrude.py | Python | gpl-3.0 | 6,660 |
# proberequests
Collect proberequests from wifi
the redis-server dependency here means a redis server needs to be available, it does not have to be on the same machine.
This data can then be visualised by https://github.com/liliakai/proberequests
## hopper.pl
Channels hops wifi devices, takes multiple --device=<name> arguments
will insure no wifi device listens on the same channel, if there are more devices than channels, extra devices will not be set.
Example: ./hopper.pl --device=mon1 --device=mon2
Depends on:
* perl
* wireless-tools
## collector.pl
Collect probe-requests from a wifi device (needs monitoring mode)
Example: ./collector --device=mon1
Depends on:
* redis-server
* tshark
* perl
* libredis-perl (Redis)
* libjson-perl (JSON)
* (optional) libprotocol-osc-perl (Protocol::OSC)
## redis2json.pl
Dumps the redis database to json, either to STDOUT or a file
Example: ./redis2json.pl --output=dump.json
Depends on:
* redis-server
* perl
* libredis-perl (Redis)
* libjson-perl (JSON)
## redis-httpd.pl
Serves the redis database as JSON via a webserver
Example: ./redis-httpd.pl --listenport=8080
Depends on:
* redis-server
* perl
* libredis-perl (Redis)
* libjson-perl (JSON)
* libpoe-perl (POE:Component::Server::TCP, POE::Filter::HTTPD)
* libhttp-message-perl (HTTP::Response)
## redis-dancer-httpd.pl
Serves the redis database as JSON via a webserver
Example: ./redis-httpd.pl --listenport=8080
Depends on:
* redis-server
* perl
* libredis-perl (Redis)
* libjson-perl (JSON)
* libdancer2-perl (Dancer2)
Can handle webrequests such as:
/all # all keys/ssids
/match/*foo* # glob matched keys/ssids
/exclude/key1/key2/ # blacklisting keys/ssids
## Preparing wireless devices
* sudo /sbin/iw phy <phy-device-name> interface add <name-of-monitor-device> type monitor
* sudo /sbin/ip link set up dev <name-of-monitor-device>
| webmind/proberequests | README.md | Markdown | gpl-3.0 | 1,869 |
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Events</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="EventDetail">
<h3>Occupation</h3>
<table class="infolist eventlist">
<tbody>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnGRAMPSID">E19998</td>
</tr>
<tr>
<td class="ColumnAttribute">Date</td>
<td class="ColumnColumnDate">
1841
</td>
</tr>
<tr>
<td class="ColumnAttribute">Description</td>
<td class="ColumnColumnDescription">
Sawyer
</td>
</tr>
</tbody>
</table>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/1/e/d15f5fb640d2fc467fe56c437e1.html" title="1841 Census" name ="sref1">
1841 Census
<span class="grampsid"> [S0179]</span>
</a>
<ol>
<li id="sref1a">
<ul>
<li>
Page: HO107; Piece 486, Book 20, Civil Parish St Paul, County Kent, Enum Dist 26, Folio 36, Page 9
</li>
<li>
Confidence: Very High
</li>
</ul>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="references">
<h4>References</h4>
<ol class="Col1" role="Volume-n-Page"type = 1>
<li>
<a href="../../../ppl/4/a/d15f60b264830348dfe07c182a4.html">
GAMMON, William
<span class="grampsid"> [I19307]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:40<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| RossGammon/the-gammons.net | RossFamilyTree/evt/d/5/d15f60b267c1f0f56eca87f355d.html | HTML | gpl-3.0 | 3,404 |
using System;
using System.Linq;
using CMS.Core;
using CMS.DataEngine;
using CMS.UIControls;
using CMS.ExtendedControls;
using CMS.PortalEngine;
using CMS.Helpers;
using CMS.DocumentEngine;
using CMS.Modules;
using CMS.PortalControls;
using CMS.Base;
[UIElement(ModuleName.CMS, "Modules.UserInterface.Design")]
public partial class CMSModules_Modules_Pages_Module_UserInterface_Design : CMSUIPage
{
#region "Public properties"
/// <summary>
/// Document manager
/// </summary>
public override ICMSDocumentManager DocumentManager
{
get
{
// Enable document manager
docMan.Visible = true;
docMan.StopProcessing = false;
docMan.MessagesPlaceHolder.UseRelativePlaceHolder = false;
return docMan;
}
}
/// <summary>
/// Local page messages placeholder
/// </summary>
public override MessagesPlaceHolder MessagesPlaceHolder
{
get
{
return DocumentManager.MessagesPlaceHolder;
}
}
#endregion
#region "Page methods"
/// <summary>
/// PreInit event handler.
/// </summary>
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
// Init the page components
manPortal.SetMainPagePlaceholder(plc);
var ui = UIElementInfoProvider.GetUIElementInfo(QueryHelper.GetInteger("elementid", 0));
// Clear UIContext data of element "Modules.UserInterface.Design" (put by UIElement attribute to check permissions)
var ctx = pnlContext.UIContext;
ctx.Data = null;
ctx.HideControlOnError = false;
if (ui != null)
{
ctx.UIElement = ui;
// Store resource name
ctx.ResourceName = UIContextHelper.GetResourceName(ui.ElementResourceID);
// Provide empty object in case of editing
if (!ui.RepresentsNew)
{
var objectType = UIContextHelper.GetObjectType(ctx);
if (!String.IsNullOrEmpty(objectType))
{
ctx.EditedObject = GetEmptyObject(objectType);
}
}
int pageTemplateId = ui.ElementPageTemplateID;
// If no page template is set, dont show any content
if (pageTemplateId == 0)
{
RedirectToInformation(GetString("uielement.design.notemplate"));
}
// Prepare the page info
PageInfo pi = PageInfoProvider.GetVirtualPageInfo(pageTemplateId);
pi.DocumentNamePath = "/" + ResHelper.GetString("edittabs.design");
DocumentContext.CurrentPageInfo = pi;
// Set the design mode
bool enable = (SystemContext.DevelopmentMode || (ui.ElementResourceID == QueryHelper.GetInteger("moduleId", 0) && ui.ElementIsCustom));
PortalContext.SetRequestViewMode(ViewModeEnum.Design);
// If displayed module is not selected, disable design mode
if (!enable)
{
plc.ViewMode = ViewModeEnum.DesignDisabled;
}
ContextHelper.Add("DisplayContentInDesignMode", PortalHelper.DisplayContentInUIElementDesignMode, true, false, false, DateTime.MinValue);
ManagersContainer = plcManagers;
ScriptManagerControl = manScript;
}
}
private static BaseInfo GetEmptyObject(string objectType)
{
var infoObj = ModuleManager.GetReadOnlyObject(objectType);
var ds = infoObj.Generalized.GetDataQuery(true, q => q.TopN(1), false).Result;
if (!DataHelper.DataSourceIsEmpty(ds))
{
return ModuleManager.GetObject(ds.Tables[0].Rows[0], objectType);
}
return ModuleManager.GetObject(objectType);
}
#endregion
}
| CCChapel/ccchapel.com | CMS/CMSModules/Modules/Pages/Module/UserInterface/Design.aspx.cs | C# | gpl-3.0 | 3,873 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import scipy as sp
#Nome do arquivo em que está os dados da posição
arq = 'CurvaGiro/pos.dat'
#Limites dos eixos
v = [-10,1000, 0, 1000]
#Título eixo x
xl = r'y metros'
#Título do eixo y
yl = r'x metros'
x = sp.genfromtxt('CurvaGiro/pos.dat')
a = plt.plot(x[:,2], x[:,1], 'k-')
plt.grid(True, 'both', color = '0.8', linestyle = '--', linewidth = 1)
plt.axis(v)
plt.xlabel(xl)
plt.ylabel(yl)
plt.show(a)
| asoliveira/NumShip | scripts/entrada/padrao/plot-1cg.py | Python | gpl-3.0 | 489 |
// Copyright (C) Explorer++ Project
// SPDX-License-Identifier: GPL-3.0-only
// See LICENSE in the top level directory
#include "stdafx.h"
#include "../Helper/Helper.h"
#include "../Helper/FileOperations.h"
#include "../Helper/Macros.h"
#include "Helper.h"
void TestGetFileProductVersion(const TCHAR *szFile, DWORD dwExpectedLS, DWORD dwExpectedMS)
{
TCHAR szDLL[MAX_PATH];
GetTestResourceFilePath(szFile, szDLL, SIZEOF_ARRAY(szDLL));
DWORD dwProductVersionLS;
DWORD dwProductVersionMS;
BOOL bRet = GetFileProductVersion(szDLL, &dwProductVersionLS, &dwProductVersionMS);
ASSERT_EQ(TRUE, bRet);
EXPECT_EQ(dwExpectedLS, dwProductVersionLS);
EXPECT_EQ(dwExpectedMS, dwProductVersionMS);
}
TEST(GetFileProductVersion, Catalan)
{
TestGetFileProductVersion(L"Explorer++CA.dll", 327680, 65539);
}
TEST(GetFileProductVersion, French)
{
TestGetFileProductVersion(L"Explorer++FR.dll", 327684, 9);
}
void TestGetFileLanguage(const TCHAR *szFile, WORD wExpectedLanguage)
{
TCHAR szDLL[MAX_PATH];
GetTestResourceFilePath(szFile, szDLL, SIZEOF_ARRAY(szDLL));
WORD wLanguage;
BOOL bRet = GetFileLanguage(szDLL, &wLanguage);
ASSERT_EQ(TRUE, bRet);
EXPECT_EQ(wExpectedLanguage, wLanguage);
}
TEST(GetFileLanguage, Catalan)
{
TestGetFileLanguage(L"Explorer++CA.dll", LANG_CATALAN);
}
TEST(GetFileLanguage, French)
{
TestGetFileLanguage(L"Explorer++FR.dll", LANG_FRENCH);
}
void TestVersionInfoString(TCHAR *szDLL, const TCHAR *szVersionInfo, const TCHAR *szExpectedValue)
{
/* Somewhat flaky, as it relies
on the users default language
been English. */
TCHAR szOutput[512];
BOOL bRet = GetVersionInfoString(szDLL, szVersionInfo, szOutput, SIZEOF_ARRAY(szOutput));
ASSERT_EQ(TRUE, bRet);
EXPECT_STREQ(szExpectedValue, szOutput);
}
TEST(GetVersionInfoString, Simple)
{
TCHAR szDLL[MAX_PATH];
GetTestResourceFilePath(L"VersionInfo.dll", szDLL, SIZEOF_ARRAY(szDLL));
TestVersionInfoString(szDLL, L"CompanyName", L"Test company");
TestVersionInfoString(szDLL, L"FileDescription", L"Test file description");
TestVersionInfoString(szDLL, L"FileVersion", L"1.18.3.3624");
TestVersionInfoString(szDLL, L"InternalName", L"VersionI.dll");
TestVersionInfoString(szDLL, L"LegalCopyright", L"Copyright (C) 2014");
TestVersionInfoString(szDLL, L"OriginalFilename", L"VersionI.dll");
TestVersionInfoString(szDLL, L"ProductName", L"Test product name");
TestVersionInfoString(szDLL, L"ProductVersion", L"1.18.23.4728");
}
class HardLinkTest : public ::testing::Test
{
public:
HardLinkTest() : m_bDeleteDirectory(FALSE)
{
}
protected:
void SetUp()
{
GetTestResourceDirectory(m_szResourceDirectory, SIZEOF_ARRAY(m_szResourceDirectory));
BOOL bRet = PathAppend(m_szResourceDirectory, L"HardLinkTemp");
ASSERT_NE(FALSE, bRet);
bRet = CreateDirectory(m_szResourceDirectory, NULL);
ASSERT_NE(FALSE, bRet);
m_bDeleteDirectory = TRUE;
}
void TearDown()
{
if(m_bDeleteDirectory)
{
std::list<std::wstring> fileList;
fileList.push_back(m_szResourceDirectory);
BOOL bRet = NFileOperations::DeleteFiles(NULL, fileList, TRUE, TRUE);
ASSERT_EQ(TRUE, bRet);
}
}
void CreateTestFileHardLink(const TCHAR *szOriginalFile, const TCHAR *szNewFileName)
{
TCHAR szCopy[MAX_PATH];
TCHAR *szRet = PathCombine(szCopy, m_szResourceDirectory, szNewFileName);
ASSERT_NE(nullptr, szRet);
BOOL bRet = CreateHardLink(szCopy, szOriginalFile, NULL);
ASSERT_NE(FALSE, bRet);
}
TCHAR m_szResourceDirectory[MAX_PATH];
private:
BOOL m_bDeleteDirectory;
};
TEST_F(HardLinkTest, Simple)
{
TCHAR szRoot[MAX_PATH];
StringCchCopy(szRoot, SIZEOF_ARRAY(szRoot), m_szResourceDirectory);
BOOL bRet = PathStripToRoot(szRoot);
ASSERT_NE(FALSE, bRet);
TCHAR szName[32];
bRet = GetVolumeInformation(szRoot, NULL, 0, NULL, NULL, NULL, szName, SIZEOF_ARRAY(szName));
ASSERT_NE(FALSE, bRet);
/* A little hacky, but hard links are
only supported on NTFS. */
if(lstrcmp(L"NTFS", szName) != 0)
{
return;
}
TCHAR szOriginalFile[MAX_PATH];
GetTestResourceFilePath(L"VersionInfo.dll", szOriginalFile, SIZEOF_ARRAY(szOriginalFile));
CreateTestFileHardLink(szOriginalFile, L"HardLinkCopy1");
CreateTestFileHardLink(szOriginalFile, L"HardLinkCopy2");
CreateTestFileHardLink(szOriginalFile, L"HardLinkCopy3");
/* 4 hard links expected - 3 copies + the original. */
DWORD dwLinks = GetNumFileHardLinks(szOriginalFile);
EXPECT_EQ(4, dwLinks);
}
void TestReadImageProperty(const TCHAR *szFile, PROPID propId, const TCHAR *szPropertyExpected)
{
TCHAR szFullFileName[MAX_PATH];
GetTestResourceFilePath(szFile, szFullFileName, SIZEOF_ARRAY(szFullFileName));
TCHAR szProperty[512];
BOOL bRes = ReadImageProperty(szFullFileName, propId, szProperty, SIZEOF_ARRAY(szProperty));
ASSERT_EQ(TRUE, bRes);
EXPECT_STREQ(szPropertyExpected, szProperty);
}
TEST(ReadImageProperty, EquipMake)
{
TestReadImageProperty(L"Metadata.jpg", PropertyTagEquipMake, L"Test camera maker");
}
TEST(ReadImageProperty, EquipModel)
{
TestReadImageProperty(L"Metadata.jpg", PropertyTagEquipModel, L"Test camera model");
}
TEST(GetFileSizeEx, Simple)
{
TCHAR szFullFileName[MAX_PATH];
GetTestResourceFilePath(L"Explorer++CA.dll", szFullFileName, SIZEOF_ARRAY(szFullFileName));
LARGE_INTEGER lFileSize;
BOOL bRes = GetFileSizeEx(szFullFileName, &lFileSize);
ASSERT_EQ(TRUE, bRes);
EXPECT_EQ(62464, lFileSize.QuadPart);
}
void TestCompareFileTypes(const TCHAR *szFile1, const TCHAR *szFile2, BOOL bSameExpected)
{
TCHAR szFullFileName1[MAX_PATH];
GetTestResourceFilePath(szFile1, szFullFileName1, SIZEOF_ARRAY(szFullFileName1));
TCHAR szFullFileName2[MAX_PATH];
GetTestResourceFilePath(szFile2, szFullFileName2, SIZEOF_ARRAY(szFullFileName2));
BOOL bRes = CompareFileTypes(szFullFileName1, szFullFileName2);
EXPECT_EQ(bSameExpected, bRes);
}
TEST(CompareFileTypes, Same)
{
TestCompareFileTypes(L"Explorer++CA.dll", L"Explorer++FR.dll", TRUE);
}
TEST(CompareFileTypes, Different)
{
TestCompareFileTypes(L"Explorer++CA.dll", L"Metadata.jpg", FALSE);
}
class BuildFileAttributeStringTest : public ::testing::Test
{
public:
BuildFileAttributeStringTest() : m_bDeleteFile(FALSE)
{
}
protected:
void TearDown()
{
if(m_bDeleteFile)
{
DeleteFile(m_szFullFileName);
}
}
void RunTest(DWORD dwAttributes, const TCHAR *szAttributeStringExpected)
{
TCHAR szResourceDirectory[MAX_PATH];
GetTestResourceDirectory(szResourceDirectory, SIZEOF_ARRAY(szResourceDirectory));
TCHAR *szOut = PathCombine(m_szFullFileName, szResourceDirectory, L"AttributeFile");
ASSERT_NE(nullptr, szOut);
HANDLE hFile = CreateFile(m_szFullFileName, 0, 0, NULL,
CREATE_NEW, dwAttributes, NULL);
ASSERT_NE(INVALID_HANDLE_VALUE, hFile);
CloseHandle(hFile);
m_bDeleteFile = TRUE;
TCHAR szAttributeString[8];
HRESULT hr = BuildFileAttributeString(m_szFullFileName, szAttributeString, SIZEOF_ARRAY(szAttributeString));
ASSERT_EQ(S_OK, hr);
EXPECT_STREQ(szAttributeStringExpected, szAttributeString);
}
private:
BOOL m_bDeleteFile;
TCHAR m_szFullFileName[MAX_PATH];
};
TEST_F(BuildFileAttributeStringTest, Case1)
{
RunTest(FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_HIDDEN, L"AH-----");
}
TEST_F(BuildFileAttributeStringTest, Case2)
{
RunTest(FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_SYSTEM, L"A--S---");
} | derceg/explorerplusplus | Explorer++/TestHelper/TestHelper.cpp | C++ | gpl-3.0 | 7,535 |
package de.westnordost.streetcomplete.quests.localized_name.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.westnordost.osmapi.map.data.LatLon;
import de.westnordost.osmapi.map.data.OsmLatLon;
import de.westnordost.streetcomplete.data.ApplicationDbTestCase;
public class RoadNameSuggestionsDaoTest extends ApplicationDbTestCase
{
private RoadNameSuggestionsDao dao;
@Override public void setUp() throws Exception
{
super.setUp();
dao = new RoadNameSuggestionsDao(dbHelper, serializer);
}
public void testGetNoNames()
{
List<LatLon> positions = new ArrayList<>();
positions.add(new OsmLatLon(5,5));
List<Map<String, String>> result = dao.getNames(positions, 0);
assertEquals(0, result.size());
}
public void testGetOneNames()
{
HashMap<String,String> names = new HashMap<>();
names.put("de","Große Straße");
names.put("en","Big Street");
dao.putRoad(1, names, createRoadPositions());
List<Map<String, String>> result = dao.getNames(createPosOnRoad(), 1000);
assertEquals(1, result.size());
assertTrue(result.get(0).equals(names));
}
public void testGetMultipleNames()
{
HashMap<String,String> names1 = new HashMap<>();
names1.put("en","Big Street");
dao.putRoad(1, names1, createRoadPositions());
HashMap<String,String> names2 = new HashMap<>();
names2.put("es","Calle Pequena");
dao.putRoad(2, names2, createRoadPositions());
List<Map<String, String>> result = dao.getNames(createPosOnRoad(), 1000);
assertEquals(2, result.size());
assertTrue(result.contains(names1));
assertTrue(result.contains(names2));
}
private static ArrayList<LatLon> createRoadPositions()
{
ArrayList<LatLon> roadPositions = new ArrayList<>();
roadPositions.add(new OsmLatLon(0,0));
roadPositions.add(new OsmLatLon(0,0.0001));
return roadPositions;
}
private static ArrayList<LatLon> createPosOnRoad()
{
ArrayList<LatLon> roadPositions = new ArrayList<>();
roadPositions.add(new OsmLatLon(0,0.00005));
return roadPositions;
}
}
| Binnette/StreetComplete | app/src/androidTest/java/de/westnordost/streetcomplete/quests/localized_name/data/RoadNameSuggestionsDaoTest.java | Java | gpl-3.0 | 2,063 |
/*******************************************************************
Part of the Fritzing project - http://fritzing.org
Copyright (c) 2007-2014 Fachhochschule Potsdam - http://fh-potsdam.de
Fritzing 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.
Fritzing 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 Fritzing. If not, see <http://www.gnu.org/licenses/>.
********************************************************************
$Revision: 6904 $:
$Author: irascibl@gmail.com $:
$Date: 2013-02-26 16:26:03 +0100 (Di, 26. Feb 2013) $
********************************************************************/
#include <QUndoCommand>
#include "abstracteditablelabelwidget.h"
#include "../utils/misc.h"
AbstractEditableLabelWidget::AbstractEditableLabelWidget(QString text, WaitPushUndoStack *undoStack, QWidget *parent, QString title, bool edited, bool noSpacing) : QFrame(parent) {
m_noSpacing = noSpacing;
m_edited = edited;
m_isInEditionMode = false;
m_undoStack = undoStack;
QGridLayout *layout = new QGridLayout;
if(!title.isNull() && !title.isEmpty()) {
m_title = new QLabel(title, this);
m_title->setObjectName("title");
layout->addWidget(m_title,0,0);
} else {
m_title = NULL;
}
setLayout(layout);
m_label = new EditableLabel(text, this);
connect(m_label,SIGNAL(editionStarted(QString)),this,SLOT(editionStarted(QString)));
connect(this,SIGNAL(editionCompleted(QString)),m_label,SLOT(editionCompleted(QString)));
m_acceptButton = new QPushButton(tr("Accept"), this);
connect(m_acceptButton,SIGNAL(clicked()),this,SLOT(informEditionCompleted()));
m_cancelButton = new QPushButton(tr("Cancel"), this);
connect(m_cancelButton,SIGNAL(clicked()),this,SLOT(editionCanceled()));
}
QString AbstractEditableLabelWidget::text() {
if(m_edited) {
return m_label->text();
} else {
return ___emptyString___;
}
}
void AbstractEditableLabelWidget::editionStarted(QString text) {
setEditionText(text);
toEditionMode();
}
void AbstractEditableLabelWidget::informEditionCompleted() {
if(m_isInEditionMode) {
m_undoStack->push(new QUndoCommand("Dummy parts editor command"));
m_edited = true;
emit editionCompleted(editionText());
toStandardMode();
}
}
void AbstractEditableLabelWidget::editionCanceled() {
toStandardMode();
}
void AbstractEditableLabelWidget::toStandardMode() {
m_isInEditionMode = false;
hide();
QGridLayout *layout = (QGridLayout*)this->layout();
myEditionWidget()->hide();
layout->removeWidget(myEditionWidget());
m_acceptButton->hide();
layout->removeWidget(m_acceptButton);
m_cancelButton->hide();
layout->removeWidget(m_cancelButton);
m_label->show();
layout->addWidget(m_label,1,0);
setNoSpacing(layout);
updateGeometry();
show();
emit editionFinished();
}
void AbstractEditableLabelWidget::toEditionMode() {
m_isInEditionMode = true;
hide();
QGridLayout *layout = (QGridLayout*)this->layout();
m_label->hide();
layout->removeWidget(m_label);
if(!m_edited) {
setEmptyTextToEdit();
}
myEditionWidget()->show();
layout->addWidget(myEditionWidget(),1,0,1,5);
m_acceptButton->show();
layout->addWidget(m_acceptButton,2,3);
m_cancelButton->show();
layout->addWidget(m_cancelButton,2,4);
setNoSpacing(layout);
updateGeometry();
show();
emit editionStarted();
}
void AbstractEditableLabelWidget::setNoSpacing(QLayout *layout) {
if(m_noSpacing) {
layout->setMargin(0);
layout->setSpacing(0);
}
}
| sirdel/fritzing | src/partseditor/obsolete/abstracteditablelabelwidget.cpp | C++ | gpl-3.0 | 3,843 |
//============== IV: Multiplayer - http://code.iv-multiplayer.com ==============
//
// File: CBlipManager.h
// Project: Server.Core
// Author(s): jenksta
// Sebihunter
// License: See LICENSE in root directory
//
//==============================================================================
#pragma once
#include "CServer.h"
#include "Interfaces/InterfaceCommon.h"
struct _Blip
{
CVector3 vecSpawnPos;
int iSprite;
unsigned int uiColor;
float fSize;
bool bShortRange;
bool bRouteBlip;
bool bShow;
String strName;
};
struct _PlayerBlip
{
EntityId playerId;
int iSprite;
bool bShortRange;
bool bShow;
};
class CBlipManager : public CBlipManagerInterface
{
private:
bool m_bActive[MAX_BLIPS];
_Blip m_Blips[MAX_BLIPS];
bool m_bPlayerActive[MAX_PLAYERS];
_PlayerBlip m_PlayerBlips[MAX_PLAYERS];
public:
CBlipManager();
~CBlipManager();
EntityId Create(int iSprite, CVector3 vecPosition, bool bShow);
void Delete(EntityId blipId);
void SetPosition(EntityId blipId, CVector3 vecPosition);
CVector3 GetPosition(EntityId blipId);
void SetColor(EntityId blipId, unsigned int color);
unsigned int GetColor(EntityId blipId);
void SetSize(EntityId blipId, float size);
float GetSize(EntityId blipId);
void ToggleShortRange(EntityId blipId, bool bShortRange);
void ToggleRoute(EntityId blipId, bool bRoute);
void SetName(EntityId blipId, String strName);
String GetName(EntityId blipId);
void HandleClientJoin(EntityId playerId);
bool DoesExist(EntityId blipId);
EntityId GetBlipCount();
void SwitchIcon(EntityId blipId, bool bShow, EntityId playerId);
void CreateForPlayer(EntityId playerId, int iSprite, bool bShow);
void DeleteForPlayer(EntityId playerId);
void TogglePlayerShortRange(EntityId playerId, bool bToggle);
void TogglePlayerDisplay(EntityId playerId, bool bToggle);
void TogglePlayerShortRangeForPlayer(EntityId playerId, EntityId toPlayerId, bool bToggle);
void SetSpriteForPlayer(EntityId playerId, int iSprite);
void TogglePlayerDisplayForPlayer(EntityId playerId, EntityId toPlayerId, bool bToggle);
bool DoesPlayerBlipExist(EntityId playerId) { return m_bPlayerActive[playerId]; }
int GetPlayerBlipSprite(EntityId playerId) { return m_PlayerBlips[playerId].iSprite; }
bool GetPlayerBlipShow(EntityId playerId) { return m_PlayerBlips[playerId].bShow; }
};
| guilhermelhr/ivmultiplayer | Server/Core/CBlipManager.h | C | gpl-3.0 | 2,465 |
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2010 Benoit 'BoD' Lubek (BoD@JRAF.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 3 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, see <http://www.gnu.org/licenses/>.
*/
package org.jraf.vtail.misc;
public class Config {
public static final boolean LOGD = false;
}
| BoD/vtail | src/main/java/org/jraf/vtail/misc/Config.java | Java | gpl-3.0 | 1,043 |
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class Frmwe
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.CmbMon = New System.Windows.Forms.ComboBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.CmbYear = New System.Windows.Forms.ComboBox()
Me.Label15 = New System.Windows.Forms.Label()
Me.ComboBox2 = New System.Windows.Forms.ComboBox()
Me.Label16 = New System.Windows.Forms.Label()
Me.TabControl2 = New System.Windows.Forms.TabControl()
Me.TabPage4 = New System.Windows.Forms.TabPage()
Me.ComboBox3 = New System.Windows.Forms.ComboBox()
Me.Button3 = New System.Windows.Forms.Button()
Me.Button4 = New System.Windows.Forms.Button()
Me.DataGridView2 = New System.Windows.Forms.DataGridView()
Me.TextBox7 = New System.Windows.Forms.TextBox()
Me.TextBox8 = New System.Windows.Forms.TextBox()
Me.TextBox9 = New System.Windows.Forms.TextBox()
Me.TextBox10 = New System.Windows.Forms.TextBox()
Me.TextBox11 = New System.Windows.Forms.TextBox()
Me.Label7 = New System.Windows.Forms.Label()
Me.Label10 = New System.Windows.Forms.Label()
Me.Label11 = New System.Windows.Forms.Label()
Me.Label12 = New System.Windows.Forms.Label()
Me.Label13 = New System.Windows.Forms.Label()
Me.Label14 = New System.Windows.Forms.Label()
Me.TabPage5 = New System.Windows.Forms.TabPage()
Me.ComboBox4 = New System.Windows.Forms.ComboBox()
Me.Button5 = New System.Windows.Forms.Button()
Me.Button6 = New System.Windows.Forms.Button()
Me.DataGridView3 = New System.Windows.Forms.DataGridView()
Me.TextBox13 = New System.Windows.Forms.TextBox()
Me.TextBox14 = New System.Windows.Forms.TextBox()
Me.TextBox15 = New System.Windows.Forms.TextBox()
Me.TextBox16 = New System.Windows.Forms.TextBox()
Me.TextBox17 = New System.Windows.Forms.TextBox()
Me.Label17 = New System.Windows.Forms.Label()
Me.Label18 = New System.Windows.Forms.Label()
Me.Label19 = New System.Windows.Forms.Label()
Me.Label20 = New System.Windows.Forms.Label()
Me.Label21 = New System.Windows.Forms.Label()
Me.Label22 = New System.Windows.Forms.Label()
Me.TabPage6 = New System.Windows.Forms.TabPage()
Me.Button7 = New System.Windows.Forms.Button()
Me.TextBox22 = New System.Windows.Forms.TextBox()
Me.TextBox24 = New System.Windows.Forms.TextBox()
Me.Label26 = New System.Windows.Forms.Label()
Me.Label28 = New System.Windows.Forms.Label()
Me.TabControl2.SuspendLayout()
Me.TabPage4.SuspendLayout()
CType(Me.DataGridView2, System.ComponentModel.ISupportInitialize).BeginInit()
Me.TabPage5.SuspendLayout()
CType(Me.DataGridView3, System.ComponentModel.ISupportInitialize).BeginInit()
Me.TabPage6.SuspendLayout()
Me.SuspendLayout()
'
'CmbMon
'
Me.CmbMon.FormattingEnabled = True
Me.CmbMon.Location = New System.Drawing.Point(252, 14)
Me.CmbMon.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.CmbMon.Name = "CmbMon"
Me.CmbMon.Size = New System.Drawing.Size(140, 34)
Me.CmbMon.TabIndex = 2
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(197, 17)
Me.Label1.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(47, 26)
Me.Label1.TabIndex = 3
Me.Label1.Text = "เดือน :"
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label2.Location = New System.Drawing.Point(439, 17)
Me.Label2.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(27, 26)
Me.Label2.TabIndex = 5
Me.Label2.Text = "ปี :"
'
'CmbYear
'
Me.CmbYear.FormattingEnabled = True
Me.CmbYear.Location = New System.Drawing.Point(474, 14)
Me.CmbYear.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.CmbYear.Name = "CmbYear"
Me.CmbYear.Size = New System.Drawing.Size(140, 34)
Me.CmbYear.TabIndex = 4
'
'Label15
'
Me.Label15.AutoSize = True
Me.Label15.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label15.Location = New System.Drawing.Point(197, 17)
Me.Label15.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label15.Name = "Label15"
Me.Label15.Size = New System.Drawing.Size(47, 26)
Me.Label15.TabIndex = 3
Me.Label15.Text = "เดือน :"
'
'ComboBox2
'
Me.ComboBox2.FormattingEnabled = True
Me.ComboBox2.Location = New System.Drawing.Point(474, 14)
Me.ComboBox2.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.ComboBox2.Name = "ComboBox2"
Me.ComboBox2.Size = New System.Drawing.Size(140, 34)
Me.ComboBox2.TabIndex = 4
'
'Label16
'
Me.Label16.AutoSize = True
Me.Label16.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label16.Location = New System.Drawing.Point(439, 17)
Me.Label16.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label16.Name = "Label16"
Me.Label16.Size = New System.Drawing.Size(27, 26)
Me.Label16.TabIndex = 5
Me.Label16.Text = "ปี :"
'
'TabControl2
'
Me.TabControl2.Controls.Add(Me.TabPage4)
Me.TabControl2.Controls.Add(Me.TabPage5)
Me.TabControl2.Controls.Add(Me.TabPage6)
Me.TabControl2.Location = New System.Drawing.Point(19, 58)
Me.TabControl2.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.TabControl2.Name = "TabControl2"
Me.TabControl2.Padding = New System.Drawing.Point(50, 3)
Me.TabControl2.SelectedIndex = 0
Me.TabControl2.Size = New System.Drawing.Size(798, 500)
Me.TabControl2.TabIndex = 6
'
'TabPage4
'
Me.TabPage4.Controls.Add(Me.ComboBox3)
Me.TabPage4.Controls.Add(Me.Button3)
Me.TabPage4.Controls.Add(Me.Button4)
Me.TabPage4.Controls.Add(Me.DataGridView2)
Me.TabPage4.Controls.Add(Me.TextBox7)
Me.TabPage4.Controls.Add(Me.TextBox8)
Me.TabPage4.Controls.Add(Me.TextBox9)
Me.TabPage4.Controls.Add(Me.TextBox10)
Me.TabPage4.Controls.Add(Me.TextBox11)
Me.TabPage4.Controls.Add(Me.Label7)
Me.TabPage4.Controls.Add(Me.Label10)
Me.TabPage4.Controls.Add(Me.Label11)
Me.TabPage4.Controls.Add(Me.Label12)
Me.TabPage4.Controls.Add(Me.Label13)
Me.TabPage4.Controls.Add(Me.Label14)
Me.TabPage4.Location = New System.Drawing.Point(4, 35)
Me.TabPage4.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.TabPage4.Name = "TabPage4"
Me.TabPage4.Padding = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.TabPage4.Size = New System.Drawing.Size(790, 461)
Me.TabPage4.TabIndex = 0
Me.TabPage4.Text = "ค่าน้ำ"
Me.TabPage4.UseVisualStyleBackColor = True
'
'ComboBox3
'
Me.ComboBox3.FormattingEnabled = True
Me.ComboBox3.Location = New System.Drawing.Point(129, 11)
Me.ComboBox3.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.ComboBox3.Name = "ComboBox3"
Me.ComboBox3.Size = New System.Drawing.Size(229, 34)
Me.ComboBox3.TabIndex = 6
'
'Button3
'
Me.Button3.BackColor = System.Drawing.Color.Snow
Me.Button3.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(222, Byte))
Me.Button3.Location = New System.Drawing.Point(660, 409)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(103, 37)
Me.Button3.TabIndex = 272
Me.Button3.Text = "บันทึก"
Me.Button3.UseVisualStyleBackColor = False
'
'Button4
'
Me.Button4.BackColor = System.Drawing.Color.Snow
Me.Button4.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(222, Byte))
Me.Button4.Location = New System.Drawing.Point(551, 409)
Me.Button4.Name = "Button4"
Me.Button4.Size = New System.Drawing.Size(103, 37)
Me.Button4.TabIndex = 271
Me.Button4.Text = "ลบข้อมูลค่าน้ำ"
Me.Button4.UseVisualStyleBackColor = False
'
'DataGridView2
'
Me.DataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.DataGridView2.Location = New System.Drawing.Point(21, 138)
Me.DataGridView2.Name = "DataGridView2"
Me.DataGridView2.Size = New System.Drawing.Size(742, 265)
Me.DataGridView2.TabIndex = 21
'
'TextBox7
'
Me.TextBox7.Location = New System.Drawing.Point(534, 89)
Me.TextBox7.Name = "TextBox7"
Me.TextBox7.Size = New System.Drawing.Size(229, 33)
Me.TextBox7.TabIndex = 20
'
'TextBox8
'
Me.TextBox8.Location = New System.Drawing.Point(129, 89)
Me.TextBox8.Name = "TextBox8"
Me.TextBox8.Size = New System.Drawing.Size(229, 33)
Me.TextBox8.TabIndex = 19
'
'TextBox9
'
Me.TextBox9.Location = New System.Drawing.Point(534, 50)
Me.TextBox9.Name = "TextBox9"
Me.TextBox9.Size = New System.Drawing.Size(229, 33)
Me.TextBox9.TabIndex = 18
'
'TextBox10
'
Me.TextBox10.Location = New System.Drawing.Point(129, 50)
Me.TextBox10.Name = "TextBox10"
Me.TextBox10.Size = New System.Drawing.Size(229, 33)
Me.TextBox10.TabIndex = 17
'
'TextBox11
'
Me.TextBox11.Location = New System.Drawing.Point(534, 11)
Me.TextBox11.Name = "TextBox11"
Me.TextBox11.Size = New System.Drawing.Size(229, 33)
Me.TextBox11.TabIndex = 16
'
'Label7
'
Me.Label7.AutoSize = True
Me.Label7.BackColor = System.Drawing.Color.White
Me.Label7.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label7.Location = New System.Drawing.Point(421, 53)
Me.Label7.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label7.Name = "Label7"
Me.Label7.Size = New System.Drawing.Size(109, 26)
Me.Label7.TabIndex = 14
Me.Label7.Text = "หน่วยน้ำครั้งหลัง :"
'
'Label10
'
Me.Label10.AutoSize = True
Me.Label10.BackColor = System.Drawing.Color.White
Me.Label10.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label10.Location = New System.Drawing.Point(16, 92)
Me.Label10.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label10.Name = "Label10"
Me.Label10.Size = New System.Drawing.Size(88, 26)
Me.Label10.TabIndex = 13
Me.Label10.Text = "จำนวนหน่วย :"
'
'Label11
'
Me.Label11.AutoSize = True
Me.Label11.BackColor = System.Drawing.Color.White
Me.Label11.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label11.Location = New System.Drawing.Point(421, 92)
Me.Label11.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label11.Name = "Label11"
Me.Label11.Size = New System.Drawing.Size(64, 26)
Me.Label11.TabIndex = 12
Me.Label11.Text = "ยอดรวม :"
'
'Label12
'
Me.Label12.AutoSize = True
Me.Label12.BackColor = System.Drawing.Color.White
Me.Label12.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label12.Location = New System.Drawing.Point(16, 53)
Me.Label12.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label12.Name = "Label12"
Me.Label12.Size = New System.Drawing.Size(110, 26)
Me.Label12.TabIndex = 11
Me.Label12.Text = "หน่วยน้ำครั้งก่อน :"
'
'Label13
'
Me.Label13.AutoSize = True
Me.Label13.BackColor = System.Drawing.Color.White
Me.Label13.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label13.Location = New System.Drawing.Point(421, 14)
Me.Label13.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label13.Name = "Label13"
Me.Label13.Size = New System.Drawing.Size(93, 26)
Me.Label13.TabIndex = 7
Me.Label13.Text = "ค่าน้ำหน่วยละ :"
'
'Label14
'
Me.Label14.AutoSize = True
Me.Label14.BackColor = System.Drawing.Color.White
Me.Label14.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label14.Location = New System.Drawing.Point(16, 14)
Me.Label14.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label14.Name = "Label14"
Me.Label14.Size = New System.Drawing.Size(70, 26)
Me.Label14.TabIndex = 6
Me.Label14.Text = "เลขที่ห้อง :"
'
'TabPage5
'
Me.TabPage5.Controls.Add(Me.ComboBox4)
Me.TabPage5.Controls.Add(Me.Button5)
Me.TabPage5.Controls.Add(Me.Button6)
Me.TabPage5.Controls.Add(Me.DataGridView3)
Me.TabPage5.Controls.Add(Me.TextBox13)
Me.TabPage5.Controls.Add(Me.TextBox14)
Me.TabPage5.Controls.Add(Me.TextBox15)
Me.TabPage5.Controls.Add(Me.TextBox16)
Me.TabPage5.Controls.Add(Me.TextBox17)
Me.TabPage5.Controls.Add(Me.Label17)
Me.TabPage5.Controls.Add(Me.Label18)
Me.TabPage5.Controls.Add(Me.Label19)
Me.TabPage5.Controls.Add(Me.Label20)
Me.TabPage5.Controls.Add(Me.Label21)
Me.TabPage5.Controls.Add(Me.Label22)
Me.TabPage5.Location = New System.Drawing.Point(4, 35)
Me.TabPage5.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.TabPage5.Name = "TabPage5"
Me.TabPage5.Padding = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.TabPage5.Size = New System.Drawing.Size(790, 461)
Me.TabPage5.TabIndex = 1
Me.TabPage5.Text = "ค่าไฟ"
Me.TabPage5.UseVisualStyleBackColor = True
'
'ComboBox4
'
Me.ComboBox4.FormattingEnabled = True
Me.ComboBox4.Location = New System.Drawing.Point(129, 11)
Me.ComboBox4.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.ComboBox4.Name = "ComboBox4"
Me.ComboBox4.Size = New System.Drawing.Size(229, 34)
Me.ComboBox4.TabIndex = 288
'
'Button5
'
Me.Button5.BackColor = System.Drawing.Color.Snow
Me.Button5.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(222, Byte))
Me.Button5.Location = New System.Drawing.Point(660, 411)
Me.Button5.Name = "Button5"
Me.Button5.Size = New System.Drawing.Size(103, 37)
Me.Button5.TabIndex = 287
Me.Button5.Text = "บันทึก"
Me.Button5.UseVisualStyleBackColor = False
'
'Button6
'
Me.Button6.BackColor = System.Drawing.Color.Snow
Me.Button6.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(222, Byte))
Me.Button6.Location = New System.Drawing.Point(551, 411)
Me.Button6.Name = "Button6"
Me.Button6.Size = New System.Drawing.Size(103, 37)
Me.Button6.TabIndex = 286
Me.Button6.Text = "ลบข้อมูลค่าไฟ"
Me.Button6.UseVisualStyleBackColor = False
'
'DataGridView3
'
Me.DataGridView3.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.DataGridView3.Location = New System.Drawing.Point(21, 138)
Me.DataGridView3.Name = "DataGridView3"
Me.DataGridView3.Size = New System.Drawing.Size(742, 265)
Me.DataGridView3.TabIndex = 285
'
'TextBox13
'
Me.TextBox13.Location = New System.Drawing.Point(534, 91)
Me.TextBox13.Name = "TextBox13"
Me.TextBox13.Size = New System.Drawing.Size(229, 33)
Me.TextBox13.TabIndex = 284
'
'TextBox14
'
Me.TextBox14.Location = New System.Drawing.Point(129, 89)
Me.TextBox14.Name = "TextBox14"
Me.TextBox14.Size = New System.Drawing.Size(229, 33)
Me.TextBox14.TabIndex = 283
'
'TextBox15
'
Me.TextBox15.Location = New System.Drawing.Point(534, 50)
Me.TextBox15.Name = "TextBox15"
Me.TextBox15.Size = New System.Drawing.Size(229, 33)
Me.TextBox15.TabIndex = 282
'
'TextBox16
'
Me.TextBox16.Location = New System.Drawing.Point(129, 50)
Me.TextBox16.Name = "TextBox16"
Me.TextBox16.Size = New System.Drawing.Size(229, 33)
Me.TextBox16.TabIndex = 281
'
'TextBox17
'
Me.TextBox17.Location = New System.Drawing.Point(534, 11)
Me.TextBox17.Name = "TextBox17"
Me.TextBox17.Size = New System.Drawing.Size(229, 33)
Me.TextBox17.TabIndex = 280
'
'Label17
'
Me.Label17.AutoSize = True
Me.Label17.BackColor = System.Drawing.Color.White
Me.Label17.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label17.Location = New System.Drawing.Point(421, 55)
Me.Label17.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label17.Name = "Label17"
Me.Label17.Size = New System.Drawing.Size(111, 26)
Me.Label17.TabIndex = 278
Me.Label17.Text = "หน่วยไฟครั้งหลัง :"
'
'Label18
'
Me.Label18.AutoSize = True
Me.Label18.BackColor = System.Drawing.Color.White
Me.Label18.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label18.Location = New System.Drawing.Point(16, 94)
Me.Label18.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label18.Name = "Label18"
Me.Label18.Size = New System.Drawing.Size(88, 26)
Me.Label18.TabIndex = 277
Me.Label18.Text = "จำนวนหน่วย :"
'
'Label19
'
Me.Label19.AutoSize = True
Me.Label19.BackColor = System.Drawing.Color.White
Me.Label19.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label19.Location = New System.Drawing.Point(421, 92)
Me.Label19.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label19.Name = "Label19"
Me.Label19.Size = New System.Drawing.Size(64, 26)
Me.Label19.TabIndex = 276
Me.Label19.Text = "ยอดรวม :"
'
'Label20
'
Me.Label20.AutoSize = True
Me.Label20.BackColor = System.Drawing.Color.White
Me.Label20.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label20.Location = New System.Drawing.Point(16, 55)
Me.Label20.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label20.Name = "Label20"
Me.Label20.Size = New System.Drawing.Size(112, 26)
Me.Label20.TabIndex = 275
Me.Label20.Text = "หน่วยไฟครั้งก่อน :"
'
'Label21
'
Me.Label21.AutoSize = True
Me.Label21.BackColor = System.Drawing.Color.White
Me.Label21.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label21.Location = New System.Drawing.Point(421, 16)
Me.Label21.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label21.Name = "Label21"
Me.Label21.Size = New System.Drawing.Size(95, 26)
Me.Label21.TabIndex = 274
Me.Label21.Text = "ค่าไฟหน่วยละ :"
'
'Label22
'
Me.Label22.AutoSize = True
Me.Label22.BackColor = System.Drawing.Color.White
Me.Label22.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label22.Location = New System.Drawing.Point(16, 16)
Me.Label22.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label22.Name = "Label22"
Me.Label22.Size = New System.Drawing.Size(70, 26)
Me.Label22.TabIndex = 273
Me.Label22.Text = "เลขที่ห้อง :"
'
'TabPage6
'
Me.TabPage6.Controls.Add(Me.Button7)
Me.TabPage6.Controls.Add(Me.TextBox22)
Me.TabPage6.Controls.Add(Me.TextBox24)
Me.TabPage6.Controls.Add(Me.Label26)
Me.TabPage6.Controls.Add(Me.Label28)
Me.TabPage6.Location = New System.Drawing.Point(4, 35)
Me.TabPage6.Name = "TabPage6"
Me.TabPage6.Padding = New System.Windows.Forms.Padding(3)
Me.TabPage6.Size = New System.Drawing.Size(790, 461)
Me.TabPage6.TabIndex = 2
Me.TabPage6.Text = "หน่วยค่าน้ำ/ ค่าไฟฟ้า"
Me.TabPage6.UseVisualStyleBackColor = True
'
'Button7
'
Me.Button7.BackColor = System.Drawing.Color.Snow
Me.Button7.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(222, Byte))
Me.Button7.Location = New System.Drawing.Point(668, 411)
Me.Button7.Name = "Button7"
Me.Button7.Size = New System.Drawing.Size(103, 37)
Me.Button7.TabIndex = 287
Me.Button7.Text = "บันทึก"
Me.Button7.UseVisualStyleBackColor = False
'
'TextBox22
'
Me.TextBox22.Location = New System.Drawing.Point(137, 50)
Me.TextBox22.Name = "TextBox22"
Me.TextBox22.Size = New System.Drawing.Size(229, 33)
Me.TextBox22.TabIndex = 281
'
'TextBox24
'
Me.TextBox24.Location = New System.Drawing.Point(137, 11)
Me.TextBox24.Name = "TextBox24"
Me.TextBox24.Size = New System.Drawing.Size(229, 33)
Me.TextBox24.TabIndex = 279
'
'Label26
'
Me.Label26.AutoSize = True
Me.Label26.BackColor = System.Drawing.Color.White
Me.Label26.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label26.Location = New System.Drawing.Point(16, 53)
Me.Label26.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label26.Name = "Label26"
Me.Label26.Size = New System.Drawing.Size(110, 26)
Me.Label26.TabIndex = 275
Me.Label26.Text = "ค่าไฟฟ้าหน่วยละ :"
'
'Label28
'
Me.Label28.AutoSize = True
Me.Label28.BackColor = System.Drawing.Color.White
Me.Label28.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label28.Location = New System.Drawing.Point(16, 14)
Me.Label28.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0)
Me.Label28.Name = "Label28"
Me.Label28.Size = New System.Drawing.Size(93, 26)
Me.Label28.TabIndex = 273
Me.Label28.Text = "ค่าน้ำหน่วยละ :"
'
'Frmwe
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 26.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(830, 602)
Me.Controls.Add(Me.TabControl2)
Me.Controls.Add(Me.Label16)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.ComboBox2)
Me.Controls.Add(Me.CmbYear)
Me.Controls.Add(Me.Label15)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.CmbMon)
Me.Font = New System.Drawing.Font("Angsana New", 14.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(222, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.Margin = New System.Windows.Forms.Padding(4, 5, 4, 5)
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "Frmwe"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "บันทึกค่าน้ำ ค่าไฟฟ้า"
Me.TabControl2.ResumeLayout(False)
Me.TabPage4.ResumeLayout(False)
Me.TabPage4.PerformLayout()
CType(Me.DataGridView2, System.ComponentModel.ISupportInitialize).EndInit()
Me.TabPage5.ResumeLayout(False)
Me.TabPage5.PerformLayout()
CType(Me.DataGridView3, System.ComponentModel.ISupportInitialize).EndInit()
Me.TabPage6.ResumeLayout(False)
Me.TabPage6.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents CmbMon As ComboBox
Friend WithEvents Label1 As Label
Friend WithEvents Label2 As Label
Friend WithEvents CmbYear As ComboBox
Friend WithEvents Label15 As Label
Friend WithEvents ComboBox2 As ComboBox
Friend WithEvents Label16 As Label
Friend WithEvents TabControl2 As TabControl
Friend WithEvents TabPage4 As TabPage
Friend WithEvents ComboBox3 As ComboBox
Friend WithEvents Button3 As Button
Friend WithEvents Button4 As Button
Friend WithEvents DataGridView2 As DataGridView
Friend WithEvents TextBox7 As TextBox
Friend WithEvents TextBox8 As TextBox
Friend WithEvents TextBox9 As TextBox
Friend WithEvents TextBox10 As TextBox
Friend WithEvents TextBox11 As TextBox
Friend WithEvents Label7 As Label
Friend WithEvents Label10 As Label
Friend WithEvents Label11 As Label
Friend WithEvents Label12 As Label
Friend WithEvents Label13 As Label
Friend WithEvents Label14 As Label
Friend WithEvents TabPage5 As TabPage
Friend WithEvents ComboBox4 As ComboBox
Friend WithEvents Button5 As Button
Friend WithEvents Button6 As Button
Friend WithEvents DataGridView3 As DataGridView
Friend WithEvents TextBox13 As TextBox
Friend WithEvents TextBox14 As TextBox
Friend WithEvents TextBox15 As TextBox
Friend WithEvents TextBox16 As TextBox
Friend WithEvents TextBox17 As TextBox
Friend WithEvents Label17 As Label
Friend WithEvents Label18 As Label
Friend WithEvents Label19 As Label
Friend WithEvents Label20 As Label
Friend WithEvents Label21 As Label
Friend WithEvents Label22 As Label
Friend WithEvents TabPage6 As TabPage
Friend WithEvents Button7 As Button
Friend WithEvents TextBox22 As TextBox
Friend WithEvents TextBox24 As TextBox
Friend WithEvents Label26 As Label
Friend WithEvents Label28 As Label
End Class
| manthanapui/PROJECTT | Frmwe.Designer.vb | Visual Basic | gpl-3.0 | 30,480 |
// $Id: ClassGenerationDialog.java 16603 2009-01-14 20:49:03Z thn $
// Copyright (c) 1996-2008 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.generator.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import org.apache.log4j.Logger;
import org.argouml.i18n.Translator;
import org.argouml.model.Model;
import org.argouml.notation.Notation;
import org.argouml.uml.generator.CodeGenerator;
import org.argouml.uml.generator.GeneratorManager;
import org.argouml.uml.generator.Language;
import org.argouml.util.ArgoDialog;
import org.tigris.swidgets.Dialog;
/**
* The dialog that starts the generation of classes.
*/
public class ClassGenerationDialog
extends ArgoDialog
implements ActionListener {
private static final String SOURCE_LANGUAGE_TAG = "src_lang";
/**
* Logger.
*/
private static final Logger LOG =
Logger.getLogger(ClassGenerationDialog.class);
private TableModelClassChecks classTableModel;
private boolean isPathInModel;
private List<Language> languages;
private JTable classTable;
private JComboBox outputDirectoryComboBox;
/**
* Used to select the next language column in case
* the "Select All" button is pressed.
*/
private int languageHistory;
/**
* Constructor.
*
* @param nodes The UML elements, typically classifiers, to generate.
*/
public ClassGenerationDialog(List<Object> nodes) {
this(nodes, false);
}
/**
* Constructor.
*
* @param nodes The UML elements, typically classifiers, to generate.
* @param inModel <code>true</code> if the path is in the model.
* TODO: Correct?
*/
public ClassGenerationDialog(List<Object> nodes, boolean inModel) {
super(
Translator.localize("dialog.title.generate-classes"),
Dialog.OK_CANCEL_OPTION,
true);
isPathInModel = inModel;
buildLanguages();
JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
// Class Table
classTableModel = new TableModelClassChecks();
classTableModel.setTarget(nodes);
classTable = new JTable(classTableModel);
classTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
classTable.setShowVerticalLines(false);
if (languages.size() <= 1) {
classTable.setTableHeader(null);
}
setClassTableColumnWidths();
classTable.setPreferredScrollableViewportSize(new Dimension(300, 300));
// Select Buttons
JButton selectAllButton = new JButton();
nameButton(selectAllButton, "button.select-all");
selectAllButton.addActionListener(new ActionListener() {
/*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
classTableModel.setAllChecks(true);
classTable.repaint();
}
});
JButton selectNoneButton = new JButton();
nameButton(selectNoneButton, "button.select-none");
selectNoneButton.addActionListener(new ActionListener() {
/*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
classTableModel.setAllChecks(false);
classTable.repaint();
}
});
JPanel selectPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
selectPanel.setBorder(BorderFactory.createEmptyBorder(8, 0, 0, 0));
JPanel selectButtons = new JPanel(new BorderLayout(5, 0));
selectButtons.add(selectAllButton, BorderLayout.CENTER);
selectButtons.add(selectNoneButton, BorderLayout.EAST);
selectPanel.add(selectButtons);
JPanel centerPanel = new JPanel(new BorderLayout(0, 2));
centerPanel.add(new JLabel(Translator.localize(
"label.available-classes")), BorderLayout.NORTH);
centerPanel.add(new JScrollPane(classTable), BorderLayout.CENTER);
centerPanel.add(selectPanel, BorderLayout.SOUTH);
contentPanel.add(centerPanel, BorderLayout.CENTER);
// Output Directory
outputDirectoryComboBox =
new JComboBox(getClasspathEntries().toArray());
JButton browseButton = new JButton();
nameButton(browseButton, "button.browse");
browseButton.setText(browseButton.getText() + "...");
browseButton.addActionListener(new ActionListener() {
/*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
doBrowse();
}
});
JPanel southPanel = new JPanel(new BorderLayout(0, 2));
if (!inModel) {
outputDirectoryComboBox.setEditable(true);
JPanel outputPanel = new JPanel(new BorderLayout(5, 0));
outputPanel.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(
Translator.localize("label.output-directory")),
BorderFactory.createEmptyBorder(2, 5, 5, 5)));
outputPanel.add(outputDirectoryComboBox, BorderLayout.CENTER);
outputPanel.add(browseButton, BorderLayout.EAST);
southPanel.add(outputPanel, BorderLayout.NORTH);
}
// Compile Checkbox
//_compileCheckBox = new JCheckBox();
//nameButton(_compileCheckBox, "checkbox.compile-generated-source");
// TODO: Implement the compile feature. For now, disable the checkbox.
//_compileCheckBox.setEnabled(false);
//southPanel.add(_compileCheckBox, BorderLayout.SOUTH);
contentPanel.add(southPanel, BorderLayout.SOUTH);
setContent(contentPanel);
// TODO: Get saved default directory
// outputDirectoryComboBox.getModel().setSelectedItem(savedDir);
}
/*
* @see org.tigris.swidgets.Dialog#nameButtons()
*/
@Override
protected void nameButtons() {
super.nameButtons();
nameButton(getOkButton(), "button.generate");
}
private void setClassTableColumnWidths() {
TableColumn column = null;
Component c = null;
int width = 0;
for (int i = 0; i < classTable.getColumnCount() - 1; ++i) {
column = classTable.getColumnModel().getColumn(i);
width = 30;
JTableHeader header = classTable.getTableHeader();
if (header != null) {
c =
header.getDefaultRenderer().getTableCellRendererComponent(
classTable,
column.getHeaderValue(),
false,
false,
0,
0);
width = Math.max(c.getPreferredSize().width + 8, width);
}
column.setPreferredWidth(width);
column.setWidth(width);
column.setMinWidth(width);
column.setMaxWidth(width);
}
}
private void buildLanguages() {
languages = new ArrayList<Language>(
GeneratorManager.getInstance().getLanguages());
}
private static Collection<String> getClasspathEntries() {
String classpath = System.getProperty("java.class.path");
Collection<String> entries = new TreeSet<String>();
// TODO: What does the output directory have to do with the class path?
// Project p = ProjectManager.getManager().getCurrentProject();
// entries.add(p.getProjectSettings().getGenerationOutputDir());
final String pathSep = System.getProperty("path.separator");
StringTokenizer allEntries = new StringTokenizer(classpath, pathSep);
while (allEntries.hasMoreElements()) {
String entry = allEntries.nextToken();
if (!entry.toLowerCase().endsWith(".jar")
&& !entry.toLowerCase().endsWith(".zip")) {
entries.add(entry);
}
}
return entries;
}
/*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
// Generate Button --------------------------------------
if (e.getSource() == getOkButton()) {
String path = null;
// TODO: Get default output directory from user settings
// Project p = ProjectManager.getManager().getCurrentProject();
// p.getProjectSettings().setGenerationOutputDir(path);
List<String>[] fileNames = new List[languages.size()];
for (int i = 0; i < languages.size(); i++) {
fileNames[i] = new ArrayList<String>();
Language language = languages.get(i);
GeneratorManager genMan = GeneratorManager.getInstance();
CodeGenerator generator = genMan.getGenerator(language);
Set nodes = classTableModel.getChecked(language);
if (!isPathInModel) {
path =
((String) outputDirectoryComboBox.getModel()
.getSelectedItem());
if (path != null) {
path = path.trim();
if (path.length() > 0) {
Collection<String> files =
generator.generateFiles(nodes, path, false);
for (String filename : files) {
fileNames[i].add(
path + CodeGenerator.FILE_SEPARATOR
+ filename);
}
}
}
} else {
// classify nodes by base path
Map<String, Set<Object>> nodesPerPath =
new HashMap<String, Set<Object>>();
for (Object node : nodes) {
if (!Model.getFacade().isAClassifier(node)) {
continue;
}
path = GeneratorManager.getCodePath(node);
if (path == null) {
Object parent =
Model.getFacade().getNamespace(node);
while (parent != null) {
path = GeneratorManager.getCodePath(parent);
if (path != null) {
break;
}
parent =
Model.getFacade().getNamespace(parent);
}
}
if (path != null) {
final String fileSep = CodeGenerator.FILE_SEPARATOR;
if (path.endsWith(fileSep)) { // remove trailing /
path =
path.substring(0, path.length()
- fileSep.length());
}
Set<Object> np = nodesPerPath.get(path);
if (np == null) {
np = new HashSet<Object>();
nodesPerPath.put(path, np);
}
np.add(node);
saveLanguage(node, language);
}
} // end for (all nodes)
// generate the files
for (Map.Entry entry : nodesPerPath.entrySet()) {
String basepath = (String) entry.getKey();
Set nodeColl = (Set) entry.getValue();
// TODO: the last argument (recursive flag) should be a
// selectable option
Collection<String> files =
generator.generateFiles(nodeColl, basepath, false);
for (String filename : files) {
fileNames[i].add(basepath
+ CodeGenerator.FILE_SEPARATOR
+ filename);
}
}
} // end if (!isPathInModel) .. else
} // end for (all languages)
// TODO: do something with the generated list fileNames,
// for example, show it to the user in a dialog box.
}
}
/**
* Save the source language in the model.
*
* TODO: Support multiple languages now that we have UML 1.4
* tagged values.
* @param node
* @param language
*/
private void saveLanguage(Object node, Language language) {
Object taggedValue =
Model.getFacade().getTaggedValue(node, SOURCE_LANGUAGE_TAG);
if (taggedValue != null) {
String savedLang = Model.getFacade().getValueOfTag(taggedValue);
if (!language.getName().equals(savedLang)) {
Model.getExtensionMechanismsHelper().setValueOfTag(
taggedValue, language.getName());
}
} else {
taggedValue =
Model.getExtensionMechanismsFactory().buildTaggedValue(
SOURCE_LANGUAGE_TAG, language.getName());
Model.getExtensionMechanismsHelper().addTaggedValue(
node, taggedValue);
}
}
private void doBrowse() {
try {
// Show Filechooser to select OutputDirectory
JFileChooser chooser =
new JFileChooser(
(String) outputDirectoryComboBox
.getModel()
.getSelectedItem());
if (chooser == null) {
chooser = new JFileChooser();
}
chooser.setFileHidingEnabled(true);
chooser.setMultiSelectionEnabled(false);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogTitle(Translator.localize(
"dialog.generation.chooser.choose-output-dir"));
chooser.showDialog(this, Translator.localize(
"dialog.generation.chooser.approve-button-text"));
if (!"".equals(chooser.getSelectedFile().getPath())) {
String path = chooser.getSelectedFile().getPath();
outputDirectoryComboBox.addItem(path);
outputDirectoryComboBox.getModel().setSelectedItem(path);
} // else ignore
} catch (Exception userPressedCancel) {
// TODO: How does the pressed cancel become a java.lang.Exception?
LOG.info("user pressed cancel");
}
}
class TableModelClassChecks extends AbstractTableModel {
/**
* List of all possible UML elements for which to generate code. The
* Object typed objects are actually UML Elements, but we don't have a
* visible type for that.
*/
private List<Object> classes;
/**
* Array of sets of UML elements that the user has selected. One set
* per language. The Object typed objects are actually UML Elements,
* but we don't have a visible type for that.
*/
private Set<Object>[] checked;
/**
* Constructor.
*/
public TableModelClassChecks() {
}
/**
* Set the target.
*
* @param nodes list of classes
*/
public void setTarget(List<Object> nodes) {
classes = nodes;
checked = new Set[getLanguagesCount()];
for (int j = 0; j < getLanguagesCount(); j++) {
// Doesn't really matter what set we use.
checked[j] = new HashSet<Object>();
}
for (Object cls : classes) {
for (int j = 0; j < getLanguagesCount(); j++) {
if (isSupposedToBeGeneratedAsLanguage(
languages.get(j), cls)) {
checked[j].add(cls);
} else if ((languages.get(j)).getName().equals(
Notation.getConfiguredNotation()
.getConfigurationValue())) {
checked[j].add(cls);
}
}
}
fireTableStructureChanged();
getOkButton().setEnabled(classes.size() > 0
&& getChecked().size() > 0);
}
private boolean isSupposedToBeGeneratedAsLanguage(
Language lang,
Object cls) {
if (lang == null || cls == null) {
return false;
}
Object taggedValue =
Model.getFacade().getTaggedValue(cls, SOURCE_LANGUAGE_TAG);
if (taggedValue == null) {
return false;
}
String savedLang = Model.getFacade().getValueOfTag(taggedValue);
return (lang.getName().equals(savedLang));
}
private int getLanguagesCount() {
if (languages == null) {
return 0;
}
return languages.size();
}
/**
* Return the set of elements which are selected for the given language.
* @param lang the language
* @return a set of UML elements
*/
public Set<Object> getChecked(Language lang) {
int index = languages.indexOf(lang);
if (index == -1) {
return Collections.emptySet();
}
return checked[index];
}
/**
* All checked classes.
*
* @return The union of all languages as a {@link Set}.
*/
public Set<Object> getChecked() {
Set<Object> union = new HashSet<Object>();
for (int i = 0; i < getLanguagesCount(); i++) {
union.addAll(checked[i]);
}
return union;
}
////////////////
// TableModel implementation
/*
* @see javax.swing.table.TableModel#getColumnCount()
*/
public int getColumnCount() {
return 1 + getLanguagesCount();
}
/*
* @see javax.swing.table.TableModel#getColumnName(int)
*/
@Override
public String getColumnName(int c) {
if (c >= 0 && c < getLanguagesCount()) {
return languages.get(c).getName();
} else if (c == getLanguagesCount()) {
return "Class Name";
}
return "XXX";
}
/*
* @see javax.swing.table.TableModel#getColumnClass(int)
*/
public Class getColumnClass(int c) {
if (c >= 0 && c < getLanguagesCount()) {
return Boolean.class;
} else if (c == getLanguagesCount()) {
return String.class;
}
return String.class;
}
/*
* @see javax.swing.table.TableModel#isCellEditable(int, int)
*/
@Override
public boolean isCellEditable(int row, int col) {
Object cls = classes.get(row);
if (col == getLanguagesCount()) {
return false;
}
if (!(Model.getFacade().getName(cls).length() > 0)) {
return false;
}
if (col >= 0 && col < getLanguagesCount()) {
return true;
}
return false;
}
/*
* @see javax.swing.table.TableModel#getRowCount()
*/
public int getRowCount() {
if (classes == null) {
return 0;
}
return classes.size();
}
/*
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int row, int col) {
Object cls = classes.get(row);
if (col == getLanguagesCount()) {
String name = Model.getFacade().getName(cls);
if (name.length() > 0) {
return name;
}
return "(anon)";
} else if (col >= 0 && col < getLanguagesCount()) {
if (checked[col].contains(cls)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
} else {
return "CC-r:" + row + " c:" + col;
}
}
/*
* @see javax.swing.table.TableModel#setValueAt(
* java.lang.Object, int, int)
*/
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == getLanguagesCount()) {
return;
}
if (columnIndex >= getColumnCount()) {
return;
}
if (!(aValue instanceof Boolean)) {
return;
}
boolean val = ((Boolean) aValue).booleanValue();
Object cls = classes.get(rowIndex);
if (columnIndex >= 0 && columnIndex < getLanguagesCount()) {
if (val) {
checked[columnIndex].add(cls);
} else {
checked[columnIndex].remove(cls);
}
}
if (val && !getOkButton().isEnabled()) {
getOkButton().setEnabled(true);
} else if (!val && getOkButton().isEnabled()
&& getChecked().size() == 0) {
getOkButton().setEnabled(false);
}
}
/**
* Sets or clears all checkmarks for the (next) language for
* all classes.
*
* @param value If false then all checkmarks are cleared for all
* languages.
* If true then all are cleared, except for one language column,
* these are all set.
*/
public void setAllChecks(boolean value) {
int rows = getRowCount();
int checks = getLanguagesCount();
if (rows == 0) {
return;
}
for (int i = 0; i < rows; ++i) {
Object cls = classes.get(i);
for (int j = 0; j < checks; ++j) {
if (value && (j == languageHistory)) {
checked[j].add(cls);
} else {
checked[j].remove(cls);
}
}
}
if (value) {
if (++languageHistory >= checks) {
languageHistory = 0;
}
}
getOkButton().setEnabled(value);
}
/**
* The UID.
*/
private static final long serialVersionUID = 6108214254680694765L;
} /* end class TableModelClassChecks */
/**
* The UID.
*/
private static final long serialVersionUID = -8897965616334156746L;
} /* end class ClassGenerationDialog */
| ckaestne/LEADT | workspace/argouml_diagrams/argouml-app/src/org/argouml/uml/generator/ui/ClassGenerationDialog.java | Java | gpl-3.0 | 26,409 |
/* Copyright 2009-2016 Francesco Biscani (bluescarni@gmail.com)
This file is part of the Piranha library.
The Piranha library is free software; you can redistribute it and/or modify
it under the terms of either:
* 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.
or
* 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.
or both in parallel, as here.
The Piranha 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.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the Piranha library. If not,
see https://www.gnu.org/licenses/. */
#include "../src/rational_function.hpp"
#define BOOST_TEST_MODULE rational_function_01_test
#include <boost/test/unit_test.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/vector.hpp>
#include <initializer_list>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include "../src/environment.hpp"
#include "../src/exceptions.hpp"
#include "../src/kronecker_monomial.hpp"
#include "../src/math.hpp"
#include "../src/monomial.hpp"
#include "../src/mp_integer.hpp"
#include "../src/mp_rational.hpp"
#include "../src/pow.hpp"
#include "../src/print_tex_coefficient.hpp"
#include "../src/real.hpp"
#include "../src/serialization.hpp"
#include "../src/symbol_set.hpp"
#include "../src/symbol.hpp"
#include "../src/type_traits.hpp"
using namespace piranha;
using key_types = boost::mpl::vector<k_monomial,monomial<unsigned char>,monomial<integer>>;
static std::mt19937 rng;
static const int ntrials = 200;
template <typename Poly>
inline static Poly rn_poly(const Poly &x, const Poly &y, const Poly &z, std::uniform_int_distribution<int> &dist)
{
int nterms = dist(rng);
Poly retval;
for (int i = 0; i < nterms; ++i) {
int m = dist(rng);
retval += m * (m % 2 ? 1 : -1 ) * x.pow(dist(rng)) * y.pow(dist(rng)) * z.pow(dist(rng));
}
return retval;
}
struct constructor_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
using q_type = typename r_type::q_type;
p_type x{"x"}, y{"y"}, z{"z"};
q_type xq{"x"}, yq{"y"}, zq{"z"};
// Standard constructors.
r_type r;
BOOST_CHECK(r.is_canonical());
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{5};
auto s = r;
BOOST_CHECK(s.is_canonical());
BOOST_CHECK_EQUAL(s.num(),5);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
// Check status of moved-from objects.
r_type t = std::move(s);
BOOST_CHECK(t.is_canonical());
BOOST_CHECK(!s.is_canonical());
BOOST_CHECK_EQUAL(t.num(),5);
BOOST_CHECK_EQUAL(t.den(),1);
BOOST_CHECK(t.num().get_symbol_set().size() == 0u);
BOOST_CHECK(t.den().get_symbol_set().size() == 0u);
BOOST_CHECK_EQUAL(s.num(),0);
BOOST_CHECK_EQUAL(s.den(),0);
BOOST_CHECK_THROW(s.canonicalise(),zero_division_error);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
// Revive.
s = t;
BOOST_CHECK(s.is_canonical());
BOOST_CHECK_EQUAL(s.num(),5);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
// Revive with move.
t = std::move(s);
BOOST_CHECK(!s.is_canonical());
BOOST_CHECK(t.is_canonical());
s = std::move(t);
BOOST_CHECK(!t.is_canonical());
BOOST_CHECK(s.is_canonical());
BOOST_CHECK_EQUAL(s.num(),5);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
BOOST_CHECK_EQUAL(t.num(),0);
BOOST_CHECK_EQUAL(t.den(),0);
BOOST_CHECK(t.num().get_symbol_set().size() == 0u);
BOOST_CHECK(t.den().get_symbol_set().size() == 0u);
// Unary ctors.
BOOST_CHECK((std::is_constructible<r_type,p_type>::value));
BOOST_CHECK((std::is_constructible<r_type,p_type &>::value));
BOOST_CHECK((std::is_constructible<r_type,p_type &&>::value));
BOOST_CHECK((std::is_constructible<r_type,q_type>::value));
BOOST_CHECK((std::is_constructible<r_type,q_type &>::value));
BOOST_CHECK((std::is_constructible<r_type,q_type &&>::value));
BOOST_CHECK((std::is_constructible<r_type,int>::value));
BOOST_CHECK((std::is_constructible<r_type,char &>::value));
BOOST_CHECK((std::is_constructible<r_type,const integer &>::value));
BOOST_CHECK((std::is_constructible<r_type,rational>::value));
BOOST_CHECK((std::is_constructible<r_type,const rational &>::value));
BOOST_CHECK((std::is_constructible<r_type,std::string>::value));
BOOST_CHECK((std::is_constructible<r_type,char *>::value));
BOOST_CHECK((std::is_constructible<r_type,const char *>::value));
BOOST_CHECK((!std::is_constructible<r_type,double>::value));
BOOST_CHECK((!std::is_constructible<r_type,const float>::value));
BOOST_CHECK((!std::is_constructible<r_type,real &&>::value));
// Ctor from ints.
r = r_type{0};
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{1u};
BOOST_CHECK_EQUAL(r.num(),1);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{-2_z};
BOOST_CHECK_EQUAL(r.num(),-2);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
// Ctor from string.
r = r_type{"x"};
BOOST_CHECK_EQUAL(r.num(),x);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 1u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{std::string("y")};
BOOST_CHECK_EQUAL(r.num(),y);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 1u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
// Ctor from p_type.
r = r_type{p_type{}};
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{x+2*y};
BOOST_CHECK_EQUAL(r.num(),x+2*y);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 2u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
// Ctor from rational.
r = r_type{0_q};
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{8/-12_q};
BOOST_CHECK_EQUAL(r.num(),-2);
BOOST_CHECK_EQUAL(r.den(),3);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
// Ctor from q_type.
r = r_type{q_type{}};
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{xq/3+2*yq};
BOOST_CHECK_EQUAL(r.num(),x+6*y);
BOOST_CHECK_EQUAL(r.den(),3);
BOOST_CHECK(r.num().get_symbol_set().size() == 2u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{xq+xq.pow(2)/2};
BOOST_CHECK_EQUAL(r.num(),2*x+x*x);
BOOST_CHECK_EQUAL(r.den(),2);
BOOST_CHECK(r.num().get_symbol_set().size() == 1u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
// Binary ctors.
BOOST_CHECK((std::is_constructible<r_type,r_type,r_type>::value));
BOOST_CHECK((std::is_constructible<r_type,const r_type,r_type &&>::value));
BOOST_CHECK((std::is_constructible<r_type,p_type,p_type>::value));
BOOST_CHECK((std::is_constructible<r_type,p_type,int>::value));
BOOST_CHECK((std::is_constructible<r_type,const int &,p_type>::value));
BOOST_CHECK((std::is_constructible<r_type,p_type &,p_type>::value));
BOOST_CHECK((std::is_constructible<r_type,p_type &&,const p_type &>::value));
BOOST_CHECK((std::is_constructible<r_type,q_type,q_type>::value));
BOOST_CHECK((std::is_constructible<r_type,q_type &,q_type>::value));
BOOST_CHECK((std::is_constructible<r_type,q_type &&,const q_type &>::value));
BOOST_CHECK((std::is_constructible<r_type,int,int>::value));
BOOST_CHECK((std::is_constructible<r_type,char &,char>::value));
BOOST_CHECK((std::is_constructible<r_type,const integer &,integer>::value));
BOOST_CHECK((std::is_constructible<r_type,rational, rational>::value));
BOOST_CHECK((std::is_constructible<r_type,const rational &, rational &&>::value));
BOOST_CHECK((std::is_constructible<r_type,std::string,std::string>::value));
BOOST_CHECK((std::is_constructible<r_type,std::string,int>::value));
BOOST_CHECK((std::is_constructible<r_type,q_type &&,std::string>::value));
BOOST_CHECK((std::is_constructible<r_type,std::string,std::string &>::value));
BOOST_CHECK((std::is_constructible<r_type,char *,char*>::value));
BOOST_CHECK((std::is_constructible<r_type,const char *,const char*>::value));
BOOST_CHECK((!std::is_constructible<r_type,double,double>::value));
BOOST_CHECK((!std::is_constructible<r_type,int,double>::value));
BOOST_CHECK((!std::is_constructible<r_type,double,rational>::value));
BOOST_CHECK((!std::is_constructible<r_type,const float,float>::value));
BOOST_CHECK((!std::is_constructible<r_type,real &&,real>::value));
// From ints.
r = r_type{4,-12};
BOOST_CHECK_EQUAL(r.num(),-1);
BOOST_CHECK_EQUAL(r.den(),3);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{0u,12u};
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
BOOST_CHECK_THROW((r = r_type{0_z,0_z}),zero_division_error);
BOOST_CHECK_THROW((r = r_type{1,0}),zero_division_error);
r = r_type{4,1};
BOOST_CHECK_EQUAL(r.num(),4);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
// From strings.
r = r_type{"x","x"};
BOOST_CHECK_EQUAL(r.num(),1);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 1u);
BOOST_CHECK(r.den().get_symbol_set().size() == 1u);
r = r_type{std::string("x"),std::string("y")};
BOOST_CHECK_EQUAL(r.num(),x);
BOOST_CHECK_EQUAL(r.den(),y);
BOOST_CHECK(r.num().get_symbol_set().size() == 2u);
BOOST_CHECK(r.den().get_symbol_set().size() == 2u);
// From p_type.
r = r_type{p_type{6},p_type{-15}};
BOOST_CHECK_EQUAL(r.num(),-2);
BOOST_CHECK_EQUAL(r.den(),5);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{(x+y)*(x-y),(2*x+2*y)*z};
BOOST_CHECK_EQUAL(r.num(),x-y);
BOOST_CHECK_EQUAL(r.den(),2*z);
BOOST_CHECK(r.num().get_symbol_set().size() == 3u);
BOOST_CHECK(r.den().get_symbol_set().size() == 3u);
r = r_type{x,p_type{1}};
BOOST_CHECK_EQUAL(r.num(),x);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 1u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{p_type{0},(2*x+2*y)*z};
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
BOOST_CHECK_THROW((r = r_type{(x+y)*(x-y),p_type{}}),zero_division_error);
BOOST_CHECK_THROW((r = r_type{(x+y)*(x-y),x.pow(-1)}),std::invalid_argument);
BOOST_CHECK_THROW((r = r_type{x.pow(-1),(x+y)*(x-y)}),std::invalid_argument);
// From rational.
r = r_type{0_q,-6_q};
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{3_q,-6_q};
BOOST_CHECK_EQUAL(r.num(),-1);
BOOST_CHECK_EQUAL(r.den(),2);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{3/2_q,-7/6_q};
BOOST_CHECK_EQUAL(r.num(),-9);
BOOST_CHECK_EQUAL(r.den(),7);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
BOOST_CHECK_THROW((r = r_type{0_q,0_q}),zero_division_error);
BOOST_CHECK_THROW((r = r_type{3/2_q,0_q}),zero_division_error);
// From q_type.
r = r_type{q_type{6},q_type{-15}};
BOOST_CHECK_EQUAL(r.num(),-2);
BOOST_CHECK_EQUAL(r.den(),5);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{q_type{6},q_type{1}};
BOOST_CHECK_EQUAL(r.num(),6);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{q_type{},xq+yq};
BOOST_CHECK_EQUAL(r.num(),0);
BOOST_CHECK_EQUAL(r.den(),1);
BOOST_CHECK(r.num().get_symbol_set().size() == 0u);
BOOST_CHECK(r.den().get_symbol_set().size() == 0u);
r = r_type{(xq/3+3*xq*yq/4)*(xq*xq+yq*yq),xq.pow(3)*(4*xq+9*xq*yq)*(xq-yq)/2};
// NOTE: k_monomial orders in revlex order.
if (std::is_same<Key,k_monomial>::value) {
BOOST_CHECK_EQUAL(r.num(),-(x*x+y*y));
BOOST_CHECK_EQUAL(r.den(),-(6*x.pow(3)*(x-y)));
} else {
BOOST_CHECK_EQUAL(r.num(),x*x+y*y);
BOOST_CHECK_EQUAL(r.den(),6*x.pow(3)*(x-y));
}
BOOST_CHECK(r.num().get_symbol_set().size() == 2u);
BOOST_CHECK(r.den().get_symbol_set().size() == 2u);
BOOST_CHECK_THROW((r = r_type{q_type{1},q_type{0}}),zero_division_error);
BOOST_CHECK_THROW((r = r_type{xq.pow(-1),xq}),std::invalid_argument);
BOOST_CHECK_THROW((r = r_type{xq,xq.pow(-1)}),std::invalid_argument);
// Some mixed binary ctor.
r = r_type{q_type{6},-15};
BOOST_CHECK_EQUAL(r.num(),-2);
BOOST_CHECK_EQUAL(r.den(),5);
r = r_type{r_type{6},-15/2_q};
BOOST_CHECK_EQUAL(r.num(),-4);
BOOST_CHECK_EQUAL(r.den(),5);
r = r_type{1_z,-15/2_q};
BOOST_CHECK_EQUAL(r.num(),-2);
BOOST_CHECK_EQUAL(r.den(),15);
r = r_type{1_q,x+3*y};
BOOST_CHECK_EQUAL(r.num(),1);
BOOST_CHECK_EQUAL(r.den(),x+3*y);
r = r_type{1_q,r_type{1,x+3*y}};
BOOST_CHECK_EQUAL(r.num(),x+3*y);
BOOST_CHECK_EQUAL(r.den(),1);
r = r_type{r_type{1,x+3*y},x*2};
BOOST_CHECK_EQUAL(r.num(),1);
BOOST_CHECK_EQUAL(r.den(),2*x*(x+3*y));
r = r_type{-x,"x"};
BOOST_CHECK_EQUAL(r.num(),-1);
BOOST_CHECK_EQUAL(r.den(),1);
r = r_type{"y","x"};
BOOST_CHECK_EQUAL(r.num(),y);
BOOST_CHECK_EQUAL(r.den(),x);
BOOST_CHECK_THROW((r = r_type{r_type{1,x+3*y},0}),zero_division_error);
BOOST_CHECK_THROW((r = r_type{r_type{1,x+3*y},q_type{}}),zero_division_error);
// Some assignment checks.
BOOST_CHECK((std::is_same<decltype(s = s),r_type &>::value));
BOOST_CHECK((std::is_same<decltype(s = std::move(s)),r_type &>::value));
// Self assignment.
s = s;
BOOST_CHECK_EQUAL(s.num(),5);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
s = std::move(s);
BOOST_CHECK_EQUAL(s.num(),5);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
// Generic assignments.
BOOST_CHECK((std::is_assignable<r_type &,p_type>::value));
BOOST_CHECK((std::is_assignable<r_type &,p_type &>::value));
BOOST_CHECK((std::is_assignable<r_type &,p_type &&>::value));
BOOST_CHECK((std::is_assignable<r_type &,q_type>::value));
BOOST_CHECK((std::is_assignable<r_type &,q_type &>::value));
BOOST_CHECK((std::is_assignable<r_type &,q_type &&>::value));
BOOST_CHECK((std::is_assignable<r_type &,int>::value));
BOOST_CHECK((std::is_assignable<r_type &,char &>::value));
BOOST_CHECK((std::is_assignable<r_type &,const integer &>::value));
BOOST_CHECK((std::is_assignable<r_type &,rational>::value));
BOOST_CHECK((std::is_assignable<r_type &,const rational &>::value));
BOOST_CHECK((std::is_assignable<r_type &,std::string>::value));
BOOST_CHECK((std::is_assignable<r_type &,char *>::value));
BOOST_CHECK((std::is_assignable<r_type &,const char *>::value));
BOOST_CHECK((!std::is_assignable<r_type &,double>::value));
BOOST_CHECK((!std::is_assignable<r_type &,const float>::value));
BOOST_CHECK((!std::is_assignable<r_type &,real &&>::value));
BOOST_CHECK((std::is_same<decltype(s = 0),r_type &>::value));
BOOST_CHECK((std::is_same<decltype(s = xq),r_type &>::value));
BOOST_CHECK((std::is_same<decltype(s = std::move(x)),r_type &>::value));
s = 0;
BOOST_CHECK_EQUAL(s.num(),0);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
s = 1_z;
BOOST_CHECK_EQUAL(s.num(),1);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
s = x+y;
BOOST_CHECK_EQUAL(s.num(),x+y);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 2u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
s = -3/6_q;
BOOST_CHECK_EQUAL(s.num(),-1);
BOOST_CHECK_EQUAL(s.den(),2);
BOOST_CHECK(s.num().get_symbol_set().size() == 0u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
s = xq - zq;
BOOST_CHECK_EQUAL(s.num(),-z+x);
BOOST_CHECK_EQUAL(s.den(),1);
BOOST_CHECK(s.num().get_symbol_set().size() == 2u);
BOOST_CHECK(s.den().get_symbol_set().size() == 0u);
// A check to trigger a code path in canonicalise() when the den is unitary.
s = 0;
s._num() = -10;
s._den() = 1;
s.canonicalise();
BOOST_CHECK(s.is_canonical());
BOOST_CHECK_EQUAL(s,-10);
}
};
BOOST_AUTO_TEST_CASE(rational_function_ctor_test)
{
environment env;
boost::mpl::for_each<key_types>(constructor_tester());
}
struct stream_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
auto str_cmp = [](const r_type &x, const std::string &cmp) {
std::ostringstream oss;
oss << x;
BOOST_CHECK_EQUAL(oss.str(),cmp);
};
r_type r;
str_cmp(r,"0");
r = -123;
str_cmp(r,"-123");
r = -123/7_q;
str_cmp(r,"-123/7");
p_type x{"x"}, y{"y"}, z{"z"};
r = -123/7_q + x;
str_cmp(r,"(-123+7*x)/7");
r = r_type{-123 + x,x+1};
str_cmp(r,"(-123+x)/(1+x)");
r = r_type{-123 + x,2*x};
str_cmp(r,"(-123+x)/(2*x)");
r = r_type{-123 + x,-x};
str_cmp(r,"(123-x)/x");
r = r_type{x,y};
str_cmp(r,"x/y");
// This was printed incorrectly (without brackets in den) in a previous version.
r = r_type{y,x*z};
str_cmp(r,"y/(x*z)");
}
};
BOOST_AUTO_TEST_CASE(rational_function_stream_test)
{
boost::mpl::for_each<key_types>(stream_tester());
}
struct canonical_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
r_type r;
r._num() = 0;
r._den() = 2;
BOOST_CHECK(!r.is_canonical());
r._num() = 0;
r._den() = -1;
BOOST_CHECK(!r.is_canonical());
r._num() = 2;
r._den() = 2;
BOOST_CHECK(!r.is_canonical());
r._den() = 0;
BOOST_CHECK(!r.is_canonical());
r._den() = -1;
BOOST_CHECK(!r.is_canonical());
}
};
BOOST_AUTO_TEST_CASE(rational_function_canonical_test)
{
boost::mpl::for_each<key_types>(canonical_tester());
}
struct add_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
using q_type = typename r_type::q_type;
BOOST_CHECK(is_addable<r_type>::value);
BOOST_CHECK((is_addable<r_type,int>::value));
BOOST_CHECK((is_addable<int,r_type>::value));
BOOST_CHECK((is_addable<r_type,integer>::value));
BOOST_CHECK((is_addable<integer,r_type>::value));
BOOST_CHECK((is_addable<r_type,rational>::value));
BOOST_CHECK((is_addable<rational,r_type>::value));
BOOST_CHECK((is_addable<r_type,p_type>::value));
BOOST_CHECK((is_addable<p_type,r_type>::value));
BOOST_CHECK((is_addable<r_type,q_type>::value));
BOOST_CHECK((is_addable<q_type,r_type>::value));
BOOST_CHECK(is_addable_in_place<r_type>::value);
BOOST_CHECK((is_addable_in_place<r_type,int>::value));
BOOST_CHECK((is_addable_in_place<r_type,integer>::value));
BOOST_CHECK((is_addable_in_place<r_type,rational>::value));
BOOST_CHECK((is_addable_in_place<r_type,p_type>::value));
BOOST_CHECK((is_addable_in_place<r_type,q_type>::value));
BOOST_CHECK((!is_addable<r_type,double>::value));
BOOST_CHECK((!is_addable<long double,r_type>::value));
BOOST_CHECK((!is_addable_in_place<r_type,double>::value));
BOOST_CHECK((!is_addable_in_place<r_type,float>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} + r_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} + 1_z),r_type>::value));
BOOST_CHECK((std::is_same<decltype(1_q + r_type{}),r_type>::value));
// This is mostly for checking that we are picking the overridden operators.
BOOST_CHECK((std::is_same<decltype(r_type{} + p_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(q_type{} + r_type{}),r_type>::value));
p_type x{"x"}, y{"y"}, z{"z"};
auto checker = [](const r_type &a, const r_type &b) {
BOOST_CHECK_EQUAL(a,b);
BOOST_CHECK(a.is_canonical());
};
checker(r_type{} + r_type{},r_type{});
checker(r_type{} + r_type{x,y},r_type{x,y});
checker(r_type{x,y} + r_type{},r_type{x,y});
checker(r_type{x,y} + 2,r_type{x+2*y,y});
checker(1_z + r_type{x,y},r_type{x+y,y});
checker(1/3_q + r_type{x,y},r_type{3*x+y,3*y});
checker(r_type{2*x,y} + r_type{y,x},r_type{2*x*x+y*y,y*x});
checker(r_type{x,y+x} + x,r_type{x+x*x+x*y,x+y});
checker(x + r_type{x,y+x},r_type{x+x*x+x*y,x+y});
checker(q_type{"x"}/2 + r_type{x,y+x},r_type{2*x+x*x+x*y,2*(x+y)});
checker(r_type{x,y+x} + q_type{"x"}/2,r_type{2*x+x*x+x*y,2*(x+y)});
// Random testing.
std::uniform_int_distribution<int> dist(0,4);
for (int i = 0; i < ntrials; ++i) {
auto n1 = rn_poly(x,y,z,dist);
auto d1 = rn_poly(x,y,z,dist);
if (math::is_zero(d1)) {
BOOST_CHECK_THROW((r_type{n1,d1}),zero_division_error);
continue;
}
auto n2 = rn_poly(x,y,z,dist);
auto d2 = rn_poly(x,y,z,dist);
if (math::is_zero(d2)) {
BOOST_CHECK_THROW((r_type{n2,d2}),zero_division_error);
continue;
}
r_type r1{n1,d1}, r2{n2,d2};
auto add = r1 + r2;
BOOST_CHECK(add.is_canonical());
auto check = add - r1;
BOOST_CHECK(check.is_canonical());
BOOST_CHECK_EQUAL(check,r2);
check = add - r2;
BOOST_CHECK(check.is_canonical());
BOOST_CHECK_EQUAL(check,r1);
// Vs interop.
BOOST_CHECK_EQUAL(-1 + r1 + 1,r1);
BOOST_CHECK_EQUAL(-1_z + r1 + 1_z,r1);
BOOST_CHECK_EQUAL(-1/2_q + r1 + 1/2_q,r1);
BOOST_CHECK_EQUAL(-n2 + r1 + n2,r1);
BOOST_CHECK_EQUAL(q_type{-n2}/2 + r1 + q_type{n2}/2,r1);
// Check the in-place version.
r1 += r2;
BOOST_CHECK_EQUAL(add,r1);
r1 += 1/2_q;
BOOST_CHECK_EQUAL(add + 1/2_q,r1);
r1 += 1;
BOOST_CHECK_EQUAL(add + 1/2_q + 1,r1);
r1 += n2;
BOOST_CHECK_EQUAL(add + 1/2_q + 1 + n2,r1);
r1 += q_type{n2}/3;
BOOST_CHECK_EQUAL(add + 1/2_q + 1 + n2 + q_type{n2}/3,r1);
}
// Identity operator.
BOOST_CHECK_EQUAL((+r_type{2*x*x+y*y,y*x}),(r_type{2*x*x+y*y,y*x}));
}
};
BOOST_AUTO_TEST_CASE(rational_function_add_test)
{
boost::mpl::for_each<key_types>(add_tester());
}
struct sub_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
using q_type = typename r_type::q_type;
BOOST_CHECK(is_subtractable<r_type>::value);
BOOST_CHECK((is_subtractable<r_type,int>::value));
BOOST_CHECK((is_subtractable<int,r_type>::value));
BOOST_CHECK((is_subtractable<r_type,integer>::value));
BOOST_CHECK((is_subtractable<integer,r_type>::value));
BOOST_CHECK((is_subtractable<r_type,rational>::value));
BOOST_CHECK((is_subtractable<rational,r_type>::value));
BOOST_CHECK((is_subtractable<r_type,p_type>::value));
BOOST_CHECK((is_subtractable<p_type,r_type>::value));
BOOST_CHECK((is_subtractable<r_type,q_type>::value));
BOOST_CHECK((is_subtractable<q_type,r_type>::value));
BOOST_CHECK(is_subtractable_in_place<r_type>::value);
BOOST_CHECK((is_subtractable_in_place<r_type,int>::value));
BOOST_CHECK((is_subtractable_in_place<r_type,integer>::value));
BOOST_CHECK((is_subtractable_in_place<r_type,rational>::value));
BOOST_CHECK((is_subtractable_in_place<r_type,p_type>::value));
BOOST_CHECK((is_subtractable_in_place<r_type,q_type>::value));
BOOST_CHECK((!is_subtractable<r_type,double>::value));
BOOST_CHECK((!is_subtractable<long double,r_type>::value));
BOOST_CHECK((!is_subtractable_in_place<r_type,double>::value));
BOOST_CHECK((!is_subtractable_in_place<r_type,float>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} - r_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} - 1_z),r_type>::value));
BOOST_CHECK((std::is_same<decltype(1_q - r_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} - p_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(q_type{} - r_type{}),r_type>::value));
p_type x{"x"}, y{"y"}, z{"z"};
auto checker = [](const r_type &a, const r_type &b) {
BOOST_CHECK_EQUAL(a,b);
BOOST_CHECK(a.is_canonical());
};
checker(r_type{} - r_type{},r_type{});
checker(r_type{} - r_type{x,y},-r_type{x,y});
checker(r_type{x,y} - r_type{},r_type{x,y});
checker(r_type{x,y} - 2,r_type{x-2*y,y});
checker(1_z - r_type{x,y},r_type{-x+y,y});
checker(1/3_q - r_type{x,y},r_type{y-3*x,3*y});
checker(r_type{2*x,y} - r_type{y,x},r_type{2*x*x-y*y,y*x});
checker(r_type{x,y+x} - x,r_type{x-x*x-x*y,x+y});
checker(x - r_type{x,y+x},r_type{-x+x*x+x*y,x+y});
checker(q_type{"x"}/2 - r_type{x,y+x},r_type{-2*x+x*x+x*y,2*(x+y)});
checker(r_type{x,y+x} - q_type{"x"}/2,r_type{2*x-x*x-x*y,2*(x+y)});
// Random testing.
std::uniform_int_distribution<int> dist(0,4);
for (int i = 0; i < ntrials; ++i) {
auto n1 = rn_poly(x,y,z,dist);
auto d1 = rn_poly(x,y,z,dist);
if (math::is_zero(d1)) {
BOOST_CHECK_THROW((r_type{n1,d1}),zero_division_error);
continue;
}
auto n2 = rn_poly(x,y,z,dist);
auto d2 = rn_poly(x,y,z,dist);
if (math::is_zero(d2)) {
BOOST_CHECK_THROW((r_type{n2,d2}),zero_division_error);
continue;
}
r_type r1{n1,d1}, r2{n2,d2};
auto sub = r1 - r2;
BOOST_CHECK(sub.is_canonical());
auto check = sub - r1;
BOOST_CHECK(check.is_canonical());
BOOST_CHECK_EQUAL(check,-r2);
check = -sub - r2;
BOOST_CHECK(check.is_canonical());
BOOST_CHECK_EQUAL(check,-r1);
// Vs interop.
BOOST_CHECK_EQUAL(1 - r1 - 1,-r1);
BOOST_CHECK_EQUAL(1_z - r1 - 1_z,-r1);
BOOST_CHECK_EQUAL(1/2_q - r1 - 1/2_q,-r1);
BOOST_CHECK_EQUAL(n2 - r1 - n2,-r1);
BOOST_CHECK_EQUAL(q_type{n2}/2 - r1 - q_type{n2}/2,-r1);
// Check the in-place version.
r1 -= r2;
BOOST_CHECK_EQUAL(sub,r1);
r1 -= 1/2_q;
BOOST_CHECK_EQUAL(sub - 1/2_q,r1);
r1 -= 1;
BOOST_CHECK_EQUAL(sub - 1/2_q - 1,r1);
r1 -= n2;
BOOST_CHECK_EQUAL(sub - 1/2_q - 1 - n2,r1);
r1 -= q_type{n2}/3;
BOOST_CHECK_EQUAL(sub - 1/2_q - 1 - n2 - q_type{n2}/3,r1);
}
// Identity operator.
BOOST_CHECK_EQUAL((-r_type{2*x*x+y*y,y*x}),(r_type{-2*x*x-y*y,y*x}));
}
};
BOOST_AUTO_TEST_CASE(rational_function_sub_test)
{
boost::mpl::for_each<key_types>(sub_tester());
}
struct mul_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
using q_type = typename r_type::q_type;
BOOST_CHECK(is_multipliable<r_type>::value);
BOOST_CHECK((is_multipliable<r_type,int>::value));
BOOST_CHECK((is_multipliable<int,r_type>::value));
BOOST_CHECK((is_multipliable<r_type,integer>::value));
BOOST_CHECK((is_multipliable<integer,r_type>::value));
BOOST_CHECK((is_multipliable<r_type,rational>::value));
BOOST_CHECK((is_multipliable<rational,r_type>::value));
BOOST_CHECK((is_multipliable<r_type,p_type>::value));
BOOST_CHECK((is_multipliable<p_type,r_type>::value));
BOOST_CHECK((is_multipliable<r_type,q_type>::value));
BOOST_CHECK((is_multipliable<q_type,r_type>::value));
BOOST_CHECK(is_multipliable_in_place<r_type>::value);
BOOST_CHECK((is_multipliable_in_place<r_type,int>::value));
BOOST_CHECK((is_multipliable_in_place<r_type,integer>::value));
BOOST_CHECK((is_multipliable_in_place<r_type,rational>::value));
BOOST_CHECK((is_multipliable_in_place<r_type,p_type>::value));
BOOST_CHECK((is_multipliable_in_place<r_type,q_type>::value));
BOOST_CHECK((!is_multipliable<r_type,double>::value));
BOOST_CHECK((!is_multipliable<long double,r_type>::value));
BOOST_CHECK((!is_multipliable_in_place<r_type,double>::value));
BOOST_CHECK((!is_multipliable_in_place<r_type,float>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} * r_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} * 1_z),r_type>::value));
BOOST_CHECK((std::is_same<decltype(1_q * r_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} * p_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(q_type{} * r_type{}),r_type>::value));
p_type x{"x"}, y{"y"}, z{"z"};
auto checker = [](const r_type &a, const r_type &b) {
BOOST_CHECK_EQUAL(a,b);
BOOST_CHECK(a.is_canonical());
};
checker(r_type{} * r_type{},r_type{});
checker(r_type{} * r_type{x,y},r_type{});
checker(r_type{x,y} * r_type{},r_type{});
checker(r_type{1} * r_type{x,y},r_type{x,y});
checker(r_type{x,y} * r_type{1},r_type{x,y});
checker(r_type{x,y} * 2,r_type{2*x,y});
checker(2_z * r_type{x,y},r_type{2*x,y});
checker(1/3_q * r_type{x,y},r_type{x,3*y});
checker(r_type{2*x,y} * r_type{y,x},r_type{2});
checker(r_type{x,y+x} * x,r_type{x*x,x+y});
checker(x * r_type{x,y+x},r_type{x*x,x+y});
checker((q_type{"x"}/2) * r_type{x,y+x},r_type{x*x,2*(x+y)});
checker(r_type{x,y+x} * (q_type{"x"}/2),r_type{x*x,2*(x+y)});
// Random testing.
std::uniform_int_distribution<int> dist(0,4);
for (int i = 0; i < ntrials; ++i) {
auto n1 = rn_poly(x,y,z,dist);
auto d1 = rn_poly(x,y,z,dist);
if (math::is_zero(d1)) {
BOOST_CHECK_THROW((r_type{n1,d1}),zero_division_error);
continue;
}
auto n2 = rn_poly(x,y,z,dist);
auto d2 = rn_poly(x,y,z,dist);
if (math::is_zero(d2)) {
BOOST_CHECK_THROW((r_type{n2,d2}),zero_division_error);
continue;
}
r_type r1{n1,d1}, r2{n2,d2};
auto mul = r1 * r2;
BOOST_CHECK(mul.is_canonical());
r_type check;
if (math::is_zero(r1)) {
BOOST_CHECK_THROW(mul / r1,zero_division_error);
} else {
check = mul / r1;
BOOST_CHECK(check.is_canonical());
BOOST_CHECK_EQUAL(check,r2);
}
if (math::is_zero(r2)) {
BOOST_CHECK_THROW(mul / r2,zero_division_error);
} else {
check = mul / r2;
BOOST_CHECK(check.is_canonical());
BOOST_CHECK_EQUAL(check,r1);
}
// Vs interop.
BOOST_CHECK_EQUAL((r1 * 2) / 2,r1);
BOOST_CHECK_EQUAL((r1 * 2_z) / 2_z,r1);
BOOST_CHECK_EQUAL((r1 * (1/2_q)) / (1/2_q),r1);
if (math::is_zero(n2)) {
BOOST_CHECK_THROW((r1 * n2) / n2,zero_division_error);
} else {
BOOST_CHECK_EQUAL((r1 * n2) / n2,r1);
BOOST_CHECK_EQUAL((q_type{n2}/2 * r1) / (q_type{n2}/2),r1);
}
// Check the in-place version.
r1 *= r2;
BOOST_CHECK_EQUAL(mul,r1);
r1 *= 1/2_q;
BOOST_CHECK_EQUAL(mul * 1/2_q,r1);
r1 *= 1;
BOOST_CHECK_EQUAL(mul * 1/2_q,r1);
r1 *= n2;
BOOST_CHECK_EQUAL(mul * 1/2_q * n2,r1);
r1 *= q_type{n2}/3;
BOOST_CHECK_EQUAL(mul * 1/2_q * n2 * q_type{n2}/3,r1);
}
}
};
BOOST_AUTO_TEST_CASE(rational_function_mul_test)
{
boost::mpl::for_each<key_types>(mul_tester());
}
struct div_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
using q_type = typename r_type::q_type;
BOOST_CHECK(is_divisible<r_type>::value);
BOOST_CHECK((is_divisible<r_type,int>::value));
BOOST_CHECK((is_divisible<int,r_type>::value));
BOOST_CHECK((is_divisible<r_type,integer>::value));
BOOST_CHECK((is_divisible<integer,r_type>::value));
BOOST_CHECK((is_divisible<r_type,rational>::value));
BOOST_CHECK((is_divisible<rational,r_type>::value));
BOOST_CHECK((is_divisible<r_type,p_type>::value));
BOOST_CHECK((is_divisible<p_type,r_type>::value));
BOOST_CHECK((is_divisible<r_type,q_type>::value));
BOOST_CHECK((is_divisible<q_type,r_type>::value));
BOOST_CHECK(is_divisible_in_place<r_type>::value);
BOOST_CHECK((is_divisible_in_place<r_type,int>::value));
BOOST_CHECK((is_divisible_in_place<r_type,integer>::value));
BOOST_CHECK((is_divisible_in_place<r_type,rational>::value));
BOOST_CHECK((is_divisible_in_place<r_type,p_type>::value));
BOOST_CHECK((is_divisible_in_place<r_type,q_type>::value));
BOOST_CHECK((!is_divisible<r_type,double>::value));
BOOST_CHECK((!is_divisible<long double,r_type>::value));
BOOST_CHECK((!is_divisible_in_place<r_type,double>::value));
BOOST_CHECK((!is_divisible_in_place<r_type,float>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} / r_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} / 1_z),r_type>::value));
BOOST_CHECK((std::is_same<decltype(1_q / r_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(r_type{} / p_type{}),r_type>::value));
BOOST_CHECK((std::is_same<decltype(q_type{} / r_type{}),r_type>::value));
p_type x{"x"}, y{"y"}, z{"z"};
auto checker = [](const r_type &a, const r_type &b) {
BOOST_CHECK_EQUAL(a,b);
BOOST_CHECK(a.is_canonical());
};
checker(r_type{1} / r_type{1},r_type{1});
checker(r_type{1} / r_type{x,y},r_type{y,x});
checker(r_type{x,y} / r_type{1},r_type{x,y});
checker(r_type{x,y} / 2,r_type{x,2*y});
checker(2_z / r_type{x,y},r_type{2*y,x});
checker(1/3_q / r_type{x,y},r_type{y,3*x});
checker(r_type{2*x,y} / r_type{y,x},r_type{2*x*x,y*y});
checker(r_type{x,y+x} / x,r_type{p_type{1},x+y});
checker(x / r_type{x,y+x},r_type{y+x,p_type{1}});
checker((q_type{"x"}/2) / r_type{x,y+x},r_type{y+x,p_type{2}});
checker(r_type{x,y+x} / (q_type{"x"}/2),r_type{p_type{2},(x+y)});
// Random testing.
std::uniform_int_distribution<int> dist(0,4);
for (int i = 0; i < ntrials; ++i) {
auto n1 = rn_poly(x,y,z,dist);
auto d1 = rn_poly(x,y,z,dist);
if (math::is_zero(d1)) {
BOOST_CHECK_THROW((r_type{n1,d1}),zero_division_error);
continue;
}
auto n2 = rn_poly(x,y,z,dist);
auto d2 = rn_poly(x,y,z,dist);
if (math::is_zero(d2)) {
BOOST_CHECK_THROW((r_type{n2,d2}),zero_division_error);
continue;
}
r_type r1{n1,d1}, r2{n2,d2};
if (math::is_zero(r2)) {
continue;
}
auto div = r1 / r2;
BOOST_CHECK(div.is_canonical());
auto check = div * r2;
BOOST_CHECK(check.is_canonical());
BOOST_CHECK_EQUAL(check,r1);
// Vs interop.
BOOST_CHECK_EQUAL((r1 / 2) * 2,r1);
BOOST_CHECK_EQUAL((r1 / 2_z) * 2_z,r1);
BOOST_CHECK_EQUAL((r1 / (1/2_q)) * (1/2_q),r1);
if (math::is_zero(n2)) {
BOOST_CHECK_THROW((r1 / n2) * n2,zero_division_error);
} else {
BOOST_CHECK_EQUAL((r1 / n2) * n2,r1);
BOOST_CHECK_EQUAL((q_type{n2}/2 * r2) / (q_type{n2}/2),r2);
}
// Check the in-place version.
r1 /= r2;
BOOST_CHECK_EQUAL(div,r1);
r1 /= 1/2_q;
BOOST_CHECK_EQUAL(div / (1/2_q),r1);
r1 /= 1;
BOOST_CHECK_EQUAL(div / (1/2_q),r1);
if (math::is_zero(n2)) {
continue;
}
r1 /= n2;
BOOST_CHECK_EQUAL((div / (1/2_q)) / n2,r1);
r1 /= q_type{n2}/3;
BOOST_CHECK_EQUAL(((div / (1/2_q)) / n2) / (q_type{n2}/3),r1);
}
}
};
BOOST_AUTO_TEST_CASE(rational_function_div_test)
{
boost::mpl::for_each<key_types>(div_tester());
}
struct is_zero_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
BOOST_CHECK((has_is_zero<r_type>::value));
BOOST_CHECK(math::is_zero(r_type{}));
BOOST_CHECK(math::is_zero(r_type{0,1}));
BOOST_CHECK(math::is_zero(r_type{0,-123}));
BOOST_CHECK(!math::is_zero(r_type{1,-1}));
}
};
BOOST_AUTO_TEST_CASE(rational_function_is_zero_test)
{
boost::mpl::for_each<key_types>(is_zero_tester());
}
struct comparison_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
using q_type = typename r_type::q_type;
p_type x{"x"}, y{"y"}, z{"z"};
BOOST_CHECK((is_equality_comparable<r_type>::value));
BOOST_CHECK((is_equality_comparable<r_type,p_type>::value));
BOOST_CHECK((is_equality_comparable<p_type,r_type>::value));
BOOST_CHECK((is_equality_comparable<r_type,q_type>::value));
BOOST_CHECK((is_equality_comparable<q_type,r_type>::value));
BOOST_CHECK((is_equality_comparable<r_type,int>::value));
BOOST_CHECK((is_equality_comparable<integer,r_type>::value));
BOOST_CHECK((is_equality_comparable<r_type,rational>::value));
BOOST_CHECK((!is_equality_comparable<r_type,double>::value));
BOOST_CHECK((!is_equality_comparable<std::string,r_type>::value));
BOOST_CHECK_EQUAL(r_type{0},p_type{});
BOOST_CHECK_EQUAL(p_type{0},r_type{});
BOOST_CHECK_EQUAL(r_type{},q_type{0});
BOOST_CHECK_EQUAL(q_type{},r_type{});
BOOST_CHECK_EQUAL(r_type{1},1);
BOOST_CHECK_EQUAL(1_z,r_type{1});
BOOST_CHECK_EQUAL((r_type{1,2}),1/2_q);
BOOST_CHECK_EQUAL((r_type{(x+y+z)*2,p_type{2}}),x+y+z);
BOOST_CHECK((r_type{x,y} != r_type{1}));
BOOST_CHECK((r_type{x,y} != 1/2_q));
BOOST_CHECK((-6 != r_type{x,p_type{2}}));
BOOST_CHECK((r_type{x,y} != q_type{x} / 2));
BOOST_CHECK((p_type{x} != r_type{x,p_type{2}}));
}
};
BOOST_AUTO_TEST_CASE(rational_function_comparison_test)
{
boost::mpl::for_each<key_types>(comparison_tester());
}
struct pow_tester
{
template <typename Key>
void operator()(const Key &)
{
using math::pow;
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
{
r_type x{"x"}, y{"y"}, z{"z"};
BOOST_CHECK((is_exponentiable<r_type,int>::value));
BOOST_CHECK((is_exponentiable<r_type,integer>::value));
BOOST_CHECK((is_exponentiable<r_type,long long>::value));
BOOST_CHECK((!is_exponentiable<r_type,double>::value));
BOOST_CHECK((!is_exponentiable<r_type,rational>::value));
BOOST_CHECK((!is_exponentiable<r_type,r_type>::value));
BOOST_CHECK_EQUAL(pow(x/y,char(2)),x*x/(y*y));
BOOST_CHECK_EQUAL(pow(x/y,0_z),1);
BOOST_CHECK_EQUAL(pow(r_type{},0_z),1);
BOOST_CHECK_EQUAL(pow(x/y,-2),y*y/(x*x));
BOOST_CHECK_THROW((pow(r_type{},-1)),zero_division_error);
}
// Random testing.
p_type x{"x"}, y{"y"}, z{"z"};
std::uniform_int_distribution<int> dist(0,4), p_dist(-4,4), clear_dist(0,9);
for (int i = 0; i < ntrials; ++i) {
auto n1 = rn_poly(x,y,z,dist);
auto d1 = rn_poly(x,y,z,dist);
if (math::is_zero(d1)) {
BOOST_CHECK_THROW((r_type{n1,d1}),zero_division_error);
continue;
}
r_type r1{n1,d1};
auto expo = p_dist(rng);
if (expo == 0) {
BOOST_CHECK_EQUAL(pow(r1,expo),1);
} else if (expo > 0) {
auto p = pow(r1,expo);
BOOST_CHECK(p.is_canonical());
r_type acc{1};
for (auto j = 0; j < expo; ++j) {
acc *= r1;
}
BOOST_CHECK_EQUAL(acc,p);
} else if (!math::is_zero(r1)) {
auto p = pow(r1,expo);
BOOST_CHECK(p.is_canonical());
r_type acc{1};
for (auto j = 0; j < -expo; ++j) {
acc /= r1;
}
BOOST_CHECK_EQUAL(acc,p);
}
if (clear_dist(rng) == 0) {
r_type::clear_pow_cache();
}
}
}
};
BOOST_AUTO_TEST_CASE(rational_function_pow_test)
{
boost::mpl::for_each<key_types>(pow_tester());
}
struct subs_tester
{
template <typename Key>
void operator()(const Key &)
{
using math::pow;
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
using q_type = typename r_type::q_type;
r_type x{"x"}, y{"y"}, z{"z"};
BOOST_CHECK((has_subs<r_type,int>::value));
BOOST_CHECK((has_subs<r_type,r_type>::value));
BOOST_CHECK((has_subs<r_type,p_type>::value));
BOOST_CHECK((has_subs<r_type,q_type>::value));
BOOST_CHECK((has_subs<r_type,integer>::value));
// More checks for these in rational_function_02.
BOOST_CHECK((has_subs<r_type,double>::value));
BOOST_CHECK((has_subs<r_type,float>::value));
BOOST_CHECK((!has_subs<r_type,std::string>::value));
BOOST_CHECK_EQUAL(x.subs("x",1),1);
BOOST_CHECK((std::is_same<r_type,decltype(x.subs("x",1))>::value));
BOOST_CHECK_THROW((1/x).subs("x",0),zero_division_error);
BOOST_CHECK_EQUAL(math::subs((x+y)/z,"z",-x-y),-1);
BOOST_CHECK((std::is_same<r_type,decltype(math::subs((x+y)/z,"z",-x-y))>::value));
BOOST_CHECK_EQUAL(math::subs((x+y)/z,"x",123_z),(123+y)/z);
BOOST_CHECK((std::is_same<r_type,decltype(math::subs((x+y)/z,"x",123_z))>::value));
BOOST_CHECK_EQUAL(math::subs((x+y)/z,"x",3/2_q),(3+2*y)/(2*z));
BOOST_CHECK((std::is_same<r_type,decltype(math::subs((x+y)/z,"x",3/2_q))>::value));
BOOST_CHECK_EQUAL(math::subs((x+y)/z,"y",p_type("z")*3),(x+3*z)/z);
BOOST_CHECK((std::is_same<r_type,decltype(math::subs((x+y)/z,"y",p_type("z")*3))>::value));
BOOST_CHECK_EQUAL(math::subs((x+y)/z,"z",q_type("z")/6),6*(x+y)/z);
BOOST_CHECK((std::is_same<r_type,decltype(math::subs((x+y)/z,"z",q_type("z")/6))>::value));
BOOST_CHECK_EQUAL(math::subs((x+y)/z,"a",123_z),(x+y)/z);
BOOST_CHECK_EQUAL(math::subs(x/(z+y),"x",0),0);
// Check that using negative powers throws.
BOOST_CHECK_THROW(math::subs(x/(z+y),"x",p_type{"x"}.pow(-1)),std::invalid_argument);
}
};
BOOST_AUTO_TEST_CASE(rational_function_subs_test)
{
boost::mpl::for_each<key_types>(subs_tester());
}
struct serialization_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
auto checker = [](const r_type &r) -> void {
r_type tmp;
std::stringstream ss;
{
boost::archive::text_oarchive oa(ss);
oa << r;
}
{
boost::archive::text_iarchive ia(ss);
ia >> tmp;
}
BOOST_CHECK_EQUAL(tmp,r);
};
// Random testing.
p_type x{"x"}, y{"y"}, z{"z"};
std::uniform_int_distribution<int> dist(0,4), p_dist(-4,4);
for (int i = 0; i < ntrials; ++i) {
auto n1 = rn_poly(x,y,z,dist);
auto d1 = rn_poly(x,y,z,dist);
if (math::is_zero(d1)) {
BOOST_CHECK_THROW((r_type{n1,d1}),zero_division_error);
continue;
}
r_type r1{n1,d1};
checker(r1);
}
}
};
BOOST_AUTO_TEST_CASE(rational_function_serialization_test)
{
boost::mpl::for_each<key_types>(serialization_tester());
}
struct ipow_subs_tester
{
template <typename Key>
void operator()(const Key &)
{
using math::pow;
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
using q_type = typename r_type::q_type;
r_type x{"x"}, y{"y"}, z{"z"};
BOOST_CHECK((has_ipow_subs<r_type,int>::value));
BOOST_CHECK((has_ipow_subs<r_type,r_type>::value));
BOOST_CHECK((has_ipow_subs<r_type,p_type>::value));
BOOST_CHECK((has_ipow_subs<r_type,q_type>::value));
BOOST_CHECK((has_ipow_subs<r_type,integer>::value));
BOOST_CHECK((!has_ipow_subs<r_type,std::string>::value));
// More checks for these in rational_function_02.
BOOST_CHECK((has_ipow_subs<r_type,double>::value));
BOOST_CHECK((has_ipow_subs<r_type,float>::value));
BOOST_CHECK_EQUAL(x.ipow_subs("x",1_z,y),y);
BOOST_CHECK((std::is_same<r_type,decltype(x.ipow_subs("x",1_z,y))>::value));
BOOST_CHECK_THROW((1/(x*x)).ipow_subs("x",2_z,0),zero_division_error);
BOOST_CHECK((std::is_same<r_type,decltype((1/(x*x)).ipow_subs("x",2_z,0))>::value));
BOOST_CHECK_EQUAL((1/(x*x)).ipow_subs("x",2_z,y),1/y);
BOOST_CHECK_EQUAL(math::ipow_subs((x+y)/(z*z),"z",2,-x-y),-1);
BOOST_CHECK_EQUAL(math::ipow_subs((x*x*x+y)/z,"x",2,123_z),(123*x+y)/z);
BOOST_CHECK_EQUAL(math::ipow_subs((x+y)/z,"x",2,3/2_q),(x+y)/z);
BOOST_CHECK((std::is_same<r_type,decltype(math::ipow_subs((x+y)/z,"x",2,3/2_q))>::value));
BOOST_CHECK_EQUAL(math::ipow_subs((x+y*y*y*y)/z,"y",2,p_type("z")*3),(x+9*z*z)/z);
BOOST_CHECK((std::is_same<r_type,decltype(math::ipow_subs((x+y*y*y*y)/z,"y",2,p_type("z")*3))>::value));
BOOST_CHECK_EQUAL(math::ipow_subs((x+y)/(z*z),"z",2,q_type("z")/6),6*(x+y)/z);
BOOST_CHECK((std::is_same<r_type,decltype(math::ipow_subs((x+y)/(z*z),"z",2,q_type("z")/6))>::value));
BOOST_CHECK_EQUAL(math::ipow_subs((x+y)/z,"a",123,123_z),(x+y)/z);
BOOST_CHECK_EQUAL(math::ipow_subs(x/(z+y),"x",1,0),0);
BOOST_CHECK_EQUAL(math::ipow_subs(x/(z+y),"x",-1,0),x/(z+y));
// Check that using negative powers throws.
BOOST_CHECK_THROW(math::ipow_subs(x/(z+y),"x",1,p_type{"x"}.pow(-1)),std::invalid_argument);
}
};
BOOST_AUTO_TEST_CASE(rational_function_ipow_subs_test)
{
boost::mpl::for_each<key_types>(ipow_subs_tester());
}
struct partial_tester
{
template <typename Key>
void operator()(const Key &)
{
using math::pow;
using math::partial;
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
{
BOOST_CHECK(is_differentiable<r_type>::value);
r_type x{"x"}, y{"y"};
BOOST_CHECK_EQUAL(partial(r_type{3,4},"x"),0);
BOOST_CHECK_EQUAL(partial(x,"x"),1);
BOOST_CHECK_EQUAL(partial(x/y,"z"),0);
BOOST_CHECK_EQUAL(partial(x/y,"x"),1/y);
BOOST_CHECK_EQUAL(partial((4*x-2)/(x*x+1),"x"),(-4*x*x+4*x+4)/pow(x*x+1,2));
}
// Random testing.
p_type x{"x"}, y{"y"}, z{"z"};
std::uniform_int_distribution<int> dist(0,4), p_dist(-4,4);
for (int i = 0; i < ntrials; ++i) {
auto n1 = rn_poly(x,y,z,dist);
auto d1 = rn_poly(x,y,z,dist);
if (math::is_zero(d1)) {
BOOST_CHECK_THROW((r_type{n1,d1}),zero_division_error);
continue;
}
r_type r1{n1,d1};
BOOST_CHECK_EQUAL(partial(r1,"x"),(r_type{partial(r1.num(),"x")*r1.den()-partial(r1.den(),"x")*r1.num(),
r1.den()*r1.den()}));
}
}
};
BOOST_AUTO_TEST_CASE(rational_function_partial_test)
{
boost::mpl::for_each<key_types>(partial_tester());
}
struct integrate_tester
{
template <typename Key>
void operator()(const Key &)
{
using math::pow;
using math::integrate;
using r_type = rational_function<Key>;
BOOST_CHECK(is_integrable<r_type>::value);
r_type x{"x"}, y{"y"};
BOOST_CHECK_EQUAL(integrate(r_type{},"x"),0);
BOOST_CHECK_EQUAL(integrate(r_type{3,4},"x"),(r_type{3,4}*x));
BOOST_CHECK_EQUAL(integrate(x,"x"),x*x/2);
BOOST_CHECK_EQUAL(integrate(x,"y"),x*y);
BOOST_CHECK_THROW(integrate(1/x,"x"),std::invalid_argument);
BOOST_CHECK_EQUAL(integrate(1/x,"y"),y/x);
BOOST_CHECK_EQUAL(integrate((7*x*x+y*x)/(2*y),"x"),(14*x*x*x+3*x*x*y)/(12*y));
}
};
BOOST_AUTO_TEST_CASE(rational_function_integrate_test)
{
boost::mpl::for_each<key_types>(integrate_tester());
}
template <typename T>
inline void tex_checker(const T &r, std::string cmp1, std::string cmp2 = "")
{
std::ostringstream oss;
r.print_tex(oss);
auto oss_str = oss.str();
oss.str("");
print_tex_coefficient(oss,r);
auto oss_str2 = oss.str();
BOOST_CHECK_EQUAL(oss_str,oss_str2);
if (cmp2 != oss_str) {
BOOST_CHECK_EQUAL(cmp1,oss_str);
}
}
struct print_tex_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
tex_checker(r_type{},"0");
r_type x{"x"}, y{"y"};
tex_checker(x,"{x}");
tex_checker(x*y,"{x}{y}");
tex_checker(-x,"-{x}");
tex_checker(-x*y,"-{x}{y}");
tex_checker(x*y/2,"\\frac{{x}{y}}{2}");
tex_checker(-x*y/2,"-\\frac{{x}{y}}{2}");
tex_checker(-x*y/(x+2),"-\\frac{{x}{y}}{{x}+2}","-\\frac{{x}{y}}{2+{x}}");
tex_checker(x*y/2,"\\frac{{x}{y}}{2}");
tex_checker(x*y/(x+2),"\\frac{{x}{y}}{{x}+2}","\\frac{{x}{y}}{2+{x}}");
tex_checker(x*y/(x-2),"\\frac{{x}{y}}{{x}-2}","-\\frac{{x}{y}}{2-{x}}");
tex_checker((x-3*y)/x,"\\frac{{x}-3{y}}{{x}}","-\\frac{3{y}-{x}}{{x}}");
tex_checker((x-2*y)/(x-y),"\\frac{{x}-2{y}}{{x}-{y}}","\\frac{2{y}-{x}}{{y}-{x}}");
}
};
BOOST_AUTO_TEST_CASE(rational_function_print_tex_test)
{
boost::mpl::for_each<key_types>(print_tex_tester());
}
struct evaluate_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using math::evaluate;
BOOST_CHECK((is_evaluable<r_type,int>::value));
BOOST_CHECK((is_evaluable<r_type,double>::value));
BOOST_CHECK((is_evaluable<r_type,integer>::value));
BOOST_CHECK((is_evaluable<r_type,rational>::value));
BOOST_CHECK((is_evaluable<r_type,r_type>::value));
BOOST_CHECK((!is_evaluable<r_type,std::string>::value));
r_type x{"x"}, y{"y"};
BOOST_CHECK((std::is_same<decltype(evaluate<rational>((x+y)/(3*y),{{"x",1/2_q},{"y",-3/5_q}})),rational>::value));
BOOST_CHECK((std::is_same<decltype(evaluate<double>((x+y)/(3*y),{{"x",1.},{"y",2.}})),double>::value));
BOOST_CHECK((std::is_same<decltype(evaluate<integer>((x+y)/(3*y),{{"x",1_z},{"y",2_z}})),integer>::value));
BOOST_CHECK((std::is_same<decltype(evaluate<r_type>((x+y)/(3*y),{{"x",r_type{}},{"y",r_type{}}})),r_type>::value));
BOOST_CHECK_EQUAL((evaluate<rational>((2*x*x+y)/(3*y),{{"x",1/2_q},{"y",-3/5_q}})),1/18_q);
BOOST_CHECK_EQUAL((evaluate<integer>((2*x*x+y)/(3*y),{{"x",2_z},{"y",3_z}})),1_z);
BOOST_CHECK_EQUAL((evaluate<r_type>((2*x*x+y)/(3*y),{{"x",r_type{"y"}},{"y",r_type{"x"}}})),(2*y*y+x)/(3*x));
BOOST_CHECK_THROW((evaluate<rational>((2*x*x+y)/(3*y),{{"x",1/2_q},{"y",0_q}})),zero_division_error);
}
};
BOOST_AUTO_TEST_CASE(rational_function_evaluate_test)
{
boost::mpl::for_each<key_types>(evaluate_tester());
}
struct trim_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
using p_type = typename r_type::p_type;
{
r_type x{"x"}, y{"y"};
auto r = (x+y)/x;
auto r_trim = r.trim();
BOOST_CHECK(r.num().get_symbol_set() == r_trim.num().get_symbol_set());
BOOST_CHECK(r.den().get_symbol_set() != r_trim.den().get_symbol_set());
r = (x-x+y)/x;
r_trim = r.trim();
BOOST_CHECK(r.num().get_symbol_set() != r_trim.num().get_symbol_set());
BOOST_CHECK(r.den().get_symbol_set() != r_trim.den().get_symbol_set());
BOOST_CHECK((r.num().get_symbol_set() == symbol_set{symbol{"x"},symbol{"y"}}));
BOOST_CHECK((r_trim.num().get_symbol_set() == symbol_set{symbol{"y"}}));
}
// Random testing.
p_type x{"x"}, y{"y"}, z{"z"};
std::uniform_int_distribution<int> dist(0,4), p_dist(-4,4);
for (int i = 0; i < ntrials; ++i) {
auto n1 = rn_poly(x,y,z,dist);
auto d1 = rn_poly(x,y,z,dist);
if (math::is_zero(d1)) {
BOOST_CHECK_THROW((r_type{n1,d1}),zero_division_error);
continue;
}
r_type r1{n1,d1};
auto r1_trim = r1.trim();
BOOST_CHECK(r1_trim.is_canonical());
BOOST_CHECK_EQUAL(r1,r1_trim);
}
}
};
BOOST_AUTO_TEST_CASE(rational_function_trim_test)
{
boost::mpl::for_each<key_types>(trim_tester());
}
struct sin_cos_tester
{
template <typename Key>
void operator()(const Key &)
{
using r_type = rational_function<Key>;
BOOST_CHECK(has_sine<r_type>::value);
BOOST_CHECK(has_cosine<r_type>::value);
BOOST_CHECK_EQUAL(math::sin(r_type{}),0);
BOOST_CHECK_EQUAL(math::cos(r_type{}),1);
BOOST_CHECK_THROW(math::sin(r_type{"x"}),std::invalid_argument);
BOOST_CHECK_THROW(math::cos(r_type{"x"}),std::invalid_argument);
}
};
BOOST_AUTO_TEST_CASE(rational_function_sin_cos_test)
{
boost::mpl::for_each<key_types>(sin_cos_tester());
}
struct degree_tester
{
template <typename Key>
void operator()(const Key &)
{
using math::degree;
using r_type = rational_function<Key>;
BOOST_CHECK(has_degree<r_type>::value);
r_type x{"x"}, y{"y"};
BOOST_CHECK_EQUAL(degree(r_type{}),0);
BOOST_CHECK_EQUAL(degree(x),1);
BOOST_CHECK_EQUAL(degree(y),1);
BOOST_CHECK_EQUAL(degree(x*x/y),2);
BOOST_CHECK_EQUAL(degree(y/(x*x)),2);
BOOST_CHECK_EQUAL(degree(y/(x*x),{"y"}),1);
BOOST_CHECK_EQUAL(degree(y/(x*x),{"x"}),2);
BOOST_CHECK_EQUAL(degree(y/(x*x),{"z"}),0);
// Check nothing funky is going on with the return type
// (during development, a bad use of std::max with trailing
// return type would end up returning a reference).
BOOST_CHECK((!std::is_reference<decltype(degree(x))>::value));
BOOST_CHECK((!std::is_reference<decltype(degree(x,{"x"}))>::value));
}
};
BOOST_AUTO_TEST_CASE(rational_function_degree_test)
{
boost::mpl::for_each<key_types>(degree_tester());
}
| isuruf/piranha | tests/rational_function_01.cpp | C++ | gpl-3.0 | 52,697 |
#include "spheroid.h"
#include "boost/foreach.hpp"
#include "cinder/app/AppBasic.h"
#include "cinder/gl/Material.h"
#include "cinder/ImageIo.h"
#include "utility/utility.h"
#include "core/azathoth.h"
using namespace cinder;
using namespace cinder::app;
using namespace std;
const double PI = 3.1415926535897;
Spheroid::Spheroid() :
triangles(360),
sphereSpace(20),
vertexCount((90 / sphereSpace+1) * (360 / sphereSpace) * 4),
sCount(0),
kCount(0),
hCount(2),
sSwitch(true),
kSwitch(true),
hSwitch(true),
sinCount(0),
osc1(Oscillator::SINE,100,190,0.01,rand()*0),
osc2(Oscillator::SINE,100,190,0.01,rand()*0),
osc3(Oscillator::SINE,100,190,0.01,rand()*0),
osc4(Oscillator::SINE,100,190,0.01,rand()*0),
osc5(Oscillator::SINE,100,190,0.01,rand()*0),
osc6(Oscillator::SINE,100,190,0.01,rand()*0),
osc7(Oscillator::SINE,100,190,0.01,rand()*0),
osc8(Oscillator::SINE,100,190,0.01,rand()*0),
osc9(Oscillator::SINE,100,190,0.01,rand()*0),
osc10(Oscillator::SINE,100,190,0.01,rand()*0),
osc11(Oscillator::SINE,100,190,0.01,rand()*0),
osc12(Oscillator::SINE,100,190,0.01,rand()*0),
osc13(Oscillator::SINE,100,190,0.01,rand()*0),
osc14(Oscillator::SINE,100,190,0.01,rand()*0),
osc15(Oscillator::SINE,100,190,0.01,rand()*0),
osc16(Oscillator::SINE,100,190,0.01,rand()*0),
osc17(Oscillator::SINE,100,190,0.01,rand()*0),
osc18(Oscillator::SINE,300,380,0.01,rand()*0)
{
std::cout << "SPHEROID!" << std::endl;
try {
gl::Texture::Format fmt;
// fmt.setWrap( GL_REPEAT,GL_REPEAT );
fmt.setWrap(GL_CLAMP,GL_CLAMP);
fmt.enableMipmapping( false );
std::cout << "FORMAT!" << std::endl;
size = 1.0;
#ifndef __LINUX__
diffuseMap = gl::Texture(loadImage(loadResource("Glitch1_COLOR.png")),fmt);
normalMap = gl::Texture(loadImage(loadResource("Glitch1_NRM.png")),fmt);
specularMap = gl::Texture(loadImage(loadResource("Glitch1_SPEC.png")),fmt);
occlusionMap = gl::Texture(loadImage(loadResource("Glitch1_OCC.png")),fmt);
#else
diffuseMap = az::util::loadImageQT("./resources/Glitch1_COLOR.png", fmt);
normalMap = az::util::loadImageQT("./resources/Glitch1_NRM.png", fmt);
specularMap = az::util::loadImageQT("./resources/Glitch1_SPEC.png", fmt);
occlusionMap = az::util::loadImageQT("./resources/Glitch1_OCC.png", fmt);
#endif
std::cout << "TERXTURES LOADED!" << std::endl;
// diffuseMap = az::util::loadPNGTexture(az::getWorkingDirectory().append("/resources/MicroCrystal_COLOR.png"),fmt);
// normalMap = az::util::loadPNGTexture(az::getWorkingDirectory().append("/resources/MicroCrystal_NRM.png"),fmt);
// specularMap = az::util::loadPNGTexture(az::getWorkingDirectory().append("/resources/MicroCrystal_SPEC.png"),fmt);
// occlusionMap = az::util::loadPNGTexture(az::getWorkingDirectory().append("/resources/MicroCrystal_OCC.png"),fmt);
} catch( ... ) {
std::cout << "Unable to load terrain texture" << std::endl;
}
try {
#ifndef __LINUX__
bumpShader = gl::GlslProg( loadResource( "bumpMapping_vert.glsl" ), loadResource( "bumpMapping_frag.glsl" ) );
// bumpShader = gl::GlslProg( loadResource( "phong_vert.glsl" ), loadResource( "phong_frag.glsl" ) );
// bumpShader = gl::GlslProg( loadResource( "blur_vert.glsl" ), loadResource( "blur_frag.glsl" ) );
#else
std::string bumpShaderVert, bumpShaderFrag;
az::util::loadFile("./resources/bumpMapping_vert.glsl", &bumpShaderVert);
az::util::loadFile("./resources/bumpMapping_frag.glsl", &bumpShaderFrag);
bumpShader = gl::GlslProg(bumpShaderVert.c_str(), bumpShaderFrag.c_str());
#endif
} catch( ci::gl::GlslProgCompileExc &exc ) {
std::cout << "Shader compile error: " << std::endl;
std::cout << exc.what();
} catch( ... ) {
std::cout << "Unable to load shader" << std::endl;
}
//Create Layout and init terrainMesh
gl::VboMesh::Layout layout;
layout.setStaticIndices();
layout.setStaticPositions();
layout.setStaticNormals();
layout.setStaticTexCoords2d();
// layout.setDynamicPositions();
// layout.setDynamicColorsRGB();
// layout.setDynamicNormals();
// layout.setDynamicTexCoords2d();
sphereMesh = gl::VboMesh(vertexCount,vertexCount,layout, GL_TRIANGLE_STRIP);
//Create Indicies
vector<u_int32_t> indicies;
int i=0;
while(i<vertexCount) {
indicies.push_back(i);
i++;
}
sphereMesh.bufferIndices(indicies);
createSphere(400.0,getWindowWidth()*-0.4,300,0);
}
int wrap(int kX, int const kLowerBound, int const kUpperBound)
{
int range_size = kUpperBound - kLowerBound + 1;
if (kX < kLowerBound)
kX += range_size * ((kLowerBound - kX) / range_size + 1);
return kLowerBound + (kX - kLowerBound) % range_size;
}
void Spheroid::draw()
{
bumpShader.bind();
diffuseMap.bind(0);
bumpShader.uniform("diffuseTexture",0);
normalMap.bind(1);
bumpShader.uniform("normalTexture",1);
specularMap.bind(2);
bumpShader.uniform("specularTexture",2);
occlusionMap.bind(3);
bumpShader.uniform("occlusionTexture",3);
if(sSwitch) {
sCount++;
if(sCount>100) {
sSwitch = false;
}
} else {
sCount-=1;
if(sCount<-100) {
sSwitch = true;
}
}
if(kSwitch) {
kCount++;
if(kCount>140) {
kSwitch = false;
}
} else {
kCount-=1;
if(kCount<-140) {
kSwitch = true;
}
}
if(hSwitch) {
hCount++;
if(hCount>200) {
hSwitch = false;
}
} else {
hCount-=1;
if(hCount<50) {
hSwitch = true;
}
}
sphereSpace = hCount;
createSphere(400.0,getWindowWidth()*-0.4+(kCount+hCount*2.25),abs(kCount*4)+200,abs(sCount)*15+100);
sinCount++;
gl::pushMatrices();
gl::translate(8000,-16000,10000);
// gl::draw(sphereMesh);
gl::rotate(Vec3f(0,180,0));
gl::draw(sphereMesh);
gl::rotate(Vec3f(0,180,0));
// sphereMesh.unbindBuffers();
gl::popMatrices();
/*
gl::draw(sphereMesh);
gl::rotate(90);
gl::draw(sphereMesh);
gl::rotate(90);
*/
bumpShader.unbind();
diffuseMap.unbind(0);
normalMap.unbind(1);
specularMap.unbind(2);
occlusionMap.unbind(3);
}
void Spheroid::createSphere(double r, double h, double k, double z) {
int n;
double a;
double b;
double sphereSize = 60;
n = 0;
// std::cout << osc2.oscillate() << std::endl;
vector<Vec3f> positions;
vector<Vec3f> normals;
vector<Vec2f> texCoords;
//Put oscillators on every 180 thing.
for( b = 0; b <= osc17.oscillate() - sphereSpace; b+=sphereSpace){
for( a = 0; a <= osc18.oscillate() - sphereSpace; a+=sphereSpace){
Vec3f pos = Vec3f(0,0,0);
Vec3f normal = Vec3f(0,0,0);
Vec2f texCoord = Vec2f(0,0);
pos.x = r * sin((a) / osc1.oscillate() * PI) * sin((b) / osc4.oscillate() * PI) - h;
pos.y = r * cos((a) / osc2.oscillate() * PI) * sin((b) / osc5.oscillate() * PI) + k;
pos.z = r * cos((b) / osc3.oscillate() * PI) - z;
pos = pos * sphereSize;
pos = pos - (pos*0.5);
normal.x = pos.x - h;
normal.y = pos.y - k;
normal.z = pos.z - z;
positions.push_back(pos);
normals.push_back(normal.normalized());
texCoord.x = (sin((a) / osc1.oscillate() * PI) * sin((b) / osc4.oscillate() * PI))*size;
texCoord.y = (cos((a) / osc2.oscillate() * PI) * sin((b) / osc5.oscillate() * PI))*size;
texCoords.push_back(texCoord);
pos.x = r * sin((a) / osc6.oscillate() * PI) * sin((b + sphereSpace) / osc8.oscillate() * PI) - h;
pos.y = r * cos((a) / osc7.oscillate() * PI) * sin((b + sphereSpace) / osc9.oscillate() * PI) + k;
pos.z = r * cos((b + sphereSpace) / 180 * PI) - z;
pos = pos * sphereSize;
pos = pos - (pos*0.5);
normal.x = pos.x - h;
normal.y = pos.y - k;
normal.z = pos.z - z;
positions.push_back(pos);
normals.push_back(normal.normalized());
texCoord.x = (sin((a) / osc6.oscillate() * PI) * sin((b + sphereSpace) / osc8.oscillate() * PI))*size;
texCoord.y = (cos((a) / osc7.oscillate() * PI) * sin((b + sphereSpace) / osc9.oscillate() * PI))*size;
texCoords.push_back(texCoord);
pos.x = r * sin((a + sphereSpace) / osc10.oscillate() * PI) * sin((b) / osc12.oscillate() * PI) - h;
pos.y = r * cos((a + sphereSpace) / osc11.oscillate() * PI) * sin((b) / osc13.oscillate() * PI) + k;
pos.z = r * cos((b) / 176 * PI) + z;
pos = pos * sphereSize;
pos = pos - (pos*0.5);
normal.x = pos.x - h;
normal.y = pos.y - k;
normal.z = pos.z + z;
positions.push_back(pos);
normals.push_back(normal.normalized());
texCoord.x = (sin((a + sphereSpace) / osc10.oscillate() * PI) * sin((b) / 180 * PI))*size;
texCoord.y = (cos((a + sphereSpace) / osc11.oscillate() * PI) * sin((b) / 180 * PI))*size;
texCoords.push_back(texCoord);
pos.x = r * sin((a + sphereSpace) / osc14.oscillate() * PI) * sin((b + sphereSpace) / 182 * PI) - h;
pos.y = r * cos((a + sphereSpace) / osc15.oscillate() * PI) * sin((b + sphereSpace) / 180 * PI) + k;
pos.z = r * cos((b + sphereSpace) / osc16.oscillate() * PI) + z;
pos = pos * sphereSize;
pos = pos - (pos*0.5);
normal.x = pos.x - h;
normal.y = pos.y - k;
normal.z = pos.z - z;
positions.push_back(pos);
normals.push_back(normal.normalized());
texCoord.x = (sin((a + sphereSpace) / osc14.oscillate() * PI) * sin((b + sphereSpace) / 180 * PI))*size;
texCoord.y = (cos((a + sphereSpace) / osc15.oscillate() * PI) * sin((b + sphereSpace) / 180 * PI))*size;
texCoords.push_back(texCoord);
}
}
sphereMesh.bufferPositions(positions);
sphereMesh.bufferNormals(normals);
sphereMesh.bufferTexCoords2d(0,texCoords);
}
| CurtisMcKinney/Simulacra | src/spheroid.cpp | C++ | gpl-3.0 | 10,532 |
/***
* Copyright 2013, 2014 Moises J. Bonilla Caraballo (Neodivert)
*
* This file is part of COMO.
*
* COMO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License v3 as published by
* the Free Software Foundation.
*
* COMO 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 COMO. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef SYSTEM_PRIMITIVES_CREATION_MENU_HPP
#define SYSTEM_PRIMITIVES_CREATION_MENU_HPP
#include <QPushButton>
#include <QFrame>
#include <client/managers/managers/primitives/system_primitives_factory.hpp>
namespace como {
class SystemPrimitivesCreationMenu : public QFrame
{
Q_OBJECT
public:
/***
* 1. Construction
***/
SystemPrimitivesCreationMenu( SystemPrimitivesFactoryPtr geometricPrimitivesFactory );
SystemPrimitivesCreationMenu() = delete;
SystemPrimitivesCreationMenu( const SystemPrimitivesCreationMenu& ) = delete;
SystemPrimitivesCreationMenu( SystemPrimitivesCreationMenu&& ) = delete;
/***
* 2. Destruction
***/
~SystemPrimitivesCreationMenu() = default;
/***
* 3. Operators
***/
SystemPrimitivesCreationMenu& operator = ( const SystemPrimitivesCreationMenu& ) = delete;
SystemPrimitivesCreationMenu& operator = ( SystemPrimitivesCreationMenu&& ) = delete;
private:
/***
* 4. Initialization
***/
QPushButton* createCubeCreationButton() const;
QPushButton* createConeCreationButton() const;
QPushButton* createCylinderCreationButton() const;
QPushButton* createSphereCreationButton() const;
SystemPrimitivesFactoryPtr systemPrimitivesFactory_;
};
} // namespace como
#endif // SYSTEM_PRIMITIVES_CREATION_MENU_HPP
| moisesjbc/como | src/client/gui/tools_menu/system_primitives_creation_menu.hpp | C++ | gpl-3.0 | 2,114 |
.hogan-module-inner{margin-left:auto;margin-right:auto}.hogan-module-width-full{padding:0}.hogan-module-width-full .hogan-module-inner{max-width:100%} | DekodeInteraktiv/hogan-core | assets/css/hogan-core.css | CSS | gpl-3.0 | 150 |
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 15-5-9
* Time: 下午3:12
*/
require_once(dirname(__FILE__) . '/' . 'LogUtils.php');
class HttpManager
{
private static function httpPost($url, $data, $gzip, $action)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, 'GeTui PHP/1.0');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, GTConfig::getHttpConnectionTimeOut());
curl_setopt($curl, CURLOPT_TIMEOUT_MS, GTConfig::getHttpSoTimeOut());
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$header = array("Content-Type:text/html;charset=UTF-8");
if ($gzip) {
$data = gzencode($data, 9);
array_push($header,'Accept-Encoding:gzip');
array_push($header,'Content-Encoding:gzip');
curl_setopt($curl, CURLOPT_ENCODING, "gzip");
}
if(!is_null($action))
{
array_push($header,"Gt-Action:".$action);
}
curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_version = curl_version();
if ($curl_version['version_number'] >= 462850) {
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 30000);
curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
}
//通过代理访问接口需要在此处配置代理
//curl_setopt($curl, CURLOPT_PROXY, '192.168.1.18:808');
//请求失败有3次重试机会
$result = HttpManager::exeBySetTimes(3, $curl);
curl_close($curl);
return $result;
}
public static function httpHead($url)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, 'GeTui PHP/1.0');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, GTConfig::getHttpConnectionTimeOut());
curl_setopt($curl, CURLOPT_TIMEOUT_MS, GTConfig::getHttpSoTimeOut());
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$header = array("Content-Type:text/html;charset=UTF-8");
curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
$curl_version = curl_version();
if ($curl_version['version_number'] >= 462850) {
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 30000);
curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
}
//通过代理访问接口需要在此处配置代理
//curl_setopt($curl, CURLOPT_PROXY, '192.168.1.18:808');
//请求失败有3次重试机会
$result = HttpManager::exeBySetTimes(3, $curl);
curl_close($curl);
return $result;
}
public static function httpPostJson($url, $params, $gzip)
{
if(!isset($params["version"]))
{
$params["version"] = GTConfig::getSDKVersion();
}
$action = $params["action"];
$data = json_encode($params);
$result = null;
try {
$resp = HttpManager::httpPost($url, $data, $gzip, $action);
//LogUtils::debug("发送请求 post:{$data} return:{$resp}");
$result = json_decode($resp, true);
return $result;
} catch (Exception $e) {
throw new RequestException($params["requestId"],"httpPost:[".$url."] [" .$data." ] [ ".$result."]:",$e);
}
}
private static function exeBySetTimes($count, $curl)
{
$result = curl_exec($curl);
$info = curl_getinfo($curl);
$code = $info["http_code"];
if (curl_errno($curl) != 0 && $code != 200) {
LogUtils::debug("request errno: ".curl_errno($curl).",url:".$info["url"]);
$count--;
if ($count > 0) {
$result = HttpManager::exeBySetTimes($count, $curl);
}
}
return $result;
}
} | xiaoxianlink/zhideinfo | application/Common/getui/igetui/utils/HttpManager.php | PHP | gpl-3.0 | 4,272 |
/*
Copyright © 2009 Jim Porter
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, see <http://www.gnu.org/licenses/>.
*/
#include "proto.h"
void CALLBACK TwitterProto::APC_callback(ULONG_PTR p)
{
reinterpret_cast<TwitterProto*>(p)->LOG("***** Executing APC");
}
template<typename T>
inline static T db_pod_get(HANDLE hContact,const char *module,const char *setting,
T errorValue)
{
DBVARIANT dbv;
DBCONTACTGETSETTING cgs;
cgs.szModule = module;
cgs.szSetting = setting;
cgs.pValue = &dbv;
if(CallService(MS_DB_CONTACT_GETSETTING,(WPARAM)hContact,(LPARAM)&cgs))
return errorValue;
// TODO: remove this, it's just a temporary workaround
if(dbv.type == DBVT_DWORD)
return dbv.dVal;
if(dbv.cpbVal != sizeof(T))
return errorValue;
return *reinterpret_cast<T*>(dbv.pbVal);
}
template<typename T>
inline static INT_PTR db_pod_set(HANDLE hContact,const char *module,const char *setting,
T val)
{
DBCONTACTWRITESETTING cws;
cws.szModule = module;
cws.szSetting = setting;
cws.value.type = DBVT_BLOB;
cws.value.cpbVal = sizeof(T);
cws.value.pbVal = reinterpret_cast<BYTE*>(&val);
return CallService(MS_DB_CONTACT_WRITESETTING,(WPARAM)hContact,(LPARAM)&cws);
}
void TwitterProto::SignOn(void*)
{
LOG("***** Beginning SignOn process");
WaitForSingleObject(&signon_lock_,INFINITE);
// Kill the old thread if it's still around
if(hMsgLoop_)
{
LOG("***** Requesting MessageLoop to exit");
QueueUserAPC(APC_callback,hMsgLoop_,(ULONG_PTR)this);
LOG("***** Waiting for old MessageLoop to exit");
WaitForSingleObject(hMsgLoop_,INFINITE);
CloseHandle(hMsgLoop_);
}
if(NegotiateConnection()) // Could this be? The legendary Go Time??
{
if(!in_chat_ && db_byte_get(0,m_szModuleName,TWITTER_KEY_CHATFEED,0))
OnJoinChat(0,true);
SetAllContactStatuses(ID_STATUS_ONLINE);
hMsgLoop_ = ForkThreadEx(&TwitterProto::MessageLoop,this);
}
ReleaseMutex(signon_lock_);
LOG("***** SignOn complete");
}
bool TwitterProto::NegotiateConnection()
{
LOG("***** Negotiating connection with Twitter");
int old_status = m_iStatus;
std::string user,pass;
DBVARIANT dbv;
if( !DBGetContactSettingString(0,m_szModuleName,TWITTER_KEY_UN,&dbv) )
{
user = dbv.pszVal;
DBFreeVariant(&dbv);
}
else
{
ShowPopup(TranslateT("Please enter a username."));
return false;
}
if( !DBGetContactSettingString(0,m_szModuleName,TWITTER_KEY_PASS,&dbv) )
{
CallService(MS_DB_CRYPT_DECODESTRING,strlen(dbv.pszVal)+1,
reinterpret_cast<LPARAM>(dbv.pszVal));
pass = dbv.pszVal;
DBFreeVariant(&dbv);
}
else
{
ShowPopup(TranslateT("Please enter a password."));
return false;
}
if( !DBGetContactSettingString(0,m_szModuleName,TWITTER_KEY_BASEURL,&dbv) )
{
ScopedLock s(twitter_lock_);
twit_.set_base_url(dbv.pszVal);
DBFreeVariant(&dbv);
}
bool success;
{
ScopedLock s(twitter_lock_);
success = twit_.set_credentials(user,pass);
}
if(!success)
{
ShowPopup(TranslateT("Your username/password combination was incorrect."));
ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_FAILED,
(HANDLE)old_status,m_iStatus);
// Set to offline
old_status = m_iStatus;
m_iDesiredStatus = m_iStatus = ID_STATUS_OFFLINE;
ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,
(HANDLE)old_status,m_iStatus);
return false;
}
else
{
m_iStatus = m_iDesiredStatus;
ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,
(HANDLE)old_status,m_iStatus);
return true;
}
}
void TwitterProto::MessageLoop(void*)
{
LOG("***** Entering Twitter::MessageLoop");
since_id_ = db_pod_get<twitter_id>(0,m_szModuleName,TWITTER_KEY_SINCEID,0);
dm_since_id_ = db_pod_get<twitter_id>(0,m_szModuleName,TWITTER_KEY_DMSINCEID,0);
bool new_account = db_byte_get(0,m_szModuleName,TWITTER_KEY_NEW,1) != 0;
bool popups = db_byte_get(0,m_szModuleName,TWITTER_KEY_POPUP_SIGNON,1) != 0;
int poll_rate = db_dword_get(0,m_szModuleName,TWITTER_KEY_POLLRATE,80);
for(unsigned int i=0;;i++)
{
if(m_iStatus != ID_STATUS_ONLINE)
goto exit;
if(i%4 == 0)
UpdateFriends();
if(m_iStatus != ID_STATUS_ONLINE)
goto exit;
UpdateStatuses(new_account,popups);
if(m_iStatus != ID_STATUS_ONLINE)
goto exit;
UpdateMessages(new_account);
if(new_account) // Not anymore!
{
new_account = false;
DBWriteContactSettingByte(0,m_szModuleName,TWITTER_KEY_NEW,0);
}
if(m_iStatus != ID_STATUS_ONLINE)
goto exit;
LOG("***** TwitterProto::MessageLoop going to sleep...");
if(SleepEx(poll_rate*1000,true) == WAIT_IO_COMPLETION)
goto exit;
LOG("***** TwitterProto::MessageLoop waking up...");
popups = true;
}
exit:
{
ScopedLock s(twitter_lock_);
twit_.set_credentials("","",false);
}
LOG("***** Exiting TwitterProto::MessageLoop");
}
struct update_avatar
{
update_avatar(HANDLE hContact,const std::string &url) : hContact(hContact),url(url) {}
HANDLE hContact;
std::string url;
};
void TwitterProto::UpdateAvatarWorker(void *p)
{
if(p == 0)
return;
std::auto_ptr<update_avatar> data( static_cast<update_avatar*>(p) );
DBVARIANT dbv;
if(DBGetContactSettingString(data->hContact,m_szModuleName,TWITTER_KEY_UN,&dbv))
return;
std::string ext = data->url.substr(data->url.rfind('.'));
std::string filename = GetAvatarFolder() + '\\' + dbv.pszVal + ext;
DBFreeVariant(&dbv);
PROTO_AVATAR_INFORMATION ai = {sizeof(ai)};
ai.hContact = data->hContact;
ai.format = ext_to_format(ext);
strncpy(ai.filename,filename.c_str(),MAX_PATH);
LOG("***** Updating avatar: %s",data->url.c_str());
WaitForSingleObjectEx(avatar_lock_,INFINITE,true);
if(CallService(MS_SYSTEM_TERMINATED,0,0))
{
LOG("***** Terminating avatar update early: %s",data->url.c_str());
return;
}
if(save_url(hAvatarNetlib_,data->url,filename))
{
DBWriteContactSettingString(data->hContact,m_szModuleName,TWITTER_KEY_AV_URL,
data->url.c_str());
ProtoBroadcastAck(m_szModuleName,data->hContact,ACKTYPE_AVATAR,
ACKRESULT_SUCCESS,&ai,0);
}
else
ProtoBroadcastAck(m_szModuleName,data->hContact,ACKTYPE_AVATAR,
ACKRESULT_FAILED, &ai,0);
ReleaseMutex(avatar_lock_);
LOG("***** Done avatar: %s",data->url.c_str());
}
void TwitterProto::UpdateAvatar(HANDLE hContact,const std::string &url,bool force)
{
DBVARIANT dbv;
if( !force &&
( !DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_AV_URL,&dbv) &&
url == dbv.pszVal) )
{
LOG("***** Avatar already up-to-date: %s",url.c_str());
}
else
{
// TODO: more defaults (configurable?)
if(url == "http://static.twitter.com/images/default_profile_normal.png")
{
PROTO_AVATAR_INFORMATION ai = {sizeof(ai),hContact};
db_string_set(hContact,m_szModuleName,TWITTER_KEY_AV_URL,url.c_str());
ProtoBroadcastAck(m_szModuleName,hContact,ACKTYPE_AVATAR,
ACKRESULT_SUCCESS,&ai,0);
}
else
{
ForkThread(&TwitterProto::UpdateAvatarWorker, this,
new update_avatar(hContact,url));
}
}
DBFreeVariant(&dbv);
}
void TwitterProto::UpdateFriends()
{
try
{
ScopedLock s(twitter_lock_);
std::vector<twitter_user> friends = twit_.get_friends();
s.Unlock();
for(std::vector<twitter_user>::iterator i=friends.begin(); i!=friends.end(); ++i)
{
if(i->username == twit_.get_username())
continue;
HANDLE hContact = AddToClientList(i->username.c_str(),i->status.text.c_str());
UpdateAvatar(hContact,i->profile_image_url);
}
LOG("***** Friends list updated");
}
catch(const bad_response &)
{
LOG("***** Bad response from server, signing off");
SetStatus(ID_STATUS_OFFLINE);
}
catch(const std::exception &e)
{
ShowPopup( (std::string("While updating friends list, an error occurred: ")
+e.what()).c_str() );
LOG("***** Error updating friends list: %s",e.what());
}
}
void TwitterProto::ShowContactPopup(HANDLE hContact,const std::string &text)
{
if(!ServiceExists(MS_POPUP_ADDPOPUPT) || DBGetContactSettingByte(0,
m_szModuleName,TWITTER_KEY_POPUP_SHOW,0) == 0)
{
return;
}
POPUPDATAT popup = {};
popup.lchContact = hContact;
popup.iSeconds = db_dword_get(0,m_szModuleName,TWITTER_KEY_POPUP_TIMEOUT,0);
popup.colorBack = db_dword_get(0,m_szModuleName,TWITTER_KEY_POPUP_COLBACK,0);
if(popup.colorBack == 0xFFFFFFFF)
popup.colorBack = GetSysColor(COLOR_WINDOW);
popup.colorText = db_dword_get(0,m_szModuleName,TWITTER_KEY_POPUP_COLTEXT,0);
if(popup.colorBack == 0xFFFFFFFF)
popup.colorBack = GetSysColor(COLOR_WINDOWTEXT);
DBVARIANT dbv;
if( !DBGetContactSettingString(hContact,"CList","MyHandle",&dbv) ||
!DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_UN,&dbv) )
{
mbcs_to_tcs(CP_UTF8,dbv.pszVal,popup.lptzContactName,MAX_CONTACTNAME);
DBFreeVariant(&dbv);
}
mbcs_to_tcs(CP_UTF8,text.c_str(),popup.lptzText,MAX_SECONDLINE);
CallService(MS_POPUP_ADDPOPUPT,reinterpret_cast<WPARAM>(&popup),0);
}
void TwitterProto::UpdateStatuses(bool pre_read,bool popups)
{
try
{
ScopedLock s(twitter_lock_);
twitter::status_list updates = twit_.get_statuses(200,since_id_);
s.Unlock();
if(!updates.empty())
since_id_ = std::max(since_id_, updates[0].status.id);
for(twitter::status_list::reverse_iterator i=updates.rbegin(); i!=updates.rend(); ++i)
{
if(!pre_read && in_chat_)
UpdateChat(*i);
if(i->username == twit_.get_username())
continue;
HANDLE hContact = AddToClientList(i->username.c_str(),"");
DBEVENTINFO dbei = {sizeof(dbei)};
dbei.pBlob = (BYTE*)(i->status.text.c_str());
dbei.cbBlob = i->status.text.size()+1;
dbei.eventType = TWITTER_DB_EVENT_TYPE_TWEET;
dbei.flags = DBEF_UTF;
//dbei.flags = DBEF_READ;
dbei.timestamp = static_cast<DWORD>(i->status.time);
dbei.szModule = m_szModuleName;
CallService(MS_DB_EVENT_ADD, (WPARAM)hContact, (LPARAM)&dbei);
DBWriteContactSettingUTF8String(hContact,"CList","StatusMsg",
i->status.text.c_str());
if(!pre_read && popups)
ShowContactPopup(hContact,i->status.text);
}
db_pod_set(0,m_szModuleName,TWITTER_KEY_SINCEID,since_id_);
LOG("***** Status messages updated");
}
catch(const bad_response &)
{
LOG("***** Bad response from server, signing off");
SetStatus(ID_STATUS_OFFLINE);
}
catch(const std::exception &e)
{
ShowPopup( (std::string("While updating status messages, an error occurred: ")
+e.what()).c_str() );
LOG("***** Error updating status messages: %s",e.what());
}
}
void TwitterProto::UpdateMessages(bool pre_read)
{
try
{
ScopedLock s(twitter_lock_);
twitter::status_list messages = twit_.get_direct(dm_since_id_);
s.Unlock();
if(messages.size())
dm_since_id_ = std::max(dm_since_id_, messages[0].status.id);
for(twitter::status_list::reverse_iterator i=messages.rbegin(); i!=messages.rend(); ++i)
{
HANDLE hContact = AddToClientList(i->username.c_str(),"");
PROTORECVEVENT recv = {};
CCSDATA ccs = {};
recv.flags = PREF_UTF;
if(pre_read)
recv.flags |= PREF_CREATEREAD;
recv.szMessage = const_cast<char*>(i->status.text.c_str());
recv.timestamp = static_cast<DWORD>(i->status.time);
ccs.hContact = hContact;
ccs.szProtoService = PSR_MESSAGE;
ccs.wParam = ID_STATUS_ONLINE;
ccs.lParam = reinterpret_cast<LPARAM>(&recv);
CallService(MS_PROTO_CHAINRECV,0,reinterpret_cast<LPARAM>(&ccs));
}
db_pod_set(0,m_szModuleName,TWITTER_KEY_DMSINCEID,dm_since_id_);
LOG("***** Direct messages updated");
}
catch(const bad_response &)
{
LOG("***** Bad response from server, signing off");
SetStatus(ID_STATUS_OFFLINE);
}
catch(const std::exception &e)
{
ShowPopup( (std::string("While updating direct messages, an error occurred: ")
+e.what()).c_str() );
LOG("***** Error updating direct messages: %s",e.what());
}
} | dentist/miranda-twitter | connection.cpp | C++ | gpl-3.0 | 12,656 |
/* -*- mia-c++ -*-
*
* This file is part of MIA - a toolbox for medical image analysis
* Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny
*
* MIA 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.
*
* 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 MIA; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <mia/core/histogram.hh>
#include <mia/core/cmdlineparser.hh>
#include <mia/core/kmeans.hh>
#include <mia/core/parallel.hh>
#include <mia/core/threadedmsg.hh>
#include <mia/2d.hh>
#include <memory>
#include <vector>
using namespace mia;
using namespace std;
typedef vector<C2DFImage> C2DFImageVec;
const SProgramDescription g_description = {
{pdi_group, "Analysis, filtering, combining, and segmentation of 2D images"},
{pdi_short, "Run a k-means segmentation of a 2D image."},
{
pdi_description, "This program runs the segmentation of a 2D image by applying "
"a localized k-means approach that helps to overcome intensity inhomogeneities "
"in the image. The approach evaluates a global k-means clustering, and then "
"separates the image into overlapping regions where more k-means iterations "
"are run only including the locally present classes, i.e. the classes that "
"relatively contain more pixels than a given threshold."
},
{
pdi_example_descr, "Run the segmentation on image test.png using three classes, "
"local regions of 40 pixels (grid width 20 pixels), and a class ignore threshold of 0.01."
},
{pdi_example_code, "-i test.png -o label.png -n 3 -g 20 -t 0.01"}
};
class FKmeans: public TFilter<unsigned>
{
public:
FKmeans(const vector<double>& in_classes, double rel_cluster_threshold);
void set_position_and_range(int x, int y, const C2DBounds& start, const C2DBounds& end);
template <typename T>
unsigned operator () (const T2DImage<T>& image) const;
private:
vector<double> m_in_classes;
double m_rel_cluster_threshold;
C2DBounds m_start;
C2DBounds m_end;
int m_x;
int m_y;
};
class FKMeansLocal: public TFilter<P2DImage>
{
public:
FKMeansLocal(const vector<C2DDImage>& class_centers);
template <typename T>
P2DImage operator () (const T2DImage<T>& image) const;
private:
const vector<C2DDImage>& m_class_centers;
};
int do_main(int argc, char *argv[])
{
string in_filename;
string out_filename;
int window = 20;
unsigned n_classes = 3;
double rel_cluster_threshold = 0.0001;
const auto& image2dio = C2DImageIOPluginHandler::instance();
CCmdOptionList opts(g_description);
opts.set_group("File-IO");
opts.add(make_opt( in_filename, "in-file", 'i', "image to be segmented", CCmdOptionFlags::required_input, &image2dio ));
opts.add(make_opt( out_filename, "out-file", 'o', "class label image based on merging local labels",
CCmdOptionFlags::required_output, &image2dio ));
opts.set_group("Parameters");
opts.add(make_opt( window, EParameterBounds::bf_min_closed, {3},
"window", 'w', "Window size around the pixel to be analyzed"));
opts.add(make_opt( n_classes, EParameterBounds::bf_closed_interval, {2u, 127u},
"nclasses", 'n', "Number of intensity classes to segment"));
opts.add(make_opt( rel_cluster_threshold, EParameterBounds::bf_min_closed | EParameterBounds::bf_max_open,
{0.0, 1.0}, "relative-cluster-threshold", 't', "Number of intensity classes to segment"));
if (opts.parse(argc, argv) != CCmdOptionList::hr_no)
return EXIT_SUCCESS;
auto in_image = load_image2d(in_filename);
stringstream kfilter_ss;
kfilter_ss << "kmeans:c=" << n_classes;
auto full_kmeans = run_filter(in_image, kfilter_ss.str().c_str());
auto full_classes_ptr = full_kmeans->get_attribute(ATTR_IMAGE_KMEANS_CLASSES);
const CVDoubleAttribute& full_classes = dynamic_cast<const CVDoubleAttribute&>(*full_classes_ptr);
C2DUBImage result_labels(in_image->get_size(), *in_image);
auto run_classification = [&result_labels, &full_classes, rel_cluster_threshold, window, &in_image]
(const C1DParallelRange & range) {
CThreadMsgStream thread_stream;
FKmeans local_kmeans(full_classes, rel_cluster_threshold);
for ( int y = range.begin(); y != range.end(); ++y ) {
auto ir = result_labels.begin_at(0, y);
for (unsigned x = 0; x < in_image->get_size().x; ++x, ++ir) {
C2DBounds start( x - window, y - window);
C2DBounds end( x + window, y + window);
if (start.x > in_image->get_size().x)
start.x = 0;
if (start.y > in_image->get_size().y)
start.y = 0;
if (end.x > in_image->get_size().x)
end.x = in_image->get_size().x;
if (end.y > in_image->get_size().y)
end.y = in_image->get_size().y;
local_kmeans.set_position_and_range(x, y, start, end);
*ir = mia::filter(local_kmeans, *in_image);
}
}
};
pfor(C1DParallelRange( 0, in_image->get_size().y), run_classification);
save_image(out_filename, result_labels);
return EXIT_SUCCESS;
}
FKmeans::FKmeans(const vector<double>& in_classes,
double rel_cluster_threshold):
m_in_classes(in_classes),
m_rel_cluster_threshold(rel_cluster_threshold)
{
}
void FKmeans::set_position_and_range(int x, int y, const C2DBounds& start, const C2DBounds& end)
{
m_start = start;
m_end = end;
m_x = x;
m_y = y;
}
template <typename T>
unsigned FKmeans::operator () (const T2DImage<T>& image) const
{
size_t n = (m_end.x - m_start.x) * (m_end.y - m_start.y);
vector<T> buffer(n);
copy(image.begin_range(m_start, m_end), image.end_range(m_start, m_end), buffer.begin());
auto i = buffer.begin();
auto iend = buffer.end();
vector<size_t> cluster_sizes(m_in_classes.size());
size_t l = m_in_classes.size() - 1;
vector<int> class_relation(n);
auto ic = class_relation.begin();
while ( i != iend ) {
const unsigned c = kmeans_get_closest_clustercenter(m_in_classes, l, *i);
++cluster_sizes[c];
*ic++ = c;
++i;
}
vector<double> rel_cluster_sizes(m_in_classes.size());
transform(cluster_sizes.begin(), cluster_sizes.end(), rel_cluster_sizes.begin(),
[n](double x) {
return x / n;
});
vector<double> result(m_in_classes);
vector<bool> fixed_centers(m_in_classes.size(), false);
for (unsigned i = 0; i < m_in_classes.size(); ++i) {
if (rel_cluster_sizes[i] <= m_rel_cluster_threshold) {
fixed_centers[i] = true;
}
}
int biggest_class = -1;
// iterate to update the class centers
for (size_t l = 1; l < 4; l++) {
if (kmeans_step_with_fixed_centers(buffer.begin(), buffer.end(), class_relation.begin(),
result, fixed_centers, result.size() - 1, biggest_class))
break;
}
auto c = kmeans_get_closest_clustercenter(result, result.size() - 1, image(m_x, m_y));
cvdebug() << "Block [" << m_x << ":" << m_y << "]@[" << m_start
<< "],[" << m_end << "] " << image(m_x, m_y) << " c=" << c
<< ", Relative cluster sizes: " << rel_cluster_sizes << "\n";
return c;
}
#include <mia/internal/main.hh>
MIA_MAIN(do_main);
| gerddie/mia | src/2dsegment-per-pixel-kmeans.cc | C++ | gpl-3.0 | 8,602 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class AddForeignKeysToTaskRulesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('task_rules', function(Blueprint $table)
{
$table->foreign('abort_on')->references('code')->on('event_name')->onUpdate('CASCADE')->onDelete('RESTRICT');
$table->foreign('for_category')->references('code')->on('matter_category')->onUpdate('CASCADE')->onDelete('RESTRICT');
$table->foreign('condition_event')->references('code')->on('event_name')->onUpdate('CASCADE')->onDelete('RESTRICT');
$table->foreign('for_country')->references('iso')->on('country')->onUpdate('CASCADE')->onDelete('RESTRICT');
$table->foreign('task')->references('code')->on('event_name')->onUpdate('CASCADE')->onDelete('RESTRICT');
$table->foreign('for_origin')->references('iso')->on('country')->onUpdate('CASCADE')->onDelete('RESTRICT');
$table->foreign('trigger_event')->references('code')->on('event_name')->onUpdate('CASCADE')->onDelete('RESTRICT');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('task_rules', function(Blueprint $table)
{
$table->dropForeign(['abort_on']);
$table->dropForeign(['for_category']);
$table->dropForeign(['condition_event']);
$table->dropForeign(['for_country']);
$table->dropForeign(['task']);
$table->dropForeign(['for_origin']);
$table->dropForeign(['trigger_event']);
});
}
}
| jjdejong/phpip | database/migrations/2018_12_07_184312_add_foreign_keys_to_task_rules_table.php | PHP | gpl-3.0 | 1,553 |
#!/bin/sh
# collect Android device info over ADB connection
# This is for use on Linux or other Unix-like systems. You must have ADB, and may (or may not) need root access
# on your desktop/laptop system to run ADB. It requires developer access on the tablet, but not root.
#
# Copyright 2021 by Ian Kluft
# released as Open Source Software under the GNU General Public License Version 3.
# See https://www.gnu.org/licenses/gpl.txt
#
# Current source code for this script can be found at
# https://github.com/ikluft/ikluft-tools/blob/master/scripts/android-deviceinfo.sh
# function to exit with an error message
die()
{
# print an error and exit
echo $@ >&2
exit 1
}
# print script action
echo Android device info collector
# find ADB
adb=$(which adb 2>/dev/null)
if [ -z "$adb" ]
then
die "adb is required to be installed in order to run this script - not found in PATH"
fi
echo "adb found at $adb"
$adb start-server \
|| die "adb server must be started (as root) before running this script"
if [ $($adb devices | fgrep -v 'List of devices' | grep -v '^$' | wc -l) -eq 0 ]
then
die "adb does not detect any connected Android devices"
fi
# get device brand and model for output file prefixes
brand=$($adb shell getprop ro.product.brand)
model=$($adb shell getprop ro.product.name)
if [ -z "$brand" -o -z "$model" ]
then
die "could not read device brand or model"
fi
echo "device found: brand=$brand model=$model"
# collect various system data into separate files
devdir="${XDG_DATA_HOME:-${HOME}/.local/share}/deviceinfo/$brand-$model"
mkdir -p $devdir || die "failed to create device info directory at $devdir"
echo "saving data files in $devdir"
echo collecting uname data
$adb shell uname -a > "$devdir/$brand-$model-uname" || die "uname failed"
echo collecting cpuinfo data
$adb shell cat /proc/cpuinfo > "$devdir/$brand-$model-cpuinfo" || die "cpuinfo failed"
echo collecting dumpsys data
$adb shell dumpsys > "$devdir/$brand-$model-dumpsys" || die "dumpsys failed"
echo collecting getprop data
$adb shell getprop > "$devdir/$brand-$model-getprop" || die "getprop failed"
echo collecting system settings data
$adb shell settings list system > "$devdir/$brand-$model-settings-system" || die "system settings list failed"
echo collecting secure settings data
$adb shell settings list secure > "$devdir/$brand-$model-settings-secure" || die "secure settings list failed"
echo collecting global settings data
$adb shell settings list global > "$devdir/$brand-$model-settings-global" || die "global settings list failed"
echo collecting window manager data
{
$adb shell wm size || die "window manager size failed"
$adb shell wm density || die "window manager density failed"
} > "$devdir/$brand-$model-windowmanager"
echo done
| ikluft/ikluft-tools | scripts/android-deviceinfo.sh | Shell | gpl-3.0 | 2,742 |
from quicktions import Fraction
from . import (
_update,
deprecated,
enumerate,
format,
get,
illustrators,
io,
iterate,
iterpitches,
lyconst,
lyenv,
makers,
mutate,
persist,
string,
wf,
)
from ._version import __version__, __version_info__
from .bind import Wrapper, annotate, attach, detach
from .bundle import LilyPondFormatBundle, SlotContributions
from .configuration import (
Configuration,
list_all_classes,
list_all_functions,
yield_all_modules,
)
from .contextmanagers import (
ContextManager,
FilesystemState,
ForbidUpdate,
NullContextManager,
ProgressIndicator,
RedirectedStreams,
TemporaryDirectory,
TemporaryDirectoryChange,
Timer,
)
from .cyclictuple import CyclicTuple
from .duration import Duration, Multiplier, NonreducedFraction, Offset
from .dynamic import Dynamic
from .enums import (
Center,
Comparison,
Down,
Exact,
HorizontalAlignment,
Left,
Less,
Middle,
More,
Right,
Up,
VerticalAlignment,
)
from .exceptions import (
AssignabilityError,
ImpreciseMetronomeMarkError,
LilyPondParserError,
MissingMetronomeMarkError,
ParentageError,
PersistentIndicatorError,
SchemeParserFinishedError,
UnboundedTimeIntervalError,
WellformednessError,
)
from .format import lilypond
from .get import Lineage
from .illustrators import illustrate
from .indicators import (
Arpeggio,
Articulation,
BarLine,
BeamCount,
BendAfter,
BreathMark,
Clef,
ColorFingering,
Fermata,
Glissando,
KeyCluster,
KeySignature,
LaissezVibrer,
MarginMarkup,
MetronomeMark,
Mode,
Ottava,
RehearsalMark,
Repeat,
RepeatTie,
StaffChange,
StaffPosition,
StartBeam,
StartGroup,
StartHairpin,
StartMarkup,
StartPhrasingSlur,
StartPianoPedal,
StartSlur,
StartTextSpan,
StartTrillSpan,
StemTremolo,
StopBeam,
StopGroup,
StopHairpin,
StopPhrasingSlur,
StopPianoPedal,
StopSlur,
StopTextSpan,
StopTrillSpan,
Tie,
TimeSignature,
)
from .instruments import (
Accordion,
AltoFlute,
AltoSaxophone,
AltoTrombone,
AltoVoice,
BaritoneSaxophone,
BaritoneVoice,
BassClarinet,
BassFlute,
BassSaxophone,
BassTrombone,
BassVoice,
Bassoon,
Cello,
ClarinetInA,
ClarinetInBFlat,
ClarinetInEFlat,
Contrabass,
ContrabassClarinet,
ContrabassFlute,
ContrabassSaxophone,
Contrabassoon,
EnglishHorn,
Flute,
FrenchHorn,
Glockenspiel,
Guitar,
Harp,
Harpsichord,
Instrument,
Marimba,
MezzoSopranoVoice,
Oboe,
Percussion,
Piano,
Piccolo,
SopraninoSaxophone,
SopranoSaxophone,
SopranoVoice,
StringNumber,
TenorSaxophone,
TenorTrombone,
TenorVoice,
Trumpet,
Tuba,
Tuning,
Vibraphone,
Viola,
Violin,
Xylophone,
)
from .io import graph, show
from .label import ColorMap
from .lilypondfile import Block, LilyPondFile
from .lyproxy import (
LilyPondContext,
LilyPondEngraver,
LilyPondGrob,
LilyPondGrobInterface,
)
from .makers import LeafMaker, NoteMaker
from .markups import Markup
from .math import Infinity, NegativeInfinity
from .meter import Meter, MeterList, MetricAccentKernel
from .metricmodulation import MetricModulation
from .obgc import OnBeatGraceContainer, on_beat_grace_container
from .overrides import (
IndexedTweakManager,
IndexedTweakManagers,
Interface,
LilyPondLiteral,
LilyPondOverride,
LilyPondSetting,
OverrideInterface,
SettingInterface,
TweakInterface,
override,
setting,
tweak,
)
from .parentage import Parentage
from .parsers import parser
from .parsers.base import Parser
from .parsers.parse import parse
from .pattern import Pattern, PatternTuple
from .pcollections import (
IntervalClassSegment,
IntervalClassSet,
IntervalSegment,
IntervalSet,
PitchClassSegment,
PitchClassSet,
PitchRange,
PitchSegment,
PitchSet,
Segment,
Set,
TwelveToneRow,
)
from .pitch import (
Accidental,
Interval,
IntervalClass,
NamedInterval,
NamedIntervalClass,
NamedInversionEquivalentIntervalClass,
NamedPitch,
NamedPitchClass,
NumberedInterval,
NumberedIntervalClass,
NumberedInversionEquivalentIntervalClass,
NumberedPitch,
NumberedPitchClass,
Octave,
Pitch,
PitchClass,
PitchTyping,
)
from .ratio import NonreducedRatio, Ratio
from .score import (
AfterGraceContainer,
BeforeGraceContainer,
Chord,
Cluster,
Component,
Container,
Context,
DrumNoteHead,
Leaf,
MultimeasureRest,
Note,
NoteHead,
NoteHeadList,
Rest,
Score,
Skip,
Staff,
StaffGroup,
TremoloContainer,
Tuplet,
Voice,
)
from .select import LogicalTie, Selection
from .setclass import SetClass
from .spanners import (
beam,
glissando,
hairpin,
horizontal_bracket,
ottava,
phrasing_slur,
piano_pedal,
slur,
text_spanner,
tie,
trill_spanner,
)
from .tag import Line, Tag, activate, deactivate
from .timespan import OffsetCounter, Timespan, TimespanList
from .typedcollections import TypedCollection, TypedFrozenset, TypedList, TypedTuple
from .typings import (
DurationSequenceTyping,
DurationTyping,
IntegerPair,
IntegerSequence,
Number,
NumberPair,
PatternTyping,
Prototype,
RatioSequenceTyping,
RatioTyping,
Strings,
)
from .verticalmoment import (
VerticalMoment,
iterate_leaf_pairs,
iterate_pitch_pairs,
iterate_vertical_moments,
)
index = Pattern.index
index_all = Pattern.index_all
index_first = Pattern.index_first
index_last = Pattern.index_last
__all__ = [
"Accidental",
"Accordion",
"AfterGraceContainer",
"AltoFlute",
"AltoSaxophone",
"AltoTrombone",
"AltoVoice",
"Arpeggio",
"Articulation",
"AssignabilityError",
"BarLine",
"BaritoneSaxophone",
"BaritoneVoice",
"BassClarinet",
"BassFlute",
"BassSaxophone",
"BassTrombone",
"BassVoice",
"Bassoon",
"BeamCount",
"BeforeGraceContainer",
"BendAfter",
"Block",
"BreathMark",
"Cello",
"Center",
"Chord",
"ClarinetInA",
"ClarinetInBFlat",
"ClarinetInEFlat",
"Clef",
"Cluster",
"ColorFingering",
"ColorMap",
"Comparison",
"Component",
"Configuration",
"Container",
"Context",
"ContextManager",
"Contrabass",
"ContrabassClarinet",
"ContrabassFlute",
"ContrabassSaxophone",
"Contrabassoon",
"CyclicTuple",
"Down",
"DrumNoteHead",
"Duration",
"DurationSequenceTyping",
"DurationTyping",
"Dynamic",
"EnglishHorn",
"Exact",
"Expression",
"Fermata",
"FilesystemState",
"Flute",
"ForbidUpdate",
"Fraction",
"FrenchHorn",
"Glissando",
"Glockenspiel",
"Guitar",
"Harp",
"Harpsichord",
"HorizontalAlignment",
"ImpreciseMetronomeMarkError",
"IndexedTweakManager",
"IndexedTweakManagers",
"Infinity",
"Instrument",
"IntegerPair",
"IntegerSequence",
"Interface",
"Interval",
"IntervalClass",
"IntervalClassSegment",
"IntervalClassSet",
"IntervalSegment",
"IntervalSet",
"KeyCluster",
"KeySignature",
"LaissezVibrer",
"Leaf",
"LeafMaker",
"Left",
"Less",
"LilyPondContext",
"LilyPondEngraver",
"LilyPondFile",
"LilyPondFormatBundle",
"LilyPondGrob",
"LilyPondGrobInterface",
"LilyPondLiteral",
"LilyPondOverride",
"LilyPondParserError",
"LilyPondSetting",
"Line",
"Lineage",
"LogicalTie",
"MarginMarkup",
"Marimba",
"Markup",
"Meter",
"MeterList",
"MetricAccentKernel",
"MetricModulation",
"MetronomeMark",
"MezzoSopranoVoice",
"Middle",
"MissingMetronomeMarkError",
"Mode",
"More",
"MultimeasureRest",
"Multiplier",
"NamedInterval",
"NamedIntervalClass",
"NamedInversionEquivalentIntervalClass",
"NamedPitch",
"NamedPitchClass",
"NegativeInfinity",
"NonreducedFraction",
"NonreducedRatio",
"Note",
"NoteHead",
"NoteHeadList",
"NoteMaker",
"NullContextManager",
"Number",
"NumberPair",
"NumberedInterval",
"NumberedIntervalClass",
"NumberedInversionEquivalentIntervalClass",
"NumberedPitch",
"NumberedPitchClass",
"Oboe",
"Octave",
"Offset",
"OffsetCounter",
"OnBeatGraceContainer",
"Ottava",
"OverrideInterface",
"Parentage",
"ParentageError",
"Parser",
"Pattern",
"PatternTuple",
"PatternTyping",
"Percussion",
"PersistentIndicatorError",
"Piano",
"Piccolo",
"Pitch",
"PitchClass",
"PitchClassSegment",
"PitchClassSet",
"PitchRange",
"PitchSegment",
"PitchSet",
"PitchTyping",
"ProgressIndicator",
"Prototype",
"Ratio",
"RatioSequenceTyping",
"RatioTyping",
"RedirectedStreams",
"RehearsalMark",
"Repeat",
"RepeatTie",
"Rest",
"Right",
"SchemeParserFinishedError",
"Score",
"Segment",
"Selection",
"Set",
"SetClass",
"SettingInterface",
"Skip",
"SlotContributions",
"SopraninoSaxophone",
"SopranoSaxophone",
"SopranoVoice",
"Staff",
"StaffChange",
"StaffGroup",
"StaffPosition",
"StartBeam",
"StartGroup",
"StartHairpin",
"StartMarkup",
"StartPhrasingSlur",
"StartPianoPedal",
"StartSlur",
"StartTextSpan",
"StartTrillSpan",
"StemTremolo",
"StopBeam",
"StopGroup",
"StopHairpin",
"StopPhrasingSlur",
"StopPianoPedal",
"StopSlur",
"StopTextSpan",
"StopTrillSpan",
"StringNumber",
"Strings",
"Tag",
"TemporaryDirectory",
"TemporaryDirectoryChange",
"TenorSaxophone",
"TenorTrombone",
"TenorVoice",
"Tie",
"TimeSignature",
"Timer",
"Timespan",
"TimespanList",
"TremoloContainer",
"Trumpet",
"Tuba",
"Tuning",
"Tuplet",
"TweakInterface",
"TwelveToneRow",
"TypedCollection",
"TypedFrozenset",
"TypedList",
"TypedTuple",
"UnboundedTimeIntervalError",
"Up",
"VerticalAlignment",
"VerticalMoment",
"Vibraphone",
"Viola",
"Violin",
"Voice",
"WellformednessError",
"Wrapper",
"Xylophone",
"__version__",
"__version_info__",
"_update",
"activate",
"annotate",
"attach",
"beam",
"deactivate",
"deprecated",
"detach",
"enumerate",
"format",
"glissando",
"graph",
"hairpin",
"horizontal_bracket",
"illustrate",
"illustrators",
"index",
"index_all",
"index_first",
"index_last",
"get",
"io",
"iterate",
"iterate_leaf_pairs",
"iterate_pitch_pairs",
"iterate_vertical_moments",
"iterpitches",
"label",
"list_all_classes",
"list_all_functions",
"lilypond",
"lyconst",
"lyenv",
"makers",
"mutate",
"on_beat_grace_container",
"ottava",
"override",
"parse",
"parser",
"persist",
"phrasing_slur",
"piano_pedal",
"select",
"setting",
"show",
"slur",
"string",
"text_spanner",
"tie",
"trill_spanner",
"tweak",
"wf",
"yield_all_modules",
]
| Abjad/abjad | abjad/__init__.py | Python | gpl-3.0 | 11,596 |
/*
* cmMemoryMap.cpp
* pointTest
*
* Created by Daniel Berio on 8/30/09.
* Copyright 2009 http://www.enist.org. All rights reserved.
*
*/
#include "cmMemoryMap.h"
#include "cmUtils.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>
namespace cm
{
/////////////////////////////////////////////////////////////
// FIXME hacky shit.
bool MemoryMap::open( const char * file, unsigned int flags )
{
_flags = flags;
if( flags == MMAP_READONLY )
{
_handle = ::open(file, flags);
}
else
{
if( flags == MMAP_READWRITE )
{
_handle = ::open (file, O_RDWR | O_CREAT | O_TRUNC, 0);
}
else
_handle = ::open(file, flags);
}
if(_handle < 0)
return false;
return true;
}
void MemoryMap::close()
{
if(_map)
unmap();
if(_handle)
::close(_handle);
_handle = 0;
}
/////////////////////////////////////////////////////////////
bool MemoryMap::map( int length )
{
// FIXME hacky shit.
if(_map)
unmap();
_length = length;
// check if we are writing
if(_flags == MMAP_READWRITE)
{
// write end char to end of file
char endchar='\0';
lseek(_handle, length-1, SEEK_SET);
write(_handle, &endchar, 1);
if((_map = (char*)mmap(0, length, PROT_WRITE, MAP_SHARED, _handle, 0)) == (char *)-1)
{
debugPrint( "Could not map output file\n");
return false;
}
return true;
}
_map = (char *)mmap(0, length, PROT_READ, MAP_SHARED, _handle, 0);
if (_map == MAP_FAILED)
return false;
_length = length;
return true;
}
/////////////////////////////////////////////////////////////
void MemoryMap::unmap()
{
munmap((char *)_map, getLength());
_length = 0;
_map = 0;
}
/////////////////////////////////////////////////////////////
size_t MemoryMap::getFileLength()
{
struct stat statbuf;
if (fstat(_handle, &statbuf) == -1)
return -1;
return statbuf.st_size;
}
} | memo/VolumeRunner | addons/colormotor/core/cmMemoryMap.cpp | C++ | gpl-3.0 | 1,973 |
/**
* @fileoverview Rule to forbid control charactes from regular expressions.
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow control characters in regular expressions",
category: "Possible Errors",
recommended: true
},
schema: []
},
create: function(context) {
/**
* Get the regex expression
* @param {ASTNode} node node to evaluate
* @returns {*} Regex if found else null
* @private
*/
function getRegExp(node) {
if (node.value instanceof RegExp) {
return node.value;
} else if (typeof node.value === "string") {
var parent = context.getAncestors().pop();
if ((parent.type === "NewExpression" || parent.type === "CallExpression") &&
parent.callee.type === "Identifier" && parent.callee.name === "RegExp"
) {
// there could be an invalid regular expression string
try {
return new RegExp(node.value);
} catch (ex) {
return null;
}
}
}
return null;
}
/**
* Check if given regex string has control characters in it
* @param {string} regexStr regex as string to check
* @returns {boolean} returns true if finds control characters on given string
* @private
*/
function hasControlCharacters(regexStr) {
// check control characters, if RegExp object used
var hasControlChars = /[\x00-\x1f]/.test(regexStr); // eslint-disable-line no-control-regex
// check substr, if regex literal used
var subStrIndex = regexStr.search(/\\x[01][0-9a-f]/i);
if (!hasControlChars && subStrIndex > -1) {
// is it escaped, check backslash count
var possibleEscapeCharacters = regexStr.substr(0, subStrIndex).match(/\\+$/gi);
hasControlChars = possibleEscapeCharacters === null || !(possibleEscapeCharacters[0].length % 2);
}
return hasControlChars;
}
return {
Literal: function(node) {
var computedValue,
regex = getRegExp(node);
if (regex) {
computedValue = regex.toString();
if (hasControlCharacters(computedValue)) {
context.report(node, "Unexpected control character in regular expression.");
}
}
}
};
}
};
| jlbooker/shop-hours-demo | node_modules/react-scripts/node_modules/eslint/lib/rules/no-control-regex.js | JavaScript | gpl-3.0 | 2,962 |
//TODO:change email to username
package care.hospital.virtual.virtualhospital;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import care.hospital.virtual.virtualhospital.util.VHRestClient;
import cz.msebera.android.httpclient.Header;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements OnClickListener {
// UI references.
private AutoCompleteTextView mUsername;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
//Toolbar toolbar = (Toolbar) findViewById(R.id.login_toolbar);
//setSupportActionBar(toolbar);
mUsername = (AutoCompleteTextView) findViewById(R.id.username);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
// Reset errors.
mUsername.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mUsername.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
login(email, password);
showProgress(true);
}
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
private void login(String username, String password) {
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
VHRestClient.post("account/login", params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("token", Context.MODE_PRIVATE).edit();
sharedPreferencesEditor.putString("access_token", responseString);
sharedPreferencesEditor.apply();
startActivity(new Intent(LoginActivity.this, Home.class));
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//TODO:fix snackbar
if(statusCode == 401) {
showProgress(false);
Snackbar.make(findViewById(android.R.id.content), "Username or Password are not Correct", Snackbar.LENGTH_LONG).show();
Log.d("Error", "Username or Password are not Correct");
} else {
showProgress(false);
Snackbar.make(findViewById(android.R.id.content), "Server is not Reachable, Check your internet connection", Snackbar.LENGTH_LONG).show();
Log.d("Error", "Server is not Reachable, Check your internet connection");
}
}
});
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public void onClick(View v) {
startActivity(new Intent(this, CreateAccount.class));
}
}
| fcm2009/VirtualHospital | app/src/main/java/care/hospital/virtual/virtualhospital/LoginActivity.java | Java | gpl-3.0 | 7,520 |
L.mapbox.accessToken = 'pk.eyJ1IjoibHVkby1hdXJnIiwiYSI6IjE0QzlVekkifQ.FK86sgWfTNbDC-Z-O-hTww';
var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
var ggl = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{
maxZoom: 20,
subdomains:['mt0','mt1','mt2','mt3']
});
var currenturl = location.href;
var url = currenturl.replace('/create','');
var featureLayer = L.mapbox.featureLayer();
var map = L.mapbox.map('editmap').setView([47.2172500,-1.5533600], 12);
featureLayer.addTo(map);
osm.addTo(map);
var drawControl = new L.Control.Draw({
draw: {
rectangle: false,
circle: false,
marker: true
},
edit: {
featureGroup: featureLayer
}
}).addTo(map);
map.on('draw:created', function(e) {
var layer = e.layer;
featureLayer.addLayer(layer);
var shape = JSON.stringify(featureLayer.toGeoJSON());
var ajax = $.ajax({
type: "POST",
url: url+'/creategeom',
data: 'shape='+shape,
dataType: "json",
encode: true
})
ajax.done(function(data) {
var typegeoms = ["Point","Polygon","LineString"];
$("#geom").empty();
$.each(typegeoms, function(key, val) {
if (typeof data[val] !== 'undefined') {
$("#geom").append('<input type="hidden" name="'+val.toLowerCase()+'" value="'+data[val].geom+'" />');
}
});
});
});
map.on('draw:edited', function(e) {
var layers = e.layers;
layers.eachLayer(function (layer) {
var shape = JSON.stringify(layers.toGeoJSON());
var ajax = $.ajax({
type: "POST",
url: url+'/creategeom',
data: 'shape='+shape,
dataType: "json",
encode: true
})
ajax.done(function(data) {
var typegeoms = ["Point","Polygon","LineString"];
$("#geom").empty();
$.each(typegeoms, function(key, val) {
if (typeof data[val] !== 'undefined') {
$("#geom").append('<input type="hidden" name="'+val.toLowerCase()+'" value="'+data[val].geom+'" />');
}
});
});
});
});
map.on('draw:deleted', function(e) {
var layer = e.layer;
featureLayer.removeLayer(layer);
var shape = JSON.stringify(featureLayer.toGeoJSON());
var ajax = $.ajax({
type: "POST",
url: url+'/creategeom',
data: 'shape='+shape,
dataType: "json",
encode: true
})
ajax.done(function(data) {
var typegeoms = ["Point","Polygon","LineString"];
$("#geom").empty();
$.each(typegeoms, function(key, val) {
if (typeof data[val] !== 'undefined') {
$("#geom").append('<input type="hidden" name="'+val.toLowerCase()+'" value="'+data[val].geom+'" />');
}else{
$("#geom").append('<input type="hidden" name="'+val.toLowerCase()+'" value="empty" />');
}
});
});
});
map.addControl(new L.Control.Layers( {'OSM':osm, 'Google':ggl}, {}));
| diouck/laravel | Modules/Commercemetro/Assets/js/creategeom.js | JavaScript | gpl-3.0 | 3,203 |
/*
APM_AHRS_DCM.cpp
AHRS system using DCM matrices
Based on DCM code by Doug Weibel, Jordi Muñoz and Jose Julio. DIYDrones.com
Adapted for the general ArduPilot AHRS interface by Andrew Tridgell
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.
*/
#include <FastSerial.h>
#include <AP_AHRS.h>
// this is the speed in cm/s above which we first get a yaw lock with
// the GPS
#define GPS_SPEED_MIN 300
// this is the speed in cm/s at which we stop using drift correction
// from the GPS and wait for the ground speed to get above GPS_SPEED_MIN
#define GPS_SPEED_RESET 100
// the limit (in degrees/second) beyond which we stop integrating
// omega_I. At larger spin rates the DCM PI controller can get 'dizzy'
// which results in false gyro drift. See
// http://gentlenav.googlecode.com/files/fastRotations.pdf
#define SPIN_RATE_LIMIT 20
// table of user settable parameters
const AP_Param::GroupInfo AP_AHRS::var_info[] PROGMEM = {
// @Param: YAW_P
// @DisplayName: Yaw P
// @Description: This controls the weight the compass has on the overall heading
// @Range: 0 .4
// @Increment: .01
AP_GROUPINFO("YAW_P", 0, AP_AHRS_DCM, _kp_yaw),
AP_GROUPINFO("RP_P", 1, AP_AHRS_DCM, _kp),
AP_GROUPEND
};
// run a full DCM update round
void
AP_AHRS_DCM::update(void)
{
float delta_t;
// tell the IMU to grab some data
_imu->update();
// ask the IMU how much time this sensor reading represents
delta_t = _imu->get_delta_time();
// Get current values for gyros
_gyro_vector = _imu->get_gyro();
_accel_vector = _imu->get_accel();
// Integrate the DCM matrix using gyro inputs
matrix_update(delta_t);
// Normalize the DCM matrix
normalize();
// Perform drift correction
drift_correction(delta_t);
// paranoid check for bad values in the DCM matrix
check_matrix();
// Calculate pitch, roll, yaw for stabilization and navigation
euler_angles();
}
// update the DCM matrix using only the gyros
void
AP_AHRS_DCM::matrix_update(float _G_Dt)
{
// note that we do not include the P terms in _omega. This is
// because the spin_rate is calculated from _omega.length(),
// and including the P terms would give positive feedback into
// the _P_gain() calculation, which can lead to a very large P
// value
_omega = _gyro_vector + _omega_I;
_dcm_matrix.rotate((_omega + _omega_P + _omega_yaw_P) * _G_Dt);
}
/*
reset the DCM matrix and omega. Used on ground start, and on
extreme errors in the matrix
*/
void
AP_AHRS_DCM::reset(bool recover_eulers)
{
// reset the integration terms
_omega_I.zero();
_omega_P.zero();
_omega_yaw_P.zero();
_omega.zero();
// if the caller wants us to try to recover to the current
// attitude then calculate the dcm matrix from the current
// roll/pitch/yaw values
if (recover_eulers && !isnan(roll) && !isnan(pitch) && !isnan(yaw)) {
_dcm_matrix.from_euler(roll, pitch, yaw);
} else {
// otherwise make it flat
_dcm_matrix.from_euler(0, 0, 0);
}
}
/*
check the DCM matrix for pathological values
*/
void
AP_AHRS_DCM::check_matrix(void)
{
if (_dcm_matrix.is_nan()) {
//Serial.printf("ERROR: DCM matrix NAN\n");
SITL_debug("ERROR: DCM matrix NAN\n");
renorm_blowup_count++;
reset(true);
return;
}
// some DCM matrix values can lead to an out of range error in
// the pitch calculation via asin(). These NaN values can
// feed back into the rest of the DCM matrix via the
// error_course value.
if (!(_dcm_matrix.c.x < 1.0 &&
_dcm_matrix.c.x > -1.0)) {
// We have an invalid matrix. Force a normalisation.
renorm_range_count++;
normalize();
if (_dcm_matrix.is_nan() ||
fabs(_dcm_matrix.c.x) > 10) {
// normalisation didn't fix the problem! We're
// in real trouble. All we can do is reset
//Serial.printf("ERROR: DCM matrix error. _dcm_matrix.c.x=%f\n",
// _dcm_matrix.c.x);
SITL_debug("ERROR: DCM matrix error. _dcm_matrix.c.x=%f\n",
_dcm_matrix.c.x);
renorm_blowup_count++;
reset(true);
}
}
}
// renormalise one vector component of the DCM matrix
// this will return false if renormalization fails
bool
AP_AHRS_DCM::renorm(Vector3f const &a, Vector3f &result)
{
float renorm_val;
// numerical errors will slowly build up over time in DCM,
// causing inaccuracies. We can keep ahead of those errors
// using the renormalization technique from the DCM IMU paper
// (see equations 18 to 21).
// For APM we don't bother with the taylor expansion
// optimisation from the paper as on our 2560 CPU the cost of
// the sqrt() is 44 microseconds, and the small time saving of
// the taylor expansion is not worth the potential of
// additional error buildup.
// Note that we can get significant renormalisation values
// when we have a larger delta_t due to a glitch eleswhere in
// APM, such as a I2c timeout or a set of EEPROM writes. While
// we would like to avoid these if possible, if it does happen
// we don't want to compound the error by making DCM less
// accurate.
renorm_val = 1.0 / a.length();
// keep the average for reporting
_renorm_val_sum += renorm_val;
_renorm_val_count++;
if (!(renorm_val < 2.0 && renorm_val > 0.5)) {
// this is larger than it should get - log it as a warning
renorm_range_count++;
if (!(renorm_val < 1.0e6 && renorm_val > 1.0e-6)) {
// we are getting values which are way out of
// range, we will reset the matrix and hope we
// can recover our attitude using drift
// correction before we hit the ground!
//Serial.printf("ERROR: DCM renormalisation error. renorm_val=%f\n",
// renorm_val);
SITL_debug("ERROR: DCM renormalisation error. renorm_val=%f\n",
renorm_val);
renorm_blowup_count++;
return false;
}
}
result = a * renorm_val;
return true;
}
/*************************************************
Direction Cosine Matrix IMU: Theory
William Premerlani and Paul Bizard
Numerical errors will gradually reduce the orthogonality conditions expressed by equation 5
to approximations rather than identities. In effect, the axes in the two frames of reference no
longer describe a rigid body. Fortunately, numerical error accumulates very slowly, so it is a
simple matter to stay ahead of it.
We call the process of enforcing the orthogonality conditions ÒrenormalizationÓ.
*/
void
AP_AHRS_DCM::normalize(void)
{
float error;
Vector3f t0, t1, t2;
error = _dcm_matrix.a * _dcm_matrix.b; // eq.18
t0 = _dcm_matrix.a - (_dcm_matrix.b * (0.5f * error)); // eq.19
t1 = _dcm_matrix.b - (_dcm_matrix.a * (0.5f * error)); // eq.19
t2 = t0 % t1; // c= a x b // eq.20
if (!renorm(t0, _dcm_matrix.a) ||
!renorm(t1, _dcm_matrix.b) ||
!renorm(t2, _dcm_matrix.c)) {
// Our solution is blowing up and we will force back
// to last euler angles
reset(true);
}
}
// produce a yaw error value. The returned value is proportional
// to sin() of the current heading error in earth frame
float
AP_AHRS_DCM::yaw_error_compass(void)
{
Vector3f mag = Vector3f(_compass->mag_x, _compass->mag_y, _compass->mag_z);
// get the mag vector in the earth frame
Vector3f rb = _dcm_matrix * mag;
rb.normalize();
if (rb.is_inf()) {
// not a valid vector
return 0.0;
}
// get the earths magnetic field (only X and Y components needed)
Vector3f mag_earth = Vector3f(cos(_compass->get_declination()),
sin(_compass->get_declination()), 0);
// calculate the error term in earth frame
Vector3f error = rb % mag_earth;
return error.z;
}
// produce a yaw error value using the GPS. The returned value is proportional
// to sin() of the current heading error in earth frame
float
AP_AHRS_DCM::yaw_error_gps(void)
{
return sin(ToRad(_gps->ground_course * 0.01) - yaw);
}
// the _P_gain raises the gain of the PI controller
// when we are spinning fast. See the fastRotations
// paper from Bill.
float
AP_AHRS_DCM::_P_gain(float spin_rate)
{
if (spin_rate < ToDeg(50)) {
return 1.0;
}
if (spin_rate > ToDeg(500)) {
return 10.0;
}
return spin_rate/ToDeg(50);
}
// yaw drift correction using the compass or GPS
// this function prodoces the _omega_yaw_P vector, and also
// contributes to the _omega_I.z long term yaw drift estimate
void
AP_AHRS_DCM::drift_correction_yaw(void)
{
bool new_value = false;
float yaw_error;
float yaw_deltat;
if (_compass && _compass->use_for_yaw()) {
if (_compass->last_update != _compass_last_update) {
yaw_deltat = (_compass->last_update - _compass_last_update) * 1.0e-6;
_compass_last_update = _compass->last_update;
if (!_have_initial_yaw) {
float heading = _compass->calculate_heading(_dcm_matrix);
_dcm_matrix.from_euler(roll, pitch, heading);
_omega_yaw_P.zero();
_have_initial_yaw = true;
}
new_value = true;
yaw_error = yaw_error_compass();
}
} else if (_fly_forward && _gps && _gps->status() == GPS::GPS_OK) {
if (_gps->last_fix_time != _gps_last_update &&
_gps->ground_speed >= GPS_SPEED_MIN) {
yaw_deltat = (_gps->last_fix_time - _gps_last_update) * 1.0e-3;
_gps_last_update = _gps->last_fix_time;
if (!_have_initial_yaw) {
_dcm_matrix.from_euler(roll, pitch, ToRad(_gps->ground_course*0.01));
_omega_yaw_P.zero();
_have_initial_yaw = true;
}
new_value = true;
yaw_error = yaw_error_gps();
}
}
if (!new_value) {
// we don't have any new yaw information
// slowly decay _omega_yaw_P to cope with loss
// of our yaw source
_omega_yaw_P *= 0.97;
return;
}
// the yaw error is a vector in earth frame
Vector3f error = Vector3f(0,0, yaw_error);
// convert the error vector to body frame
error = _dcm_matrix.mul_transpose(error);
// the spin rate changes the P gain, and disables the
// integration at higher rates
float spin_rate = _omega.length();
// update the proportional control to drag the
// yaw back to the right value. We use a gain
// that depends on the spin rate. See the fastRotations.pdf
// paper from Bill Premerlani
_omega_yaw_P.z = error.z * _P_gain(spin_rate) * _kp_yaw.get();
// don't update the drift term if we lost the yaw reference
// for more than 2 seconds
if (yaw_deltat < 2.0 && spin_rate < ToRad(SPIN_RATE_LIMIT)) {
// also add to the I term
_omega_I_sum.z += error.z * _ki_yaw * yaw_deltat;
}
_error_yaw_sum += fabs(yaw_error);
_error_yaw_count++;
}
// perform drift correction. This function aims to update _omega_P and
// _omega_I with our best estimate of the short term and long term
// gyro error. The _omega_P value is what pulls our attitude solution
// back towards the reference vector quickly. The _omega_I term is an
// attempt to learn the long term drift rate of the gyros.
//
// This drift correction implementation is based on a paper
// by Bill Premerlani from here:
// http://gentlenav.googlecode.com/files/RollPitchDriftCompensation.pdf
void
AP_AHRS_DCM::drift_correction(float deltat)
{
Vector3f velocity;
uint32_t last_correction_time;
// perform yaw drift correction if we have a new yaw reference
// vector
drift_correction_yaw();
// integrate the accel vector in the earth frame between GPS readings
_ra_sum += _dcm_matrix * (_accel_vector * deltat);
// keep a sum of the deltat values, so we know how much time
// we have integrated over
_ra_deltat += deltat;
if (_gps == NULL || _gps->status() != GPS::GPS_OK) {
// no GPS, or no lock. We assume zero velocity. This at
// least means we can cope with gyro drift while sitting
// on a bench with no GPS lock
if (_ra_deltat < 0.1) {
// not enough time has accumulated
return;
}
velocity.zero();
_last_velocity.zero();
last_correction_time = millis();
_have_gps_lock = false;
} else {
if (_gps->last_fix_time == _ra_sum_start) {
// we don't have a new GPS fix - nothing more to do
return;
}
velocity = Vector3f(_gps->velocity_north(), _gps->velocity_east(), 0);
last_correction_time = _gps->last_fix_time;
if (_have_gps_lock == false) {
// if we didn't have GPS lock in the last drift
// correction interval then set the velocities equal
_last_velocity = velocity;
}
_have_gps_lock = true;
}
#define USE_BAROMETER_FOR_VERTICAL_VELOCITY 1
#if USE_BAROMETER_FOR_VERTICAL_VELOCITY
/*
The barometer for vertical velocity is only enabled if we got
at least 5 pressure samples for the reading. This ensures we
don't use very noisy climb rate data
*/
if (_barometer != NULL && _barometer->get_pressure_samples() >= 5) {
// Z velocity is down
velocity.z = - _barometer->get_climb_rate();
}
#endif
// see if this is our first time through - in which case we
// just setup the start times and return
if (_ra_sum_start == 0) {
_ra_sum_start = last_correction_time;
_last_velocity = velocity;
return;
}
// equation 9: get the corrected acceleration vector in earth frame. Units
// are m/s/s
Vector3f GA_e;
float v_scale = 1.0/(_ra_deltat*_gravity);
GA_e = Vector3f(0, 0, -1.0) + ((velocity - _last_velocity) * v_scale);
GA_e.normalize();
if (GA_e.is_inf()) {
// wait for some non-zero acceleration information
return;
}
// calculate the error term in earth frame.
Vector3f GA_b = _ra_sum / _ra_deltat;
GA_b.normalize();
if (GA_b.is_inf()) {
// wait for some non-zero acceleration information
return;
}
Vector3f error = GA_b % GA_e;
#define YAW_INDEPENDENT_DRIFT_CORRECTION 0
#if YAW_INDEPENDENT_DRIFT_CORRECTION
// step 2 calculate earth_error_Z
float earth_error_Z = error.z;
// equation 10
float tilt = sqrt(sq(GA_e.x) + sq(GA_e.y));
// equation 11
float theta = atan2(GA_b.y, GA_b.x);
// equation 12
Vector3f GA_e2 = Vector3f(cos(theta)*tilt, sin(theta)*tilt, GA_e.z);
// step 6
error = GA_b % GA_e2;
error.z = earth_error_Z;
#endif // YAW_INDEPENDENT_DRIFT_CORRECTION
// only use the gps/accelerometers for earth frame yaw correction
// if we are not using a compass. Otherwise we have two competing
// controllers for yaw correction
if (_compass && _compass->use_for_yaw()) {
error.z = 0;
}
// convert the error term to body frame
error = _dcm_matrix.mul_transpose(error);
_error_rp_sum += error.length();
_error_rp_count++;
// base the P gain on the spin rate
float spin_rate = _omega.length();
// we now want to calculate _omega_P and _omega_I. The
// _omega_P value is what drags us quickly to the
// accelerometer reading.
_omega_P = error * _P_gain(spin_rate) * _kp;
// accumulate some integrator error
if (spin_rate < ToRad(SPIN_RATE_LIMIT)) {
_omega_I_sum += error * _ki * _ra_deltat;
_omega_I_sum_time += _ra_deltat;
}
if (_omega_I_sum_time >= 5) {
// limit the rate of change of omega_I to the hardware
// reported maximum gyro drift rate. This ensures that
// short term errors don't cause a buildup of omega_I
// beyond the physical limits of the device
float change_limit = _gyro_drift_limit * _omega_I_sum_time;
_omega_I_sum.x = constrain(_omega_I_sum.x, -change_limit, change_limit);
_omega_I_sum.y = constrain(_omega_I_sum.y, -change_limit, change_limit);
_omega_I_sum.z = constrain(_omega_I_sum.z, -change_limit, change_limit);
_omega_I += _omega_I_sum;
_omega_I_sum.zero();
_omega_I_sum_time = 0;
}
// zero our accumulator ready for the next GPS step
_ra_sum.zero();
_ra_deltat = 0;
_ra_sum_start = last_correction_time;
// remember the velocity for next time
_last_velocity = velocity;
}
// calculate the euler angles which will be used for high level
// navigation control
void
AP_AHRS_DCM::euler_angles(void)
{
_dcm_matrix.to_euler(&roll, &pitch, &yaw);
roll_sensor = degrees(roll) * 100;
pitch_sensor = degrees(pitch) * 100;
yaw_sensor = degrees(yaw) * 100;
if (yaw_sensor < 0)
yaw_sensor += 36000;
}
/* reporting of DCM state for MAVLink */
// average error_roll_pitch since last call
float AP_AHRS_DCM::get_error_rp(void)
{
if (_error_rp_count == 0) {
// this happens when telemetry is setup on two
// serial ports
return _error_rp_last;
}
_error_rp_last = _error_rp_sum / _error_rp_count;
_error_rp_sum = 0;
_error_rp_count = 0;
return _error_rp_last;
}
// average error_yaw since last call
float AP_AHRS_DCM::get_error_yaw(void)
{
if (_error_yaw_count == 0) {
// this happens when telemetry is setup on two
// serial ports
return _error_yaw_last;
}
_error_yaw_last = _error_yaw_sum / _error_yaw_count;
_error_yaw_sum = 0;
_error_yaw_count = 0;
return _error_yaw_last;
}
| emlun/arducoopter | libraries/AP_AHRS/AP_AHRS_DCM.cpp | C++ | gpl-3.0 | 16,956 |
package com.vmware.o11n.plugin.redis.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.vmware.o11n.sdk.modeldriven.Findable;
import com.vmware.o11n.sdk.modeldriven.Sid;
import com.vmware.o11n.sdk.modeldriven.extension.ExtensionMethod;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Component
@Qualifier(value = "connection")
@Scope(value = "prototype")
public class Connection implements Findable {
private static final int DEFAULT_REDIS_DATABASE_INDEX = 0;
/*
* The connectionInfo which stands behind this live connection.
*/
private ConnectionInfo connectionInfo;
private Map<Integer, Database> databases = null;
private JedisPool pool;
/*
* There is no default constructor, the Connection must be initialised only
* with a connection info argument.
*/
public Connection(ConnectionInfo info) {
init(info);
}
@Override
public Sid getInternalId() {
return getConnectionInfo().getId();
}
@Override
public void setInternalId(Sid id) {
// do nothing, we set the Id in the constructor
}
public String getName() {
return getConnectionInfo().getName();
}
public String getHost() {
return getConnectionInfo().getHost();
}
public int getPort() {
return getConnectionInfo().getPort();
}
public synchronized ConnectionInfo getConnectionInfo() {
return connectionInfo;
}
public String getDisplayName() {
return getConnectionInfo().getName() + " [" + getConnectionInfo().getHost() + "]";
}
public List<Database> getDatabases() {
if (databases == null) {
databases = new HashMap<>(16);
// Issue a call to Redis, to see how many databases are configured,
// default is 16
List<String> configs = getResource(DEFAULT_REDIS_DATABASE_INDEX).configGet("databases");
int numberOfInstances = Integer.parseInt(configs.get(1));
for (int index = 0; index < numberOfInstances; index++) {
databases.put(index, new Database(this, index));
}
}
return new ArrayList<>(databases.values());
}
@ExtensionMethod
public Database getDatabase(int index) {
return getDatabases().get(index);
}
@ExtensionMethod
public Database getDefaultDatabase() {
return getDatabase(DEFAULT_REDIS_DATABASE_INDEX);
}
/**
* Returns a redis connection from the pool.
*
* @param index
* the index of the database
*/
public Jedis getResource(int index) {
Jedis resource = getPool().getResource();
resource.select(index);
return resource;
}
/*
* Lazy initialization of the pool.
*/
private synchronized JedisPool getPool() {
if (pool == null) {
JedisPoolConfig jedisConfig = new JedisPoolConfig();
pool = new JedisPool(jedisConfig, connectionInfo.getHost(), connectionInfo.getPort());
}
return pool;
}
/*
* Updates this connection with the provided info. This operation will
* destroy the existing third party client, causing all associated
* operations to fail.
*/
public synchronized void update(ConnectionInfo connectionInfo) {
if (this.connectionInfo != null && !connectionInfo.getId().equals(this.connectionInfo.getId())) {
throw new IllegalArgumentException("Cannot update using different id");
}
destroy();
init(connectionInfo);
}
private void init(ConnectionInfo connectionInfo) {
this.connectionInfo = connectionInfo;
}
public synchronized void destroy() {
if (pool != null) {
pool.destroy();
}
}
}
| dimitrovvlado/o11n-plugin-redis | o11nplugin-redis-core/src/main/java/com/vmware/o11n/plugin/redis/model/Connection.java | Java | gpl-3.0 | 4,105 |
package com.whtss.assets.render.animations;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RadialGradientPaint;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Point2D;
import com.whtss.assets.hex.HexPoint;
import com.whtss.assets.render.Animation;
public class TileDamage extends Animation
{
private HexPoint pos;
public TileDamage(HexPoint location)
{
super(500);
this.pos = location;
}
@Override
public void drawOverEntities(Graphics2D g, int s)
{
float time = Math.max(T(), getLength());
Shape bound = pos.getBorder(s);
Rectangle border = bound.getBounds();
Point2D.Double f = new Point2D.Double(border.getCenterX(), border.getCenterY());
Paint grad = new RadialGradientPaint(f, s / 3, new float[] {0, .7f, 1}, new Color[]{
new Color(1, 0, 0, 0),
new Color(1, 0, 0, .2f * (1 - time / getLength())),
new Color(1, 0, 0, .8f * (1 - time / getLength()))});
g.setPaint(grad);
g.fill(bound);
}
}
| Chroniaro/What-Happened-to-Station-7 | src/com/whtss/assets/render/animations/TileDamage.java | Java | gpl-3.0 | 1,042 |
#ifndef FEAT_H
#define FEAT_H
#ifndef INC_INDIVIDUAL
#define INC_INDIVIDUAL
#include <Individual/Individual.hpp>
#endif
#ifndef INC_STRING
#define INC_STRING
#include <string>
#endif
class Individual;
///
/// \brief Class that holds the data of a certain Individual.
///This container can be used for holding deterministic Features or sets of
///samples.
///
class Feature{
private:
/**
* @brief Pointer to the Individual to which this Feature was attributed.
*/
Individual *ind;
/**
* @brief Text describing the Feature.
*/
std::string description;
public:
// Constructors
Feature();
Feature(Individual* owner);
Feature(Individual* owner, std::string name);
Feature(std::string name);
// Description handling functions
std::string describe();
void describe(std::string name);
// Individual (owner) handling functions
Individual* parent();
void parent(Individual* owner);
};
#endif
| BioFoV/BioFoV | application/src/Feature/Feature.hpp | C++ | gpl-3.0 | 913 |
#include "Global.h"
Global::~Global()
{
}
bool Global::Load()
{
auto manager = AssetManager::GetInstance();
texBlack = manager->CreateTextureFromFile("res/front/black.jpg");
if (texBlack == nullptr)
{
return false;
}
this->titleMusic = Audio::GetInstance()->CreateMusic("bgm/title.wav");
return true;
} | Ibuki-Suika/THXYY | THXYY/src/STGCore/Global.cpp | C++ | gpl-3.0 | 315 |
-- Preparation pointage previsionnel à partir d'un autre previsionnel
-- positionne a 0 les UO par User/Project
-- => preparation des users (on ne sera pas obligé de creer les lignes user par projet dans le pointage previsionnel)
-- @ID_DATE -- date ou inserer des UO a 0 s'il existe dans previsonnel
SET FOREIGN_KEY_CHECKS=0;
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
set @ID_DATE_REF="2020-12-01"; -- date de reference yyyy-mm-dd
set @ID_DATE_NEW="2021-01-01"; -- date d'insertion (en generale le 01/01/xxxx) yyyy-mm-dd
set @ID_PROJECT_REF="P2X901"; -- id du projet de reference
set @ID_PROJECT_NEW="P2Y901"; -- id du projet a peupler
-- creation nouveau pointage de projet par copie depuis le provisionnel
-- ne cree le pointage que pour (annee-mois) donné et pour les tuples non deja existant (projet, user, profil)
-- place le nombre d'UO a 0
INSERT INTO `test`.`cegid_pointage_previsionnel` (`PROJECT_ID`, `DATE`, `USER_ID`, `PROFIL`, `UO`)
SELECT @ID_PROJECT_NEW, @ID_DATE_NEW, USER_ID, `PROFIL`, 0 FROM `cegid_pointage_previsionnel`
WHERE `DATE` = @ID_DATE_REF
AND `PROJECT_ID` = @ID_PROJECT_REF
AND concat(PROJECT_ID, month(DATE), USER_ID, PROFIL) not in (
select concat(PROJECT_ID, month(DATE), USER_ID, PROFIL) from cegid_pointage_previsionnel WHERE year(`DATE`)=year(@ID_DATE) and month(`DATE`)=month(@ID_DATE)
);
SET FOREIGN_KEY_CHECKS=1;
ROLLBACK;
-- COMMIT;
| selleron/pointageWebCEGID | configuration/requests/init_pointage_user_previsionel.sql | SQL | gpl-3.0 | 1,513 |
---
title: "मुख्यमंत्री के इकबाल को अपराधियों की खुली चुनौती: डा0 चन्द्रमोहन"
layout: item
category: lucknow
date: 2016-03-18T13:11:17.000Z
image: 173bf182ab0298d40ba36878d93b2809.jpg
---
<p style="text-align: justify;">लखनऊ: भारतीय जनता पार्टी ने कहा कि प्रदेश के मुख्यमंत्री अखिलेश यादव द्वारा आईएएस वीक के दौरान यह कहना कि अफसरों पर कार्यवाही होती है तो जनता खुश होती है यह बात मुख्यमंत्री की कानून व्यवस्था के मसले पर खुद की स्वीकारोक्ति है। प्रदेश के मुख्यमंत्री एक ओर खुद बड़े-बड़े आधारहीन दावे कर रहे है और वह घोषणा भी करते है कि कानून व्यवस्था कि समीक्षा खुद करेंगे लेकिन प्रदेश की जनता को प्रदेश के मुख्यमंत्री पर विश्वास करने का कोई कारण समझ नहीं आ रहा है।</p>
<p style="text-align: justify;">प्रदेश पार्टी मुख्यालय में पत्रकारों से चर्चा करते हुए प्रदेश पार्टी प्रवक्ता डा0 चन्द्रमोहन ने कहा कि प्रदेश में मुख्यमंत्री जब तिलक हाल में अपनी सरकार की विफलतायें छिपाने के लिये आई.ए.एस. अधिकारियों से कुतर्क कर रहे थे उसी समय कुछ ही दूर पर हजरतगंज स्थिति विधायक निवास के समीप सड़क गोलियों से गूंज रही थी और प्रदेश की राजधानी में नागरिक दहशत के साये में थे।</p>
<p style="text-align: justify;">प्रदेश की राजधानी लखनऊ के महानगर स्थित छन्नीलाल चैराहे के पास मासूम से हैवानियत की घटना फेल कानून व्यवस्था का सबसे बड़ा उदाहरण हैं। प्रदेश भर में बरेली, मुजफ्फरनगर सहित अनेक स्थानों पर महिला अस्मत पर हमले लगातार जारी है प्रदेश सरकार महिला सुरक्षा को 1090 के हवाले कर के अपनी जिम्मेदारी से इतिश्री कर ली है। प्रदेश के मुख्यमंत्री केवल वोट बैंक की राजनीति कर रहे है, मुख्यमंत्री का यह कथन कि हमकों तकलीफ हुई तो फिर आप लोगों को भी दिक्कत होगी, उनकी हताशा को दिखा रहा है।</p>
<p style="text-align: justify;">प्रदेश प्रवक्ता डा0 चन्द्रमोहन ने कहा कि कानून व्यवस्था इकबाल से कायम होती है कुतर्को से नहीं। मुख्यमंत्री को सत्ता संरक्षित अराजक गुण्डातत्वों पर कठोर कार्यवाही कर प्रशासनिक मशीनरी में विश्वास का वातावरण पैदा करना होगा।</p> | InstantKhabar/_source | _source/news/30192-lucknow.html | HTML | gpl-3.0 | 4,338 |
#include <Eigen/Core>
#include <Eigen/LU>
#include <Eigen/QR>
#include <Eigen/Cholesky>
#include <Eigen/Geometry>
#include <Eigen/Jacobi>
#include <Eigen/Eigenvalues>
#include <iostream>
using namespace Eigen;
using namespace std;
int main(int, char**)
{
cout.precision(3);
Array3d v(2,3,4);
cout << v.cube() << endl;
return 0;
}
| lriazuelo/c2tam | c2tam_mapping/EXTERNAL/g2o/EXTERNAL/eigen3/doc/snippets/compile_Cwise_cube.cpp | C++ | gpl-3.0 | 339 |
/**
* Copyright 2015 University of Applied Sciences Western Switzerland / Fribourg
*
* 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.
*
* Project: HEIA-FR / Internet of Things Laboratory
*
* Abstract: Project - Connected Weather Station
*
* Purpose: Module to create a button, which can detect a single-click or a double-click
*
* Source: This library is a lightweight & simplest version of the OneButton library
* https://github.com/mathertel/OneButton
*
* Author: Samuel Mertenat - T2f
* Date: 25.05.2015
*/
#include "Button.h"
button::button(uint8_t p_button_pin):
m_button_pin(p_button_pin),
m_click_ticks(800),
m_state(0),
m_button_level(LOW) {
// sets the pin as INPUT
pinMode(m_button_pin, INPUT);
}
void button::attach_fnct_on_click(callbackFunction p_function) {
m_click_fnct = p_function;
}
void button::attach_fnct_on_double_click(callbackFunction p_function) {
m_double_click_fnct = p_function;
}
void button::tick() {
// detects the input level & gets the current time
m_button_level = digitalRead(m_button_pin);
m_now = millis();
if (m_state == 0) {
if (m_button_level == HIGH) {
m_state = 1;
m_start_time = m_now; // remembers starting time
}
} else if (m_state == 1) {
if (m_button_level == LOW) {
m_state = 2;
}
} else if (m_state == 2) {
if (m_now > m_start_time + m_click_ticks) {
// this was only a single-click
if (m_click_fnct) m_click_fnct();
m_state = 0; // resets state
} else if (m_button_level == HIGH) {
m_state = 3;
}
} else if (m_state == 3) {
if (m_button_level == LOW) {
// this was a 2 click sequence.
if (m_double_click_fnct) m_double_click_fnct();
m_state = 0; // resets state
}
}
}
| mertenats/heia | IoT/tp05/IoT/Button.cpp | C++ | gpl-3.0 | 2,293 |
/** This file is part of project comment
*
* File: config.cpp
* Created: 2009-02-13
* Author: Jonathan Verner <jonathan.verner@matfyz.cz>
* License: GPL v2 or later
*
* Copyright (C) 2010 Jonathan Verner <jonathan.verner@matfyz.cz>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QRegExp>
#include <QtCore/QStringList>
#include <QtCore/QDebug>
QString configurator::fName = "";
QHash<QString,QString> configurator::cfg;
bool configurator::haveTeXAndFriends;
configurator& config() {
static configurator *conf = new configurator();
return *conf;
}
bool configurator::haveKey( const QString key ) const {
return cfg.contains( key.toLower().replace(' ','_') );
}
void configurator::removeKey( const QString key ) {
cfg.remove( key.toLower().replace(' ','_') );
}
bool configurator::findTeX() {
if ( cfg["tex"] != "" && QFile::exists( cfg["tex"] ) ) return true;
if ( QFile::exists( "/usr/bin/pdflatex" ) ) {
cfg["tex"] = "/usr/bin/pdflatex";
return true;
}
return false;
}
bool configurator::findGhostScript() {
if ( cfg["gs"] != "" && QFile::exists( cfg["gs"] ) ) return true;
if ( QFile::exists( "/usr/bin/gs" ) ) {
cfg["gs"] = "/usr/bin/gs";
return true;
}
return false;
}
configurator::configurator()
{
fName = QDir::homePath()+"/.comment";
load();
haveTeXAndFriends = findTeX() && findGhostScript();
qDebug() << "initializing configurator";
}
void configurator::load() {
qDebug() << "Loading config from "<<fName << "...";
QFile cfgFile( fName );
if ( ! cfgFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
return;
QTextStream in(&cfgFile);
while( ! in.atEnd() ) {
QString line = in.readLine();
QRegExp exp(" *([^ ][^#= ]*) *= *([^ ][^;]*).*");
if ( ! exp.exactMatch( line ) ) continue;
QStringList list = exp.capturedTexts();
cfg[list[1].toLower().replace(' ','_')]=list[2];
}
cfgFile.close();
}
void configurator::save() {
qDebug() << "Saving config to "<<fName << "...";
QFile cfgFile( fName );
if ( ! cfgFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
return;
QTextStream out(&cfgFile);
foreach( QString key, cfg.keys() ) {
out << key.toLower().replace(' ','_') << " = " << cfg[key] << ";" << endl;
}
cfgFile.close();
}
QString &configurator::operator[] (const QString key) {
return cfg[key.toLower().replace(' ','_')];
}
| jonathanverner/comment | config.cpp | C++ | gpl-3.0 | 3,241 |
#include <iostream>
#include <vector>
#include <string>
using namespace std;
namespace {
const string KReset ("0");
const string KNoir ("30");
const string KRouge ("31");
const string KVert ("32");
const string KJaune ("33");
const string KBleu ("34");
const string KMAgenta ("35");
const string KCyan ("36");
const char KEmpty = '-';
typedef vector <char> CVLine; // un type représentant une ligne de la grille
typedef vector <CVLine> CMatrix; // un type représentant la grille
typedef struct {
unsigned posX;
unsigned posY;
unsigned sizeX;
unsigned sizeY;
char token;
string color;
} Player;
void Couleur (const string & coul);
void ClearScreen ();
void ShowMatrix (const CMatrix & Mat,Player & FirstPlayer, Player & SecondPlayer);
void InitMat (CMatrix & Mat, unsigned NbLine, unsigned NbColumn, Player & FirstPlayer, Player & SecondPlayer);
void MoveToken (CMatrix & Mat, char Move, Player & player);
void GetBonus(CMatrix & Mat, Player & player);
void PutBonus(CMatrix & Mat, const char & token, const unsigned & posX, const unsigned & posY);
bool CheckWin(Player & FirstPlayer, Player & SecondPlayer);
int ppal();
void Couleur (const string & coul)
{
cout << "\033[" << coul <<"m";
}
void ClearScreen ()
{
cout << "\033[H\033[2J";
}
void ShowMatrix (const CMatrix & Mat,Player & FirstPlayer, Player & SecondPlayer)
{
ClearScreen();
Couleur (KReset);
for (CVLine line : Mat)
{
for (char C : line)
{
if (C == FirstPlayer.token) Couleur (FirstPlayer.color);
if (C == SecondPlayer.token) Couleur (SecondPlayer.color);
cout << C;
if ((C == FirstPlayer.token)||(C == SecondPlayer.token)) Couleur (KReset);
}
cout << endl;
}
}
void InitMat (CMatrix & Mat, unsigned NbLine, unsigned NbColumn, Player & FirstPlayer, Player & SecondPlayer)
{
Mat.resize(NbLine);
for (unsigned i (0); i<NbLine; ++i)
{
for (unsigned j (0); j<NbColumn; ++j)
{
Mat[i].push_back(KEmpty);
}
}
for (unsigned i (FirstPlayer.posY); i<FirstPlayer.posY + FirstPlayer.sizeY; ++i)
for (unsigned j (FirstPlayer.posX); j<FirstPlayer.posX + FirstPlayer.sizeX; ++j)
Mat[i][j] = FirstPlayer.token;
for (unsigned i (SecondPlayer.posY); i<SecondPlayer.posY + SecondPlayer.sizeY; ++i)
for (unsigned j (SecondPlayer.posX); j<SecondPlayer.posX + SecondPlayer.sizeX; ++j)
Mat[i][j] = SecondPlayer.token;
}
void MoveToken (CMatrix & Mat, char Move, Player & player)
{
switch (Move)
{
case 'z':
if (player.posY > 0)
{
player.posY = player.posY - 1;
GetBonus(Mat, player);
for (unsigned i (player.posX); i < player.posX + player.sizeX; ++i)
Mat[player.posY + player.sizeY][i] = KEmpty;
for (unsigned i (player.posX); i < player.posX + player.sizeX; ++i)
Mat[player.posY][i] = player.token;
}
break;
case 's':
if (player.posY + player.sizeY < Mat.size())
{
player.posY = player.posY + 1;
GetBonus(Mat, player);
for (unsigned i (player.posX); i < player.posX + player.sizeX; ++i)
Mat[player.posY - 1][i] = KEmpty;
for (unsigned i (player.posX); i < player.posX + player.sizeX; ++i)
Mat[player.posY + player.sizeY - 1][i] = player.token;
}
break;
case 'q':
if (player.posX > 0)
{
player.posX = player.posX - 1;
GetBonus(Mat, player);
for (unsigned i (player.posY); i < player.posY + player.sizeY; ++i)
Mat[i][player.posX + player.sizeX] = KEmpty;
for (unsigned i (player.posY); i < player.posY + player.sizeY; ++i)
Mat[i][player.posX] = player.token;
}
break;
case 'd':
if (player.posX + player.sizeX < Mat[0].size())
{
player.posX = player.posX + 1;
GetBonus(Mat, player);
for (unsigned i (player.posY); i < player.posY + player.sizeY; ++i)
Mat[i][player.posX - 1] = KEmpty;
for (unsigned i (player.posY); i < player.posY + player.sizeY; ++i)
Mat[i][player.posX + player.sizeX - 1] = player.token;
}
break;
}
}
void PutBonus(CMatrix & Mat, const char & token, const unsigned & posX, const unsigned & posY)
{
Mat[posY][posX] = token;
}
void GetBonus(CMatrix & Mat, Player & player)
{
for (unsigned i (player.posY); i<player.posY + player.sizeY; ++i)
{
for (unsigned j (player.posX); j<player.posX + player.sizeX; ++j)
{
if (Mat[i][j] == 'B')
{
++player.sizeX;
++player.sizeY;
for (unsigned i (player.posY); i<player.posY + player.sizeY; ++i)
for (unsigned j (player.posX); j<player.posX + player.sizeX; ++j)
Mat[i][j] = player.token;
}
}
}
}
bool CheckIfWin(Player & FirstPlayer, Player & SecondPlayer)
{
return !((FirstPlayer.posX > SecondPlayer.posX + SecondPlayer.sizeX - 1) ||
(FirstPlayer.posX + FirstPlayer.sizeX - 1 < SecondPlayer.posX) ||
(SecondPlayer.posY > FirstPlayer.posY + FirstPlayer.sizeY - 1) ||
(SecondPlayer.posY + SecondPlayer.sizeY - 1 < FirstPlayer.posY));
}
void SetPlayerSize( Player & player, const unsigned & largeur, const unsigned & hauteur){
player.sizeX = largeur;
player.sizeY = hauteur;
}
void SetPlayerPosition(Player & player, const unsigned & AxeX, const unsigned & AxeY){
player.posX = AxeX;
player.posY = AxeY;
}
void SetPlayerToken(Player & player, const char & Token){
player.token = Token;
}
void SetPlayerColor(Player & player, const string & Color){
player.color = Color;
}
unsigned AskTourMax(){
unsigned NbRnds;
cout << "Entrez le nombre de rounds" << endl;
cin >> NbRnds;
return NbRnds;
}
char GetWinner(Player& FirstPlayer, Player &SecondPlayer, const unsigned & NbrTour){
return (NbrTour%2 == 0 ? FirstPlayer.token : SecondPlayer.token);
}
int ppal ()
{
const unsigned KSizeX (5);
const unsigned KSizeY (5);
unsigned NbRnds = AskTourMax();
char EnteredKey;
Player FirstPlayer;
Player SecondPlayer;
CMatrix Map;
SetPlayerPosition(FirstPlayer, 0, 0);
SetPlayerPosition(SecondPlayer, KSizeX - 1, KSizeY - 1);
SetPlayerSize(FirstPlayer, 1, 1);
SetPlayerSize(SecondPlayer, 1, 1);
SetPlayerToken(FirstPlayer, 'X');
SetPlayerToken(SecondPlayer, 'Y');
SetPlayerColor(FirstPlayer, KRouge);
SetPlayerColor(SecondPlayer, KBleu);
InitMat(Map, KSizeX, KSizeY, FirstPlayer, SecondPlayer);
PutBonus(Map,'B',2,2);
ShowMatrix(Map, FirstPlayer, SecondPlayer);
cout << FirstPlayer.token << " commeeence et chasse " << SecondPlayer.token << endl;
for (unsigned i (0); i < NbRnds*2; ++i)
{
ShowMatrix(Map, FirstPlayer, SecondPlayer);
cout << "Au tour de " << (i%2 == 0 ? FirstPlayer.token : SecondPlayer.token) << endl;
cin >> EnteredKey;
MoveToken (Map, EnteredKey, (i%2 == 0 ? FirstPlayer : SecondPlayer) );
if (CheckIfWin(FirstPlayer, SecondPlayer))
{
cout << GetWinner(FirstPlayer, SecondPlayer, i) << " a gagne !" << endl;
return 0;
}
}
cout << "Egalite !" << endl;
return 0;
}
}
int main()
{
ppal ();
return 0;
}
| pcppg4/JeuVoleur | main.cpp | C++ | gpl-3.0 | 7,600 |
/*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "Lightweight-Directory-Access-Protocol-V3"
* found in "simple_ldap_asn1.asn"
*/
#ifndef _SearchControlValue_H_
#define _SearchControlValue_H_
#include <asn_application.h>
/* Including external dependencies */
#include <INTEGER.h>
#include <OCTET_STRING.h>
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* SearchControlValue */
typedef struct SearchControlValue {
INTEGER_t size;
OCTET_STRING_t cookie;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} SearchControlValue_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_SearchControlValue;
#ifdef __cplusplus
}
#endif
#endif /* _SearchControlValue_H_ */
#include <asn_internal.h>
| uplusware/erisemail | src/ldap_asn1/SearchControlValue.h | C | gpl-3.0 | 794 |
/**
* This file is part of Rizzly.
*
* Rizzly 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.
*
* Rizzly 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 Rizzly. If not, see <http://www.gnu.org/licenses/>.
*/
package ast.pass.input.xml.parser.expression;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import org.junit.Test;
import ast.data.expression.Expression;
import ast.pass.input.xml.infrastructure.XmlParser;
import ast.pass.input.xml.scanner.ExpectionParser;
import error.RizzlyError;
public class ExpressionParser_Test {
final private ExpectionParser stream = mock(ExpectionParser.class);
final private XmlParser parser = mock(XmlParser.class);
final private RizzlyError error = mock(RizzlyError.class);
final private ExpressionParser testee = new ExpressionParser(stream, parser, error);
@Test
public void has_all_needed_value_parsers() {
assertNotNull(testee.parserFor("NumberValue"));
assertNotNull(testee.parserFor("BooleanValue"));
}
@Test
public void has_correct_type() {
assertEquals(testee, testee.parserFor(Expression.class));
}
}
| ursfassler/rizzly | src/ast/pass/input/xml/parser/expression/ExpressionParser_Test.java | Java | gpl-3.0 | 1,646 |
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/VCardUpdate.h>
namespace Swift {
class VCardUpdateSerializer : public GenericPayloadSerializer<VCardUpdate> {
public:
VCardUpdateSerializer();
virtual std::string serializePayload(boost::shared_ptr<VCardUpdate>) const;
};
}
| marosi/SocialDesktopClient | plugins/buddycloud/3rdparty/swift/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h | C | gpl-3.0 | 495 |
<?php
/**
* BabDev Transifex Package
*
* @copyright Copyright (C) 2012-2014 Michael Babker. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License Version 2 or Later
*/
namespace BabDev\Transifex;
/**
* Transifex API Languages class.
*
* @link http://docs.transifex.com/developer/api/languages
* @since 1.0
*/
class Languages extends TransifexObject
{
/**
* Method to create a language for a project.
*
* @param string $slug The slug for the project
* @param string $langCode The language code for the new language
* @param array $coordinators An array of coordinators for the language
* @param array $options Optional additional params to send with the request
* @param boolean $skipInvalidUsername If true, the API call does not fail and instead will return a list of invalid usernames
*
* @return \stdClass
*
* @since 1.0
* @throws \InvalidArgumentException
*/
public function createLanguage($slug, $langCode, array $coordinators, array $options = array(), $skipInvalidUsername = false)
{
// Make sure the $coordinators array is not empty
if (count($coordinators) < 1)
{
throw new \InvalidArgumentException('The coordinators array must contain at least one username.');
}
// Build the request path.
$path = '/project/' . $slug . '/languages/';
// Check if invalid usernames should be skipped
if ($skipInvalidUsername)
{
$path .= '?skip_invalid_username';
}
// Build the required request data.
$data = array(
'language_code' => $langCode,
'coordinators' => $coordinators
);
// Valid options to check
$validOptions = array('translators', 'reviewers', 'list');
// Loop through the valid options and if we have them, add them to the request data
foreach ($validOptions as $option)
{
if (isset($options[$option]))
{
$data[$option] = $options[$option];
}
}
// Send the request.
return $this->processResponse(
$this->client->post(
$this->fetchUrl($path),
json_encode($data),
array('Content-Type' => 'application/json')
),
201
);
}
/**
* Method to delete a language within a project.
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
*
* @return \stdClass
*
* @since 1.0
*/
public function deleteLanguage($project, $langCode)
{
// Build the request path.
$path = '/project/' . $project . '/language/' . $langCode . '/';
// Send the request.
return $this->processResponse($this->client->delete($this->fetchUrl($path)), 204);
}
/**
* Method to get the coordinators for a language team in a project
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
*
* @return \stdClass The coordinator information from the API.
*
* @since 1.0
*/
public function getCoordinators($project, $langCode)
{
// Build the request path.
$path = '/project/' . $project . '/language/' . $langCode . '/coordinators/';
// Send the request.
return $this->processResponse($this->client->get($this->fetchUrl($path)));
}
/**
* Method to get information about a given language in a project.
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
*
* @return \stdClass The language details for the specified project from the API.
*
* @since 1.0
*/
public function getLanguage($project, $langCode)
{
// Build the request path.
$path = '/project/' . $project . '/language/' . $langCode . '/';
// Send the request.
return $this->processResponse($this->client->get($this->fetchUrl($path)));
}
/**
* Method to get a list of languages for a specified project.
*
* @param string $project The project to retrieve details for
*
* @return \stdClass The language data for the project.
*
* @since 1.0
*/
public function getLanguages($project)
{
// Build the request path.
$path = '/project/' . $project . '/languages/';
// Send the request.
return $this->processResponse($this->client->get($this->fetchUrl($path)));
}
/**
* Method to get the reviewers for a language team in a project
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
*
* @return \stdClass The reviewer information from the API.
*
* @since 1.0
*/
public function getReviewers($project, $langCode)
{
// Build the request path.
$path = '/project/' . $project . '/language/' . $langCode . '/reviewers/';
// Send the request.
return $this->processResponse($this->client->get($this->fetchUrl($path)));
}
/**
* Method to get the translators for a language team in a project
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
*
* @return \stdClass The translators information from the API.
*
* @since 1.0
*/
public function getTranslators($project, $langCode)
{
// Build the request path.
$path = '/project/' . $project . '/language/' . $langCode . '/translators/';
// Send the request.
return $this->processResponse($this->client->get($this->fetchUrl($path)));
}
/**
* Method to update the coordinators for a language team in a project
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
* @param array $coordinators An array of coordinators for the language
* @param boolean $skipInvalidUsername If true, the API call does not fail and instead will return a list of invalid usernames
*
* @return \stdClass
*
* @since 1.0
*/
public function updateCoordinators($project, $langCode, array $coordinators, $skipInvalidUsername = false)
{
return $this->updateTeam($project, $langCode, $coordinators, $skipInvalidUsername, 'coordinators');
}
/**
* Method to update a language within a project.
*
* @param string $slug The slug for the project
* @param string $langCode The language code for the new language
* @param array $coordinators An array of coordinators for the language
* @param array $options Optional additional params to send with the request
*
* @return \stdClass
*
* @since 1.0
* @throws \InvalidArgumentException
*/
public function updateLanguage($slug, $langCode, array $coordinators, array $options = array())
{
// Make sure the $coordinators array is not empty
if (count($coordinators) < 1)
{
throw new \InvalidArgumentException('The coordinators array must contain at least one username.');
}
// Build the request path.
$path = '/project/' . $slug . '/language/' . $langCode . '/';
// Build the required request data.
$data = array('coordinators' => $coordinators);
// Set the translators if present
if (isset($options['translators']))
{
$data['translators'] = $options['translators'];
}
// Set the reviewers if present
if (isset($options['reviewers']))
{
$data['reviewers'] = $options['reviewers'];
}
// Send the request.
return $this->processResponse(
$this->client->put(
$this->fetchUrl($path),
json_encode($data),
array('Content-Type' => 'application/json')
),
200
);
}
/**
* Method to update the reviewers for a language team in a project
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
* @param array $reviewers An array of reviewers for the language
* @param boolean $skipInvalidUsername If true, the API call does not fail and instead will return a list of invalid usernames
*
* @return \stdClass
*
* @since 1.0
*/
public function updateReviewers($project, $langCode, array $reviewers, $skipInvalidUsername = false)
{
return $this->updateTeam($project, $langCode, $reviewers, $skipInvalidUsername, 'reviewers');
}
/**
* Base method to update a given language team in a project
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
* @param array $members An array of the team members for the language
* @param boolean $skipInvalidUsername If true, the API call does not fail and instead will return a list of invalid usernames
* @param string $team The team to update
*
* @return \stdClass
*
* @since 1.0
* @throws \InvalidArgumentException
*/
protected function updateTeam($project, $langCode, array $members, $skipInvalidUsername, $team)
{
// Make sure the $members array is not empty
if (count($members) < 1)
{
throw new \InvalidArgumentException('The ' . $team . ' array must contain at least one username.');
}
// Build the request path.
$path = '/project/' . $project . '/language/' . $langCode . '/' . $team . '/';
// Check if invalid usernames should be skipped
if ($skipInvalidUsername)
{
$path .= '?skip_invalid_username';
}
// Send the request.
return $this->processResponse(
$this->client->put(
$this->fetchUrl($path),
json_encode($members),
array('Content-Type' => 'application/json')
),
200
);
}
/**
* Method to update the translators for a language team in a project
*
* @param string $project The project to retrieve details for
* @param string $langCode The language code to retrieve details for
* @param array $translators An array of translators for the language
* @param boolean $skipInvalidUsername If true, the API call does not fail and instead will return a list of invalid usernames
*
* @return \stdClass
*
* @since 1.0
*/
public function updateTranslators($project, $langCode, array $translators, $skipInvalidUsername = false)
{
return $this->updateTeam($project, $langCode, $translators, $skipInvalidUsername, 'translators');
}
}
| kasobus/EDENS-Mautic | vendor/babdev/transifex/src/Languages.php | PHP | gpl-3.0 | 10,406 |
<?php
// --------------------------------------------------------
// SESSION CHECK TO SEE IF USER IS LOGGED IN.
session_start();
if ((!isset($_SESSION['username'])) || (!isset($_SESSION['userID']))){
header('location: ../login.php'); // If they aren't logged in, send them to login page.
} else { // If they are logged in and have set a callsign, show the page.
// --------------------------------------------------------
?>
<?php
# AUTOLOAD CLASSES
require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/includes/autoloadClasses.php');
$classDB = new Database();
# Check if old structure ports table structure and update if needed
$classDB->upgrade_ports_table_structure();
# Check and Update Database Structure with new fields if they don't already exist
$classDB->add_record('settings','ID_Only_When_Active','False');
$classDB->add_record('settings','Location_Info','');
$classDB->add_record('settings','LinkGroup_Settings','');
$classDB->add_record('system_flags','config_files','');
# Add macros table if it doesn't exist
$classDB->insert('CREATE TABLE IF NOT EXISTS macros ( macroKey INTEGER PRIMARY KEY, macroEnabled INTEGER, macroNum INTEGER, macroLabel TEXT, macroModuleID INTEGER, macroString TEXT, macroPorts TEXT);');
# Add devices table if it doesn't exist
$classDB->insert('CREATE TABLE IF NOT EXISTS devices ( device_id INTEGER PRIMARY KEY NOT NULL, device_path TEXT, description TEXT, type TEXT);');
# Update Users Table to Newer Format
if ( !$classDB->exists_column('users', 'enabled') ) {
$classDB->add_table_column('users', 'enabled', 'INTEGER', '1');
}
if ( !$classDB->exists_column('users', 'user_role') ) {
$classDB->add_table_column('users', 'user_role', 'TEXT', '');
$classDB->update("UPDATE users SET user_role='admin' WHERE userID = '1';");
}
if ( !$classDB->exists_column('users', 'user_meta') ) {
$classDB->add_table_column('users', 'user_meta', 'TEXT', '');
}
# Convert to JSON function
function serial2JSON($setting, $table, $db) {
$results = $db->select_single("SELECT value FROM $table WHERE keyID='LinkGroup_Settings'");
// Check if setting is serialized, and if it is converit it to JSON format
$data = @unserialize($results['value']);
if ($data !== false) {
$converted = json_encode($data);
$db->update("UPDATE $table SET value='$converted' WHERE keyID='LinkGroup_Settings'");
}
}
# Convert the follwoing to JSON format using above function
serial2JSON('Location_Info','settings',$classDB);
serial2JSON('LinkGroup_Settings','settings',$classDB);
# Convert Port Options to JSON
$ports = $classDB->select_all('ports','SELECT * FROM ports');
foreach($ports as $curPort) {
// Check if setting is serialized, and if it is converit it to JSON format
$curOptions = @unserialize($curPort['portOptions']);
if ($curOptions !== false) {
$curPortNum = $curPort['portNum'];
$converted = json_encode($curOptions);
$classDB->update("UPDATE ports SET portOptions='$converted' WHERE portNum='$curPortNum'");
}
}
# Convert Module Options to JSON
$modules = $classDB->select_all('modules','SELECT * FROM modules');
foreach($modules as $curModules) {
// Check if setting is serialized, and if it is converit it to JSON format
$curOptions = @unserialize($curModules['moduleOptions']);
if ($curOptions !== false) {
$curModuleKey = $curModules['moduleKey'];
$converted = json_encode($curOptions);
$classDB->update("UPDATE modules SET moduleOptions='$converted' WHERE moduleKey='$curModuleKey'");
}
}
# Update version table and add SVXLink Release if it doesn't exist.
if ( !$classDB->exists_column('version_info', 'svxlink_release') ) {
$version_results = $classDB->select_single('SELECT version_num FROM version_info LIMIT 1');
switch (true) {
case stristr($version_results['version_num'],'2.1.0'):
case stristr($version_results['version_num'],'2.1.1'):
case stristr($version_results['version_num'],'2.1.2'):
$svxlink_ver = '17.12.2';
break;
case stristr($version_results['version_num'],'2.1.3'):
case stristr($version_results['version_num'],'2.2'):
case stristr($version_results['version_num'],'3.0'):
$svxlink_ver = '19.09.1';
break;
}
$classDB->add_table_column('version_info', 'svxlink_release');
$classDB->update("UPDATE version_info SET svxlink_release='$svxlink_ver' WHERE ROWID = 1;");
}
?>
<?php
include('header.php');
$result = 'dummy';
if ($result) { echo 'Database Updated on <strong>' . date('Y-m-d h:i:sa') . '</strong>'; } else { echo "<h1>ERROR UPDATING DATABASE</h1>"; }
include('footer.php');
?>
<?php
// --------------------------------------------------------
// SESSION CHECK TO SEE IF USER IS LOGGED IN.
} // close ELSE to end login check from top of page
// --------------------------------------------------------
?> | OpenRepeater/OpenRepeater | dev_ui/dbupdate.php | PHP | gpl-3.0 | 4,767 |
#pragma message("bigreqstr.h is obsolete and may be removed in the future.")
#pragma message("include <X11/extensions/bigreqsproto.h> for the protocol defines.")
#include <X11/extensions/bigreqsproto.h>
| ArcticaProject/vcxsrv | X11/extensions/bigreqstr.h | C | gpl-3.0 | 203 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>debtor:testDepreciateInvoice</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">debtor:testDepreciateInvoice</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>install/reset-staging-server.php?modules=onlinepayment,debtor,invoice,contact,product,administration&helper_function=Administration:fillInIntranetAddress,Debtor:createInvoice&login=true</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=login</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=debtor</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Test invoice</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>sent</td>
<td></td>
</tr>
<tr>
<td>assertTextPresent</td>
<td>I am not going to recieve the full payment...</td>
<td></td>
</tr>
<tr>
<td>assertConfirmation</td>
<td>Are you sure?</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=I am not going to recieve the full payment...</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>amount</td>
<td>200,00</td>
</tr>
<tr>
<td>type</td>
<td>payment_date</td>
<td>10-10-2008</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>depreciation</td>
<td></td>
</tr>
<tr>
<td>assertTextPresent</td>
<td>depreciation</td>
<td></td>
</tr>
<tr>
<td>assertTextPresent</td>
<td>Missing payment</td>
<td></td>
</tr>
<tr>
<td>assertTextPresent</td>
<td>175,00</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=I am not going to recieve the full payment...</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>depreciation</td>
<td></td>
</tr>
<tr>
<td>assertTextPresent</td>
<td>executed</td>
<td></td>
</tr>
<tr>
<td>verifyTextNotPresent</td>
<td>I am not going to recieve the full payment...</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
| intraface/intraface.dk | tests/selenium/debtor/testDepreciateInvoice.html | HTML | gpl-3.0 | 2,190 |
using uint8_t = System.Byte;
using uint16_t = System.UInt16;
using uint32_t = System.UInt32;
using uint64_t = System.UInt64;
using int8_t = System.SByte;
using int16_t = System.Int16;
using int32_t = System.Int32;
using int64_t = System.Int64;
using float32 = System.Single;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace UAVCAN
{
public partial class uavcan {
static void encode_uavcan_protocol_file_GetInfo_req(uavcan_protocol_file_GetInfo_req msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx) {
uint8_t[] buffer = new uint8_t[8];
_encode_uavcan_protocol_file_GetInfo_req(buffer, msg, chunk_cb, ctx, true);
}
static uint32_t decode_uavcan_protocol_file_GetInfo_req(CanardRxTransfer transfer, uavcan_protocol_file_GetInfo_req msg) {
uint32_t bit_ofs = 0;
_decode_uavcan_protocol_file_GetInfo_req(transfer, ref bit_ofs, msg, true);
return (bit_ofs+7)/8;
}
static void _encode_uavcan_protocol_file_GetInfo_req(uint8_t[] buffer, uavcan_protocol_file_GetInfo_req msg, uavcan_serializer_chunk_cb_ptr_t chunk_cb, object ctx, bool tao) {
_encode_uavcan_protocol_file_Path(buffer, msg.path, chunk_cb, ctx, tao);
}
static void _decode_uavcan_protocol_file_GetInfo_req(CanardRxTransfer transfer,ref uint32_t bit_ofs, uavcan_protocol_file_GetInfo_req msg, bool tao) {
_decode_uavcan_protocol_file_Path(transfer, ref bit_ofs, msg.path, tao);
}
}
} | diydrones/MissionPlanner | ExtLibs/UAVCAN/out/src/uavcan.protocol.file.GetInfo_req.cs | C# | gpl-3.0 | 1,580 |
/*
* This file is part of the BlizzLikeCore Project. See CREDITS and LICENSE files
*
* 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 3 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
*/
#include "Common.h"
#include "Language.h"
#include "Database/DatabaseEnv.h"
#include "Database/DatabaseImpl.h"
#include "WorldPacket.h"
#include "Opcodes.h"
#include "Log.h"
#include "Player.h"
#include "World.h"
#include "GuildMgr.h"
#include "ObjectMgr.h"
#include "WorldSession.h"
#include "Auth/BigNumber.h"
#include "Auth/Sha1.h"
#include "UpdateData.h"
#include "LootMgr.h"
#include "Chat.h"
#include "ScriptMgr.h"
#include <zlib/zlib.h>
#include "ObjectAccessor.h"
#include "Object.h"
#include "BattleGround/BattleGround.h"
#include "OutdoorPvP/OutdoorPvP.h"
#include "Pet.h"
#include "SocialMgr.h"
void WorldSession::HandleRepopRequestOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_REPOP_REQUEST");
recv_data.read_skip<uint8>();
if (GetPlayer()->isAlive() || GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
return;
// the world update order is sessions, players, creatures
// the netcode runs in parallel with all of these
// creatures can kill players
// so if the server is lagging enough the player can
// release spirit after he's killed but before he is updated
if (GetPlayer()->getDeathState() == JUST_DIED)
{
DEBUG_LOG("HandleRepopRequestOpcode: got request after player %s(%d) was killed and before he was updated", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow());
GetPlayer()->KillPlayer();
}
// this is spirit release confirm?
GetPlayer()->RemovePet(PET_SAVE_REAGENTS);
GetPlayer()->BuildPlayerRepop();
GetPlayer()->RepopAtGraveyard();
}
void WorldSession::HandleWhoOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_WHO");
// recv_data.hexlike();
// prevent who command from being spammed and causing the server to lag
/*time_t now = time(NULL);
if (now - timeLastWhoCommand < 5)
return;
else timeLastWhoCommand = now;*/
uint32 clientcount = 0;
uint32 level_min, level_max, racemask, classmask, zones_count, str_count;
uint32 zoneids[10]; // 10 is client limit
std::string player_name, guild_name;
recv_data >> level_min; // maximal player level, default 0
recv_data >> level_max; // minimal player level, default 100 (MAX_LEVEL)
recv_data >> player_name; // player name, case sensitive...
recv_data >> guild_name; // guild name, case sensitive...
recv_data >> racemask; // race mask
recv_data >> classmask; // class mask
recv_data >> zones_count; // zones count, client limit=10 (2.0.10)
if (zones_count > 10)
return; // can't be received from real client or broken packet
for (uint32 i = 0; i < zones_count; ++i)
{
uint32 temp;
recv_data >> temp; // zone id, 0 if zone is unknown...
zoneids[i] = temp;
DEBUG_LOG("Zone %u: %u", i, zoneids[i]);
}
recv_data >> str_count; // user entered strings count, client limit=4 (checked on 2.0.10)
if (str_count > 4)
return; // can't be received from real client or broken packet
DEBUG_LOG("Minlvl %u, maxlvl %u, name %s, guild %s, racemask %u, classmask %u, zones %u, strings %u", level_min, level_max, player_name.c_str(), guild_name.c_str(), racemask, classmask, zones_count, str_count);
std::wstring str[4]; // 4 is client limit
for (uint32 i = 0; i < str_count; ++i)
{
std::string temp;
recv_data >> temp; // user entered string, it used as universal search pattern(guild+player name)?
if (!Utf8toWStr(temp, str[i]))
continue;
wstrToLower(str[i]);
DEBUG_LOG("String %u: %s", i, temp.c_str());
}
std::wstring wplayer_name;
std::wstring wguild_name;
if (!(Utf8toWStr(player_name, wplayer_name) && Utf8toWStr(guild_name, wguild_name)))
return;
wstrToLower(wplayer_name);
wstrToLower(wguild_name);
// client send in case not set max level value 100 but BlizzLike support 255 max level,
// update it to show GMs with characters after 100 level
if (level_max >= MAX_LEVEL)
level_max = STRONG_MAX_LEVEL;
Team team = _player->GetTeam();
AccountTypes security = GetSecurity();
bool allowTwoSideWhoList = sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_WHO_LIST);
AccountTypes gmLevelInWhoList = (AccountTypes)sWorld.getConfig(CONFIG_UINT32_GM_LEVEL_IN_WHO_LIST);
WorldPacket data(SMSG_WHO, 50); // guess size
data << uint32(clientcount); // clientcount place holder, listed count
data << uint32(clientcount); // clientcount place holder, online count
// TODO: Guard Player map
HashMapHolder<Player>::MapType& m = sObjectAccessor.GetPlayers();
for (HashMapHolder<Player>::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr)
{
Player* pl = itr->second;
if (security == SEC_PLAYER)
{
// player can see member of other team only if CONFIG_BOOL_ALLOW_TWO_SIDE_WHO_LIST
if (pl->GetTeam() != team && !allowTwoSideWhoList)
continue;
// player can see MODERATOR, GAME MASTER, ADMINISTRATOR only if CONFIG_GM_IN_WHO_LIST
if (pl->GetSession()->GetSecurity() > gmLevelInWhoList)
continue;
}
// do not process players which are not in world
if (!pl->IsInWorld())
continue;
// check if target is globally visible for player
if (!pl->IsVisibleGloballyFor(_player))
continue;
// check if target's level is in level range
uint32 lvl = pl->getLevel();
if (lvl < level_min || lvl > level_max)
continue;
// check if class matches classmask
uint32 class_ = pl->getClass();
if (!(classmask & (1 << class_)))
continue;
// check if race matches racemask
uint32 race = pl->getRace();
if (!(racemask & (1 << race)))
continue;
uint32 pzoneid = pl->GetZoneId();
uint8 gender = pl->getGender();
bool z_show = true;
for (uint32 i = 0; i < zones_count; ++i)
{
if (zoneids[i] == pzoneid)
{
z_show = true;
break;
}
z_show = false;
}
if (!z_show)
continue;
std::string pname = pl->GetName();
std::wstring wpname;
if (!Utf8toWStr(pname, wpname))
continue;
wstrToLower(wpname);
if (!(wplayer_name.empty() || wpname.find(wplayer_name) != std::wstring::npos))
continue;
std::string gname = sGuildMgr.GetGuildNameById(pl->GetGuildId());
std::wstring wgname;
if (!Utf8toWStr(gname, wgname))
continue;
wstrToLower(wgname);
if (!(wguild_name.empty() || wgname.find(wguild_name) != std::wstring::npos))
continue;
std::string aname;
if (AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(pzoneid))
aname = areaEntry->area_name[GetSessionDbcLocale()];
bool s_show = true;
for (uint32 i = 0; i < str_count; ++i)
{
if (!str[i].empty())
{
if (wgname.find(str[i]) != std::wstring::npos ||
wpname.find(str[i]) != std::wstring::npos ||
Utf8FitTo(aname, str[i]))
{
s_show = true;
break;
}
s_show = false;
}
}
if (!s_show)
continue;
data << pname; // player name
data << gname; // guild name
data << uint32(lvl); // player level
data << uint32(class_); // player class
data << uint32(race); // player race
data << uint8(gender); // player gender
data << uint32(pzoneid); // player zone id
// 50 is maximum player count sent to client
if ((++clientcount) == 50)
break;
}
uint32 count = m.size();
data.put(0, clientcount); // insert right count, listed count
data.put(4, count > 50 ? count : clientcount); // insert right count, online count
SendPacket(&data);
DEBUG_LOG("WORLD: Send SMSG_WHO Message");
}
void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recv_data*/)
{
DEBUG_LOG("WORLD: Received opcode CMSG_LOGOUT_REQUEST, security %u", GetSecurity());
if (ObjectGuid lootGuid = GetPlayer()->GetLootGuid())
DoLootRelease(lootGuid);
// Can not logout if...
if (GetPlayer()->isInCombat() || //...is in combat
GetPlayer()->duel || //...is in Duel
//...is jumping ...is falling
GetPlayer()->m_movementInfo.HasMovementFlag(MovementFlags(MOVEFLAG_FALLING | MOVEFLAG_FALLINGFAR)))
{
WorldPacket data(SMSG_LOGOUT_RESPONSE, (2 + 4)) ;
data << (uint8)0xC;
data << uint32(0);
data << uint8(0);
SendPacket(&data);
LogoutRequest(0);
return;
}
// instant logout in taverns/cities or on taxi or for admins, gm's, mod's if its enabled in worldserver.conf
if (GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) || GetPlayer()->IsTaxiFlying() ||
GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_INSTANT_LOGOUT))
{
LogoutPlayer(true);
return;
}
// not set flags if player can't free move to prevent lost state at logout cancel
if (GetPlayer()->CanFreeMove())
{
float height = GetPlayer()->GetMap()->GetHeight(GetPlayer()->GetPositionX(), GetPlayer()->GetPositionY(), GetPlayer()->GetPositionZ());
if ((GetPlayer()->GetPositionZ() < height + 0.1f) && !(GetPlayer()->IsInWater()))
GetPlayer()->SetStandState(UNIT_STAND_STATE_SIT);
GetPlayer()->SetRoot(true);
GetPlayer()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
}
WorldPacket data(SMSG_LOGOUT_RESPONSE, 5);
data << uint32(0);
data << uint8(0);
SendPacket(&data);
LogoutRequest(time(NULL));
}
void WorldSession::HandlePlayerLogoutOpcode(WorldPacket & /*recv_data*/)
{
DEBUG_LOG("WORLD: Received opcode CMSG_PLAYER_LOGOUT Message");
}
void WorldSession::HandleLogoutCancelOpcode(WorldPacket & /*recv_data*/)
{
DEBUG_LOG("WORLD: Received opcode CMSG_LOGOUT_CANCEL Message");
LogoutRequest(0);
WorldPacket data(SMSG_LOGOUT_CANCEL_ACK, 0);
SendPacket(&data);
// not remove flags if can't free move - its not set in Logout request code.
if (GetPlayer()->CanFreeMove())
{
//!we can move again
GetPlayer()->SetRoot(false);
//! Stand Up
GetPlayer()->SetStandState(UNIT_STAND_STATE_STAND);
//! DISABLE_ROTATE
GetPlayer()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
}
DEBUG_LOG("WORLD: sent SMSG_LOGOUT_CANCEL_ACK Message");
}
void WorldSession::HandleTogglePvP(WorldPacket& recv_data)
{
// this opcode can be used in two ways: Either set explicit new status or toggle old status
if (recv_data.size() == 1)
{
bool newPvPStatus;
recv_data >> newPvPStatus;
GetPlayer()->ApplyModFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP, newPvPStatus);
}
else
{
GetPlayer()->ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP);
}
if (GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP))
{
if (!GetPlayer()->IsPvP() || GetPlayer()->pvpInfo.endTimer != 0)
GetPlayer()->UpdatePvP(true, true);
}
else
{
if (!GetPlayer()->pvpInfo.inHostileArea && GetPlayer()->IsPvP())
GetPlayer()->pvpInfo.endTimer = time(NULL); // start toggle-off
}
}
void WorldSession::HandleZoneUpdateOpcode(WorldPacket& recv_data)
{
uint32 newZone;
recv_data >> newZone;
DETAIL_LOG("WORLD: Received opcode CMSG_ZONEUPDATE: newzone is %u", newZone);
// use server side data
uint32 newzone, newarea;
GetPlayer()->GetZoneAndAreaId(newzone, newarea);
GetPlayer()->UpdateZone(newzone, newarea);
}
void WorldSession::HandleSetTargetOpcode(WorldPacket& recv_data)
{
// When this packet send?
ObjectGuid guid ;
recv_data >> guid;
_player->SetTargetGuid(guid);
// update reputation list if need
Unit* unit = ObjectAccessor::GetUnit(*_player, guid); // can select group members at diff maps
if (!unit)
return;
if (FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(unit->getFaction()))
_player->GetReputationMgr().SetVisible(factionTemplateEntry);
}
void WorldSession::HandleSetSelectionOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
recv_data >> guid;
_player->SetSelectionGuid(guid);
// update reputation list if need
Unit* unit = ObjectAccessor::GetUnit(*_player, guid); // can select group members at diff maps
if (!unit)
return;
if (FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(unit->getFaction()))
_player->GetReputationMgr().SetVisible(factionTemplateEntry);
}
void WorldSession::HandleStandStateChangeOpcode(WorldPacket& recv_data)
{
// DEBUG_LOG("WORLD: Received opcode CMSG_STANDSTATECHANGE"); -- too many spam in log at lags/debug stop
uint32 animstate;
recv_data >> animstate;
_player->SetStandState(animstate);
}
void WorldSession::HandleContactListOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_CONTACT_LIST");
uint32 unk;
recv_data >> unk;
DEBUG_LOG("unk value is %u", unk);
_player->GetSocial()->SendSocialList();
}
void WorldSession::HandleAddFriendOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_ADD_FRIEND");
std::string friendName = GetBlizzLikeString(LANG_FRIEND_IGNORE_UNKNOWN);
std::string friendNote;
recv_data >> friendName;
recv_data >> friendNote;
if (!normalizePlayerName(friendName))
return;
CharacterDatabase.escape_string(friendName); // prevent SQL injection - normal name don't must changed by this call
DEBUG_LOG("WORLD: %s asked to add friend : '%s'",
GetPlayer()->GetName(), friendName.c_str());
CharacterDatabase.AsyncPQuery(&WorldSession::HandleAddFriendOpcodeCallBack, GetAccountId(), friendNote, "SELECT guid, race FROM characters WHERE name = '%s'", friendName.c_str());
}
void WorldSession::HandleAddFriendOpcodeCallBack(QueryResult* result, uint32 accountId, std::string friendNote)
{
if (!result)
return;
uint32 friendLowGuid = (*result)[0].GetUInt32();
ObjectGuid friendGuid = ObjectGuid(HIGHGUID_PLAYER, friendLowGuid);
Team team = Player::TeamForRace((*result)[1].GetUInt8());
delete result;
WorldSession* session = sWorld.FindSession(accountId);
if (!session || !session->GetPlayer())
return;
FriendsResult friendResult = FRIEND_NOT_FOUND;
if (friendGuid)
{
if (friendGuid == session->GetPlayer()->GetObjectGuid())
friendResult = FRIEND_SELF;
else if (session->GetPlayer()->GetTeam() != team && !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_ADD_FRIEND) && session->GetSecurity() < SEC_MODERATOR)
friendResult = FRIEND_ENEMY;
else if (session->GetPlayer()->GetSocial()->HasFriend(friendGuid))
friendResult = FRIEND_ALREADY;
else
{
Player* pFriend = ObjectAccessor::FindPlayer(friendGuid);
if (pFriend && pFriend->IsInWorld() && pFriend->IsVisibleGloballyFor(session->GetPlayer()))
friendResult = FRIEND_ADDED_ONLINE;
else
friendResult = FRIEND_ADDED_OFFLINE;
if (!session->GetPlayer()->GetSocial()->AddToSocialList(friendGuid, false))
{
friendResult = FRIEND_LIST_FULL;
DEBUG_LOG("WORLD: %s's friend list is full.", session->GetPlayer()->GetName());
}
session->GetPlayer()->GetSocial()->SetFriendNote(friendGuid, friendNote);
}
}
sSocialMgr.SendFriendStatus(session->GetPlayer(), friendResult, friendGuid, false);
DEBUG_LOG("WORLD: Sent (SMSG_FRIEND_STATUS)");
}
void WorldSession::HandleDelFriendOpcode(WorldPacket& recv_data)
{
ObjectGuid friendGuid;
DEBUG_LOG("WORLD: Received opcode CMSG_DEL_FRIEND");
recv_data >> friendGuid;
_player->GetSocial()->RemoveFromSocialList(friendGuid, false);
sSocialMgr.SendFriendStatus(GetPlayer(), FRIEND_REMOVED, friendGuid, false);
DEBUG_LOG("WORLD: Sent motd (SMSG_FRIEND_STATUS)");
}
void WorldSession::HandleAddIgnoreOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_ADD_IGNORE");
std::string IgnoreName = GetBlizzLikeString(LANG_FRIEND_IGNORE_UNKNOWN);
recv_data >> IgnoreName;
if (!normalizePlayerName(IgnoreName))
return;
CharacterDatabase.escape_string(IgnoreName); // prevent SQL injection - normal name don't must changed by this call
DEBUG_LOG("WORLD: %s asked to Ignore: '%s'",
GetPlayer()->GetName(), IgnoreName.c_str());
CharacterDatabase.AsyncPQuery(&WorldSession::HandleAddIgnoreOpcodeCallBack, GetAccountId(), "SELECT guid FROM characters WHERE name = '%s'", IgnoreName.c_str());
}
void WorldSession::HandleAddIgnoreOpcodeCallBack(QueryResult* result, uint32 accountId)
{
if (!result)
return;
uint32 ignoreLowGuid = (*result)[0].GetUInt32();
ObjectGuid ignoreGuid = ObjectGuid(HIGHGUID_PLAYER, ignoreLowGuid);
delete result;
WorldSession* session = sWorld.FindSession(accountId);
if (!session || !session->GetPlayer())
return;
FriendsResult ignoreResult = FRIEND_IGNORE_NOT_FOUND;
if (ignoreGuid)
{
if (ignoreGuid == session->GetPlayer()->GetObjectGuid())
ignoreResult = FRIEND_IGNORE_SELF;
else if (session->GetPlayer()->GetSocial()->HasIgnore(ignoreGuid))
ignoreResult = FRIEND_IGNORE_ALREADY;
else
{
ignoreResult = FRIEND_IGNORE_ADDED;
// ignore list full
if (!session->GetPlayer()->GetSocial()->AddToSocialList(ignoreGuid, true))
ignoreResult = FRIEND_IGNORE_FULL;
}
}
sSocialMgr.SendFriendStatus(session->GetPlayer(), ignoreResult, ignoreGuid, false);
DEBUG_LOG("WORLD: Sent (SMSG_FRIEND_STATUS)");
}
void WorldSession::HandleDelIgnoreOpcode(WorldPacket& recv_data)
{
ObjectGuid ignoreGuid;
DEBUG_LOG("WORLD: Received opcode CMSG_DEL_IGNORE");
recv_data >> ignoreGuid;
_player->GetSocial()->RemoveFromSocialList(ignoreGuid, true);
sSocialMgr.SendFriendStatus(GetPlayer(), FRIEND_IGNORE_REMOVED, ignoreGuid, false);
DEBUG_LOG("WORLD: Sent motd (SMSG_FRIEND_STATUS)");
}
void WorldSession::HandleSetContactNotesOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_SET_CONTACT_NOTES");
ObjectGuid guid;
std::string note;
recv_data >> guid >> note;
_player->GetSocial()->SetFriendNote(guid, note);
}
void WorldSession::HandleBugOpcode(WorldPacket& recv_data)
{
uint32 suggestion, contentlen, typelen;
std::string content, type;
recv_data >> suggestion >> contentlen >> content;
recv_data >> typelen >> type;
if (suggestion == 0)
DEBUG_LOG("WORLD: Received opcode CMSG_BUG [Bug Report]");
else
DEBUG_LOG("WORLD: Received opcode CMSG_BUG [Suggestion]");
DEBUG_LOG("%s", type.c_str());
DEBUG_LOG("%s", content.c_str());
CharacterDatabase.escape_string(type);
CharacterDatabase.escape_string(content);
CharacterDatabase.PExecute("INSERT INTO bugreport (type,content) VALUES('%s', '%s')", type.c_str(), content.c_str());
}
void WorldSession::HandleReclaimCorpseOpcode(WorldPacket& recv_data)
{
DETAIL_LOG("WORLD: Received opcode CMSG_RECLAIM_CORPSE");
ObjectGuid guid;
recv_data >> guid;
if (GetPlayer()->isAlive())
return;
// do not allow corpse reclaim in arena
if (GetPlayer()->InArena())
return;
// body not released yet
if (!GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
return;
Corpse* corpse = GetPlayer()->GetCorpse();
if (!corpse)
return;
// prevent resurrect before 30-sec delay after body release not finished
if (corpse->GetGhostTime() + GetPlayer()->GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP) > time(NULL))
return;
if (!corpse->IsWithinDistInMap(GetPlayer(), CORPSE_RECLAIM_RADIUS, true))
return;
// resurrect
GetPlayer()->ResurrectPlayer(GetPlayer()->InBattleGround() ? 1.0f : 0.5f);
// spawn bones
GetPlayer()->SpawnCorpseBones();
}
void WorldSession::HandleResurrectResponseOpcode(WorldPacket& recv_data)
{
DETAIL_LOG("WORLD: Received opcode CMSG_RESURRECT_RESPONSE");
ObjectGuid guid;
uint8 status;
recv_data >> guid;
recv_data >> status;
if (GetPlayer()->isAlive())
return;
if (status == 0)
{
GetPlayer()->clearResurrectRequestData(); // reject
return;
}
if (!GetPlayer()->isRessurectRequestedBy(guid))
return;
GetPlayer()->ResurectUsingRequestData(); // will call spawncorpsebones
}
void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_AREATRIGGER");
uint32 Trigger_ID;
recv_data >> Trigger_ID;
DEBUG_LOG("Trigger ID: %u", Trigger_ID);
Player* player = GetPlayer();
if (player->IsTaxiFlying())
{
DEBUG_LOG("Player '%s' (GUID: %u) in flight, ignore Area Trigger ID: %u", player->GetName(), player->GetGUIDLow(), Trigger_ID);
return;
}
AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(Trigger_ID);
if (!atEntry)
{
DEBUG_LOG("Player '%s' (GUID: %u) send unknown (by DBC) Area Trigger ID: %u", player->GetName(), player->GetGUIDLow(), Trigger_ID);
return;
}
// delta is safe radius
const float delta = 5.0f;
// check if player in the range of areatrigger
if (!IsPointInAreaTriggerZone(atEntry, player->GetMapId(), player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), delta))
{
DEBUG_LOG("Player '%s' (GUID: %u) too far, ignore Area Trigger ID: %u", player->GetName(), player->GetGUIDLow(), Trigger_ID);
return;
}
if (sScriptMgr.OnAreaTrigger(player, atEntry))
return;
uint32 quest_id = sObjectMgr.GetQuestForAreaTrigger(Trigger_ID);
if (quest_id && player->isAlive() && player->IsActiveQuest(quest_id))
{
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (pQuest)
{
if (player->GetQuestStatus(quest_id) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(quest_id);
}
}
// enter to tavern, not overwrite city rest
if (sObjectMgr.IsTavernAreaTrigger(Trigger_ID))
{
// set resting flag we are in the inn
if (player->GetRestType() != REST_TYPE_IN_CITY)
player->SetRestType(REST_TYPE_IN_TAVERN, Trigger_ID);
return;
}
if (BattleGround* bg = player->GetBattleGround())
{
bg->HandleAreaTrigger(player, Trigger_ID);
return;
}
else if (OutdoorPvP* outdoorPvP = sOutdoorPvPMgr.GetScript(player->GetCachedZoneId()))
{
if (outdoorPvP->HandleAreaTrigger(player, Trigger_ID))
return;
}
// NULL if all values default (non teleport trigger)
AreaTrigger const* at = sObjectMgr.GetAreaTrigger(Trigger_ID);
if (!at)
return;
MapEntry const* targetMapEntry = sMapStore.LookupEntry(at->target_mapId);
if (!targetMapEntry)
return;
// ghost resurrected at enter attempt to dungeon with corpse (including fail enter cases)
if (!player->isAlive() && targetMapEntry->IsDungeon())
{
int32 corpseMapId = 0;
if (Corpse* corpse = player->GetCorpse())
corpseMapId = corpse->GetMapId();
// check back way from corpse to entrance
uint32 instance_map = corpseMapId;
do
{
// most often fast case
if (instance_map == targetMapEntry->MapID)
break;
InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(instance_map);
instance_map = instance ? instance->parent : 0;
}
while (instance_map);
// corpse not in dungeon or some linked deep dungeons
if (!instance_map)
{
player->GetSession()->SendAreaTriggerMessage("You cannot enter %s while in a ghost mode",
targetMapEntry->name[player->GetSession()->GetSessionDbcLocale()]);
return;
}
// need find areatrigger to inner dungeon for landing point
if (at->target_mapId != corpseMapId)
{
if (AreaTrigger const* corpseAt = sObjectMgr.GetMapEntranceTrigger(corpseMapId))
{
at = corpseAt;
targetMapEntry = sMapStore.LookupEntry(at->target_mapId);
if (!targetMapEntry)
return;
}
}
// now we can resurrect player, and then check teleport requirements
player->ResurrectPlayer(0.5f);
player->SpawnCorpseBones();
}
// teleport player (trigger requirement will be checked on TeleportTo)
player->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, at->target_Orientation, TELE_TO_NOT_LEAVE_TRANSPORT, at);
}
void WorldSession::HandleUpdateAccountData(WorldPacket& recv_data)
{
DETAIL_LOG("WORLD: Received opcode CMSG_UPDATE_ACCOUNT_DATA");
recv_data.rpos(recv_data.wpos()); // prevent spam at unimplemented packet
// recv_data.hexlike();
}
void WorldSession::HandleRequestAccountData(WorldPacket& /*recv_data*/)
{
DETAIL_LOG("WORLD: Received opcode CMSG_REQUEST_ACCOUNT_DATA");
// recv_data.hexlike();
}
void WorldSession::HandleSetActionButtonOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_SET_ACTION_BUTTON");
uint8 button;
uint32 packetData;
recv_data >> button >> packetData;
uint32 action = ACTION_BUTTON_ACTION(packetData);
uint8 type = ACTION_BUTTON_TYPE(packetData);
DETAIL_LOG("BUTTON: %u ACTION: %u TYPE: %u", button, action, type);
if (!packetData)
{
DETAIL_LOG("MISC: Remove action from button %u", button);
GetPlayer()->removeActionButton(button);
}
else
{
switch (type)
{
case ACTION_BUTTON_MACRO:
case ACTION_BUTTON_CMACRO:
DETAIL_LOG("MISC: Added Macro %u into button %u", action, button);
break;
case ACTION_BUTTON_SPELL:
DETAIL_LOG("MISC: Added Spell %u into button %u", action, button);
break;
case ACTION_BUTTON_ITEM:
DETAIL_LOG("MISC: Added Item %u into button %u", action, button);
break;
default:
sLog.outError("MISC: Unknown action button type %u for action %u into button %u", type, action, button);
return;
}
GetPlayer()->addActionButton(button, action, type);
}
}
void WorldSession::HandleCompleteCinematic(WorldPacket & /*recv_data*/)
{
DEBUG_LOG("WORLD: Received opcode CMSG_COMPLETE_CINEMATIC");
}
void WorldSession::HandleNextCinematicCamera(WorldPacket & /*recv_data*/)
{
DEBUG_LOG("WORLD: Received opcode CMSG_NEXT_CINEMATIC_CAMERA");
}
void WorldSession::HandleMoveTimeSkippedOpcode(WorldPacket& recv_data)
{
/* WorldSession::Update( WorldTimer::getMSTime() );*/
DEBUG_LOG("WORLD: Received opcode CMSG_MOVE_TIME_SKIPPED");
recv_data >> Unused<uint64>();
recv_data >> Unused<uint32>();
/*
ObjectGuid guid;
uint32 time_skipped;
recv_data >> guid;
recv_data >> time_skipped;
DEBUG_LOG("WORLD: Received opcode CMSG_MOVE_TIME_SKIPPED");
/// TODO
must be need use in BlizzLike
We substract server Lags to move time ( AntiLags )
for exmaple
GetPlayer()->ModifyLastMoveTime( -int32(time_skipped) );
*/
}
void WorldSession::HandleFeatherFallAck(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_MOVE_FEATHER_FALL_ACK");
// no used
recv_data.rpos(recv_data.wpos()); // prevent warnings spam
}
void WorldSession::HandleMoveUnRootAck(WorldPacket& recv_data)
{
// no used
recv_data.rpos(recv_data.wpos()); // prevent warnings spam
/*
ObjectGuid guid;
recv_data >> guid;
// now can skip not our packet
if(_player->GetGUID() != guid)
{
recv_data.rpos(recv_data.wpos()); // prevent warnings spam
return;
}
DEBUG_LOG("WORLD: Received opcode CMSG_FORCE_MOVE_UNROOT_ACK");
recv_data.read_skip<uint32>(); // unk
MovementInfo movementInfo;
ReadMovementInfo(recv_data, &movementInfo);
*/
}
void WorldSession::HandleMoveRootAck(WorldPacket& recv_data)
{
// no used
recv_data.rpos(recv_data.wpos()); // prevent warnings spam
/*
ObjectGuid guid;
recv_data >> guid;
// now can skip not our packet
if(_player->GetObjectGuid() != guid)
{
recv_data.rpos(recv_data.wpos()); // prevent warnings spam
return;
}
DEBUG_LOG("WORLD: Received opcode CMSG_FORCE_MOVE_ROOT_ACK");
recv_data.read_skip<uint32>(); // unk
MovementInfo movementInfo;
ReadMovementInfo(recv_data, &movementInfo);
*/
}
void WorldSession::HandleSetActionBarTogglesOpcode(WorldPacket& recv_data)
{
uint8 ActionBar;
recv_data >> ActionBar;
if (!GetPlayer()) // ignore until not logged (check needed because STATUS_AUTHED)
{
if (ActionBar != 0)
sLog.outError("WorldSession::HandleSetActionBarToggles in not logged state with value: %u, ignored", uint32(ActionBar));
return;
}
GetPlayer()->SetByteValue(PLAYER_FIELD_BYTES, 2, ActionBar);
}
void WorldSession::HandleWardenDataOpcode(WorldPacket& recv_data)
{
recv_data.read_skip<uint8>();
/*
uint8 tmp;
recv_data >> tmp;
DEBUG_LOG("Received opcode CMSG_WARDEN_DATA, not resolve.uint8 = %u", tmp);
*/
}
void WorldSession::HandlePlayedTime(WorldPacket& /*recv_data*/)
{
WorldPacket data(SMSG_PLAYED_TIME, 4 + 4);
data << uint32(_player->GetTotalPlayedTime());
data << uint32(_player->GetLevelPlayedTime());
SendPacket(&data);
}
void WorldSession::HandleInspectOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
recv_data >> guid;
DEBUG_LOG("Inspected guid is %s", guid.GetString().c_str());
_player->SetSelectionGuid(guid);
Player* plr = sObjectMgr.GetPlayer(guid);
if (!plr) // wrong player
return;
uint32 talent_points = 0x3D;
uint32 guid_size = plr->GetPackGUID().size();
WorldPacket data(SMSG_INSPECT_TALENT, 4 + talent_points);
data << plr->GetPackGUID();
data << uint32(talent_points);
// fill by 0 talents array
for (uint32 i = 0; i < talent_points; ++i)
data << uint8(0);
if (sWorld.getConfig(CONFIG_BOOL_TALENTS_INSPECTING) || _player->isGameMaster())
{
// find class talent tabs (all players have 3 talent tabs)
uint32 const* talentTabIds = GetTalentTabPages(plr->getClass());
uint32 talentTabPos = 0; // pos of first talent rank in tab including all prev tabs
for (uint32 i = 0; i < 3; ++i)
{
uint32 talentTabId = talentTabIds[i];
// fill by real data
for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
{
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if (!talentInfo)
continue;
// skip another tab talents
if (talentInfo->TalentTab != talentTabId)
continue;
// find talent rank
uint32 curtalent_maxrank = 0;
for (uint32 k = MAX_TALENT_RANK; k > 0; --k)
{
if (talentInfo->RankID[k-1] && plr->HasSpell(talentInfo->RankID[k-1]))
{
curtalent_maxrank = k;
break;
}
}
// not learned talent
if (!curtalent_maxrank)
continue;
// 1 rank talent bit index
uint32 curtalent_index = talentTabPos + GetTalentInspectBitPosInTab(talentId);
uint32 curtalent_rank_index = curtalent_index + curtalent_maxrank - 1;
// slot/offset in 7-bit bytes
uint32 curtalent_rank_slot7 = curtalent_rank_index / 7;
uint32 curtalent_rank_offset7 = curtalent_rank_index % 7;
// rank pos with skipped 8 bit
uint32 curtalent_rank_index2 = curtalent_rank_slot7 * 8 + curtalent_rank_offset7;
// slot/offset in 8-bit bytes with skipped high bit
uint32 curtalent_rank_slot = curtalent_rank_index2 / 8;
uint32 curtalent_rank_offset = curtalent_rank_index2 % 8;
// apply mask
uint32 val = data.read<uint8>(guid_size + 4 + curtalent_rank_slot);
val |= (1 << curtalent_rank_offset);
data.put<uint8>(guid_size + 4 + curtalent_rank_slot, val & 0xFF);
}
talentTabPos += GetTalentTabInspectBitSize(talentTabId);
}
}
SendPacket(&data);
}
void WorldSession::HandleInspectHonorStatsOpcode(WorldPacket& recv_data)
{
ObjectGuid guid;
recv_data >> guid;
Player* player = sObjectMgr.GetPlayer(guid);
if (!player)
{
sLog.outError("InspectHonorStats: WTF, player not found...");
return;
}
WorldPacket data(MSG_INSPECT_HONOR_STATS, 8 + 1 + 4 * 4);
data << player->GetObjectGuid();
data << uint8(player->GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY));
data << uint32(player->GetUInt32Value(PLAYER_FIELD_KILLS));
data << uint32(player->GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
data << uint32(player->GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION));
data << uint32(player->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS));
SendPacket(&data);
}
void WorldSession::HandleWorldTeleportOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_WORLD_TELEPORT from %s", GetPlayer()->GetGuidStr().c_str());
// write in client console: worldport 469 452 6454 2536 180 or /console worldport 469 452 6454 2536 180
// Received opcode CMSG_WORLD_TELEPORT
// Time is ***, map=469, x=452.000000, y=6454.000000, z=2536.000000, orient=3.141593
uint32 time;
uint32 mapid;
float PositionX;
float PositionY;
float PositionZ;
float Orientation;
recv_data >> time; // time in m.sec.
recv_data >> mapid;
recv_data >> PositionX;
recv_data >> PositionY;
recv_data >> PositionZ;
recv_data >> Orientation; // o (3.141593 = 180 degrees)
// DEBUG_LOG("Received opcode CMSG_WORLD_TELEPORT");
if (GetPlayer()->IsTaxiFlying())
{
DEBUG_LOG("Player '%s' (GUID: %u) in flight, ignore worldport command.", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow());
return;
}
DEBUG_LOG("Time %u sec, map=%u, x=%f, y=%f, z=%f, orient=%f", time / 1000, mapid, PositionX, PositionY, PositionZ, Orientation);
if (GetSecurity() >= SEC_ADMINISTRATOR)
GetPlayer()->TeleportTo(mapid, PositionX, PositionY, PositionZ, Orientation);
else
SendNotification(LANG_YOU_NOT_HAVE_PERMISSION);
}
void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_WHOIS");
std::string charname;
recv_data >> charname;
if (GetSecurity() < SEC_ADMINISTRATOR)
{
SendNotification(LANG_YOU_NOT_HAVE_PERMISSION);
return;
}
if (charname.empty() || !normalizePlayerName(charname))
{
SendNotification(LANG_NEED_CHARACTER_NAME);
return;
}
Player* plr = sObjectMgr.GetPlayer(charname.c_str());
if (!plr)
{
SendNotification(LANG_PLAYER_NOT_EXIST_OR_OFFLINE, charname.c_str());
return;
}
uint32 accid = plr->GetSession()->GetAccountId();
QueryResult* result = LoginDatabase.PQuery("SELECT username,email,last_ip FROM account WHERE id=%u", accid);
if (!result)
{
SendNotification(LANG_ACCOUNT_FOR_PLAYER_NOT_FOUND, charname.c_str());
return;
}
Field* fields = result->Fetch();
std::string acc = fields[0].GetCppString();
if (acc.empty())
acc = "Unknown";
std::string email = fields[1].GetCppString();
if (email.empty())
email = "Unknown";
std::string lastip = fields[2].GetCppString();
if (lastip.empty())
lastip = "Unknown";
std::string msg = charname + "'s " + "account is " + acc + ", e-mail: " + email + ", last ip: " + lastip;
WorldPacket data(SMSG_WHOIS, msg.size() + 1);
data << msg;
_player->GetSession()->SendPacket(&data);
delete result;
DEBUG_LOG("Received whois command from player %s for character %s", GetPlayer()->GetName(), charname.c_str());
}
void WorldSession::HandleComplainOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_COMPLAIN");
recv_data.hexlike();
uint8 spam_type; // 0 - mail, 1 - chat
ObjectGuid spammerGuid;
uint32 unk1 = 0;
uint32 unk2 = 0;
uint32 unk3 = 0;
uint32 unk4 = 0;
std::string description = "";
recv_data >> spam_type; // unk 0x01 const, may be spam type (mail/chat)
recv_data >> spammerGuid; // player guid
switch (spam_type)
{
case 0:
recv_data >> unk1; // const 0
recv_data >> unk2; // probably mail id
recv_data >> unk3; // const 0
break;
case 1:
recv_data >> unk1; // probably language
recv_data >> unk2; // message type?
recv_data >> unk3; // probably channel id
recv_data >> unk4; // unk random value
recv_data >> description; // spam description string (messagetype, channel name, player name, message)
break;
}
// NOTE: all chat messages from this spammer automatically ignored by spam reporter until logout in case chat spam.
// if it's mail spam - ALL mails from this spammer automatically removed by client
// Complaint Received message
WorldPacket data(SMSG_COMPLAIN_RESULT, 1);
data << uint8(0);
SendPacket(&data);
DEBUG_LOG("REPORT SPAM: type %u, spammer %s, unk1 %u, unk2 %u, unk3 %u, unk4 %u, message %s", spam_type, spammerGuid.GetString().c_str(), unk1, unk2, unk3, unk4, description.c_str());
}
void WorldSession::HandleRealmSplitOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_REALM_SPLIT");
uint32 unk;
std::string split_date = "01/01/01";
recv_data >> unk;
WorldPacket data(SMSG_REALM_SPLIT, 4 + 4 + split_date.size() + 1);
data << unk;
data << uint32(0x00000000); // realm split state
// split states:
// 0x0 realm normal
// 0x1 realm split
// 0x2 realm split pending
data << split_date;
SendPacket(&data);
// DEBUG_LOG("response sent %u", unk);
}
void WorldSession::HandleFarSightOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_FAR_SIGHT");
// recv_data.hexlike();
uint8 op;
recv_data >> op;
WorldObject* obj = _player->GetMap()->GetWorldObject(_player->GetFarSightGuid());
if (!obj)
return;
switch (op)
{
case 0:
DEBUG_LOG("Removed FarSight from %s", _player->GetGuidStr().c_str());
_player->GetCamera().ResetView(false);
break;
case 1:
DEBUG_LOG("Added FarSight %s to %s", _player->GetFarSightGuid().GetString().c_str(), _player->GetGuidStr().c_str());
_player->GetCamera().SetView(obj, false);
break;
}
}
void WorldSession::HandleSetTitleOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode CMSG_SET_TITLE");
int32 title;
recv_data >> title;
// -1 at none
if (title > 0 && title < MAX_TITLE_INDEX)
{
if (!GetPlayer()->HasTitle(title))
return;
}
else
title = 0;
GetPlayer()->SetUInt32Value(PLAYER_CHOSEN_TITLE, title);
}
void WorldSession::HandleTimeSyncResp(WorldPacket& recv_data)
{
uint32 counter, clientTicks;
recv_data >> counter >> clientTicks;
DEBUG_LOG("WORLD: Received opcode CMSG_TIME_SYNC_RESP: counter %u, client ticks %u, time since last sync %u", counter, clientTicks, clientTicks - _player->m_timeSyncClient);
if (counter != _player->m_timeSyncCounter - 1)
DEBUG_LOG(" WORLD: Opcode CMSG_TIME_SYNC_RESP -- Wrong time sync counter from %s (cheater?)", _player->GetGuidStr().c_str());
uint32 ourTicks = clientTicks + (WorldTimer::getMSTime() - _player->m_timeSyncServer);
// diff should be small
DEBUG_LOG(" WORLD: Opcode CMSG_TIME_SYNC_RESP -- Our ticks: %u, diff %u, latency %u", ourTicks, ourTicks - clientTicks, GetLatency());
_player->m_timeSyncClient = clientTicks;
}
void WorldSession::HandleResetInstancesOpcode(WorldPacket& /*recv_data*/)
{
DEBUG_LOG("WORLD: Received opcode CMSG_RESET_INSTANCES");
if (Group* pGroup = _player->GetGroup())
{
if (pGroup->IsLeader(_player->GetObjectGuid()))
pGroup->ResetInstances(INSTANCE_RESET_ALL, _player);
}
else
_player->ResetInstances(INSTANCE_RESET_ALL);
}
void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket& recv_data)
{
DEBUG_LOG("WORLD: Received opcode MSG_SET_DUNGEON_DIFFICULTY");
uint32 mode;
recv_data >> mode;
if (mode >= MAX_DIFFICULTY)
{
sLog.outError("WorldSession::HandleSetDungeonDifficultyOpcode: player %d sent an invalid instance mode %d!", _player->GetGUIDLow(), mode);
return;
}
if (Difficulty(mode) == _player->GetDifficulty())
return;
// cannot reset while in an instance
Map* map = _player->GetMap();
if (map && map->IsDungeon())
{
sLog.outError("WorldSession::HandleSetDungeonDifficultyOpcode: player %d tried to reset the instance while inside!", _player->GetGUIDLow());
return;
}
// Exception to set mode to normal for low-level players
if (_player->getLevel() < LEVELREQUIREMENT_HEROIC && mode > REGULAR_DIFFICULTY)
return;
if (Group* pGroup = _player->GetGroup())
{
if (pGroup->IsLeader(_player->GetObjectGuid()))
{
// the difficulty is set even if the instances can't be reset
//_player->SendDungeonDifficulty(true);
pGroup->ResetInstances(INSTANCE_RESET_CHANGE_DIFFICULTY, _player);
pGroup->SetDifficulty(Difficulty(mode));
}
}
else
{
_player->ResetInstances(INSTANCE_RESET_CHANGE_DIFFICULTY);
_player->SetDifficulty(Difficulty(mode));
}
}
void WorldSession::HandleCancelMountAuraOpcode(WorldPacket & /*recv_data*/)
{
DEBUG_LOG("WORLD: Received opcode CMSG_CANCEL_MOUNT_AURA");
// If player is not mounted, so go out :)
if (!_player->IsMounted()) // not blizz like; no any messages on blizz
{
ChatHandler(this).SendSysMessage(LANG_CHAR_NON_MOUNTED);
return;
}
if (_player->IsTaxiFlying()) // not blizz like; no any messages on blizz
{
ChatHandler(this).SendSysMessage(LANG_YOU_IN_FLIGHT);
return;
}
_player->Unmount(_player->HasAuraType(SPELL_AURA_MOUNTED));
_player->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
}
void WorldSession::HandleMoveSetCanFlyAckOpcode(WorldPacket& recv_data)
{
// fly mode on/off
DEBUG_LOG("WORLD: Received opcode CMSG_MOVE_SET_CAN_FLY_ACK");
// recv_data.hexlike();
MovementInfo movementInfo;
recv_data >> Unused<uint64>(); // guid
recv_data >> Unused<uint32>(); // unk
recv_data >> movementInfo;
recv_data >> Unused<uint32>(); // unk2
_player->m_movementInfo.SetMovementFlags(movementInfo.GetMovementFlags());
}
void WorldSession::HandleRequestPetInfoOpcode(WorldPacket & /*recv_data */)
{
/*
DEBUG_LOG("WORLD: Received opcode CMSG_REQUEST_PET_INFO");
recv_data.hexlike();
*/
}
void WorldSession::HandleSetTaxiBenchmarkOpcode(WorldPacket& recv_data)
{
uint8 mode;
recv_data >> mode;
DEBUG_LOG("Client used \"/timetest %d\" command", mode);
}
| blizzlikegroup/blizzlikecore | src/game/MiscHandler.cpp | C++ | gpl-3.0 | 47,414 |
package org.esa.beam.statistics;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.framework.gpf.OperatorException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class StatisticsOpTest_ValidateInputTest {
private StatisticsOp statisticsOp;
@Before
public void setUp() throws Exception {
statisticsOp = new StatisticsOp();
statisticsOp.setParameterDefaultValues();
statisticsOp.startDate = ProductData.UTC.parse("2010-01-31 14:45:23", "yyyy-MM-ss hh:mm:ss");
statisticsOp.endDate = ProductData.UTC.parse("2010-01-31 14:46:23", "yyyy-MM-ss hh:mm:ss");
statisticsOp.accuracy = 0;
statisticsOp.sourceProducts = new Product[]{TestUtil.getTestProduct()};
}
@After
public void tearDown() throws Exception {
}
@Test
public void testValidation_PrecisionLessThanMinPrecision() {
statisticsOp.accuracy = -1;
try {
statisticsOp.validateInput();
fail();
} catch (OperatorException expected) {
assertEquals("Parameter 'accuracy' must be greater than or equal to 0", expected.getMessage());
}
}
@Test
public void testValidation_PrecisionGreaterThanMaxPrecision() {
statisticsOp.accuracy = 7;
try {
statisticsOp.validateInput();
fail();
} catch (OperatorException expected) {
assertEquals("Parameter 'accuracy' must be less than or equal to 6", expected.getMessage());
}
}
@Test
public void testStartDateHasToBeBeforeEndDate() throws Exception {
statisticsOp.startDate = ProductData.UTC.parse("2010-01-31 14:46:23", "yyyy-MM-ss hh:mm:ss");
statisticsOp.endDate = ProductData.UTC.parse("2010-01-31 14:45:23", "yyyy-MM-ss hh:mm:ss");
try {
statisticsOp.validateInput();
fail();
} catch (OperatorException expected) {
assertTrue(expected.getMessage().contains("before start date"));
}
}
@Test
public void testSourceProductsMustBeGiven() {
statisticsOp.sourceProducts = null;
try {
statisticsOp.validateInput();
fail();
} catch (OperatorException expected) {
assertTrue(expected.getMessage().contains("must be given"));
}
statisticsOp.sourceProducts = new Product[0];
try {
statisticsOp.validateInput();
fail();
} catch (OperatorException expected) {
assertTrue(expected.getMessage().contains("must be given"));
}
}
@Test
public void testInvalidBandConfiguration() throws IOException {
final BandConfiguration configuration = new BandConfiguration();
statisticsOp.bandConfigurations = new BandConfiguration[]{configuration};
try {
statisticsOp.validateInput();
fail();
} catch (OperatorException expected) {
assertTrue(expected.getMessage().contains("must contain either a source band name or an expression"));
}
configuration.expression = "algal_2 * PI";
configuration.sourceBandName = "bandname";
try {
statisticsOp.validateInput();
fail();
} catch (OperatorException expected) {
assertTrue(expected.getMessage().contains("must contain either a source band name or an expression"));
}
}
@Test
public void testValidBandConfiguration() throws IOException {
final BandConfiguration configuration = new BandConfiguration();
statisticsOp.bandConfigurations = new BandConfiguration[]{configuration};
configuration.expression = "algal_2 * PI";
statisticsOp.validateInput();
configuration.expression = null;
configuration.sourceBandName = "bandname";
statisticsOp.validateInput();
}
}
| bcdev/beam | beam-statistics-op/src/test/java/org/esa/beam/statistics/StatisticsOpTest_ValidateInputTest.java | Java | gpl-3.0 | 4,051 |
/* Copyright (c) 2012-2015 Todd Freed <todd.freed@gmail.com>
This file is part of fab.
fab 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.
fab 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 fab. If not, see <http://www.gnu.org/licenses/>. */
#ifndef _ARRAY_INTERNAL_H
#define _ARRAY_INTERNAL_H
/*
MODULE
array.internal
*/
#include "types.h"
#include "xapi.h"
#include "array.h"
#include "macros.h"
struct array_t;
typedef struct ar_operations {
/// compare_items
//
// SUMMARY
// compare items
//
int (*compare_items)(const struct array_t * ht, const void * a, const void * b, int (*cmp_fn)(const void *, size_t, const void *, size_t))
__attribute__((nonnull(1, 2, 3)));
/// destroy_item
//
// SUMMARY
// called when an item is destroyed (in array_destroy)
//
// PARAMETRS
// ht - array
// item - item
//
xapi (*destroy_item)(const struct array_t * ht, void * item);
/// store_item
//
// SUMMARY
// called when an item is stored in a bucket
//
// PARAMETRS
// ht - array
// dst - pointer to storage within a bucket of size ht->esz
// item - pointer to the item to store
//
xapi (*store_items)(const struct array_t * ht, void * dst, void * items, size_t len);
} ar_operations;
typedef struct array_t {
union {
array arx;
struct {
size_t size;
};
};
char * v; // storage
size_t a; // allocated size in items
size_t esz; // item size, for primary storage
// implementation
ar_operations * ops;
// user operations
int (*cmp_fn)(const void * A, size_t Asz, const void * B, size_t Bsz);
void (*init_fn)(void * item);
xapi (*xinit_fn)(void * item);
void (*destroy_fn)(void * item);
xapi (*xdestroy_fn)(void * item);
} array_t;
STATIC_ASSERT(offsetof(array, size) == offsetof(array_t, size));
/// array_init
//
// SUMMARY
// initialize an already allocated array
//
xapi array_init(
array_t * restrict ar
, size_t esz
, size_t capacity
, ar_operations * restrict ops
, int (*cmp_fn)(const void * A, size_t Asz, const void * B, size_t Bsz)
)
__attribute__((nonnull(1, 4)));
/// array_destroy
//
// SUMMARY
//
//
xapi array_xdestroy(array_t * restrict ar)
__attribute__((nonnull));
/// array_put
//
// SUMMARY
// add elements to the array
//
// PARAMETERS
// li - array
// index - 0 <= index <= array_size(li)
// len - number of elements to add
// [rv] - (returns) pointers to elements
//
xapi array_put(array * const restrict li, size_t index, size_t len, void * restrict rv)
__attribute__((nonnull(1)));
/// array_destroy_range
//
// SUMMARY
// free a range of elements in a array
//
// PARAMETERS
// ar - pointer to array
// start - index of the first element
// len - number of elements
//
xapi array_destroy_range(array_t * const restrict ar, size_t start, size_t len)
__attribute__((nonnull(1)));
/// array_store
//
// SUMMARY
// overwrite elements in the array
//
void array_store(array_t * const restrict ar, size_t index, size_t len, void * restrict items, void ** const restrict rv)
__attribute__((nonnull(1)));
#endif
| hossbeast/fab | libvalyria/array/array.internal.h | C | gpl-3.0 | 3,587 |
"""Address model tests."""
from core.models import Address
from core.factory import AddressFactory
from tests.utils import ModelTestCase
class AddressTest(ModelTestCase):
"""Test the Address model."""
model = Address
field_tests = {
'line1': {
'verbose_name': 'ligne 1',
'blank': False,
'max_length': 300,
},
'line2': {
'verbose_name': 'ligne 2',
'max_length': 300,
'blank': True,
'default': '',
},
'post_code': {
'verbose_name': 'code postal',
'blank': False,
'max_length': 20,
},
'city': {
'verbose_name': 'ville',
'blank': False,
'max_length': 100,
},
'country': {
'verbose_name': 'pays',
'blank': False,
'default': 'FR',
},
}
model_tests = {
'verbose_name': 'adresse',
}
@classmethod
def setUpTestData(cls):
cls.obj = AddressFactory.create(
line1='3 Rue Joliot Curie',
post_code='91190',
city='Gif-sur-Yvette',
)
def test_str(self):
expected = '3 Rue Joliot Curie, 91190 Gif-sur-Yvette, France'
self.assertEqual(expected, str(self.obj))
| oser-cs/oser-website | tests/test_core/test_address.py | Python | gpl-3.0 | 1,331 |
#!/bin/bash
if [ $# -eq 0 ] ; then
echo "usage: clean_slave.sh <hadoop_dir_disk1> [<hadoop_dir_disk2> ...]"
exit 0
fi
YARN_DIRS=
DATANODE_DIRS=
while [ $# -gt 0 ] ; do
YARN_DIRS="${YARN_DIRS} $1/mapred/local $1/yarn/local"
DATANODE_DIRS="${DATANODE_DIRS} $1/dfs/dn $1/hdfs/data"
shift
done
# Yarn directories
rm -rf ${YARN_DIRS}
# DataNode directories
rm -rf ${DATANODE_DIRS}
| hypertable/hadoop-install | cdh3/bin/clean_slave.sh | Shell | gpl-3.0 | 400 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div class="SRResult" id="SR_threshold_5fpress_5fsensor0">
<div class="SREntry">
<a id="Item0" onkeydown="return searchResults.Nav(event,0)" onkeypress="return searchResults.Nav(event,0)" onkeyup="return searchResults.Nav(event,0)" class="SRSymbol" href="../group___configuration.html#ga8c11f6ba7531c370675de59c8298c63f" target="basefrm">THRESHOLD_PRESS_SENSOR0</a>
<span class="SRScope">mTouch_documentation.h</span>
</div>
</div>
<div class="SRResult" id="SR_timeout">
<div class="SREntry">
<a id="Item1" onkeydown="return searchResults.Nav(event,1)" onkeypress="return searchResults.Nav(event,1)" onkeyup="return searchResults.Nav(event,1)" class="SRSymbol" href="../structm_touch___sensor_variables.html#a7bd15b1b4bbdd7329986c9c4af33d10d" target="basefrm">timeout</a>
<span class="SRScope">mTouch_SensorVariables</span>
</div>
</div>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| artnavsegda/picnavsegda | docs/Help v2013-06-15/mTouch CVD Help Content/html/search/all_74.html | HTML | gpl-3.0 | 1,664 |
Bitrix 16.5 Business Demo = 4f8878c3abeabd565a0e39f95464e559
| gohdan/DFC | known_files/hashes/bitrix/modules/sale/install/gadgets/bitrix/admin_orders_graph/lang/en/index.php | PHP | gpl-3.0 | 61 |
# Wopo
Web app for creating portfolios.
### Instalation
* `git clone https://github.com/mertindervish/wopo-back-end.git`
* Change into the new directory
* Create `.env` with variables from `.env.example`
* `npm install`
## Running / Development
* `npm run dev`
* Visit app at [http://localhost:3333](http://localhost:3333). | mertindervish/wopo-back-end | README.md | Markdown | gpl-3.0 | 328 |
use std::fs::File;
use std::io::prelude::*;
use png::errors::PNGError;
use super::chunk::{Chunk, ChunkBuilder};
pub struct ChunkIterator<'a> {
parser: &'a PNGParser<'a>,
}
impl<'a> Iterator for ChunkIterator<'a> {
type Item = Chunk;
fn next (&mut self) -> Option<Chunk> {
self.parser.read_chunk().ok()
}
}
pub struct PNGParser<'a> {
pub source: &'a mut File,
}
impl<'a> PNGParser<'a> {
pub fn new(source: &'a mut File) -> Result<PNGParser, PNGError> {
let mut parser = PNGParser { source: source };
parser.check_header().map(|_| parser)
}
// should be called before any other access to the file
pub fn check_header(&mut self) -> Result<(), PNGError> {
let mut header : [u8; 8] = [0; 8];
self.source.read_exact(&mut header)
.map_err(|_| PNGError::InvalidHeader)
.and_then(|_| {
if b"\x89PNG\x0d\x0a\x1a\x0a" == &header {
Ok(())
}
else {
Err(PNGError::InvalidHeader)
}
})
}
pub fn read_chunk(&'a self) -> Result<Chunk, PNGError>{
ChunkBuilder::default()
.read_header(self.source)
.and_then(|b| b.read_data(self.source))
.map(|b| b.as_chunk())
}
pub fn iter_chunks(&'a self) -> ChunkIterator {
ChunkIterator { parser: self }
}
}
| etandel/p2j | src/png/parsing/parser.rs | Rust | gpl-3.0 | 1,453 |
# Copyright © 2013, 2015, 2016, 2017, 2018, 2020, 2022 Tom Most <twm@freecog.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 3 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, see <http://www.gnu.org/licenses/>.
#
# Additional permission under GNU GPL version 3 section 7
#
# If you modify this Program, or any covered work, by linking or
# combining it with OpenSSL (or a modified version of that library),
# containing parts covered by the terms of the OpenSSL License, the
# licensors of this Program grant you additional permission to convey
# the resulting work. Corresponding Source for a non-source form of
# such a combination shall include the source code for the parts of
# OpenSSL used as well as that of the covered work.
"""
Yarrharr production server via Twisted Web
"""
import io
import json
import logging
import os
import re
import sys
from base64 import b64encode
import attr
from django.conf import settings
from django.dispatch import receiver
from twisted.internet import defer
from twisted.internet.endpoints import serverFromString
from twisted.logger import (
FileLogObserver,
FilteringLogObserver,
ILogFilterPredicate,
Logger,
LogLevel,
PredicateResult,
formatEvent,
globalLogBeginner,
globalLogPublisher,
)
from twisted.python.filepath import FilePath
from twisted.web.resource import ErrorPage, NoResource, Resource
from twisted.web.server import Site
from twisted.web.static import File
from twisted.web.wsgi import WSGIResource
from zope.interface import implementer
from . import __version__
from .signals import schedule_changed
from .wsgi import application
log = Logger()
@attr.s
class CSPReport(object):
url = attr.ib()
referrer = attr.ib()
resource = attr.ib()
violatedDirective = attr.ib()
effectiveDirective = attr.ib()
source = attr.ib()
sample = attr.ib()
status = attr.ib()
policy = attr.ib()
disposition = attr.ib()
def __str__(self):
bits = []
for a in attr.fields(self.__class__):
value = getattr(self, a.name)
if value is None:
continue
bits.append("{}={!r}".format(a.name, value))
return "\n".join(bits)
@classmethod
def fromJSON(cls, data):
"""
Construct a :class:`CSPReport` from the serialization of a violation
per CSP Level 3 §5.3.
"""
if {"source-file", "line-number", "column-number"} <= data.keys():
source = "{source-file} {line-number}:{column-number}".format_map(data)
elif {"source-file", "line-number"} <= data.keys():
source = "{source-file} {line-number}".format_map(data)
else:
source = data.get("source-file")
return cls(
url=data["document-uri"],
referrer=data["referrer"] or None, # Always seems to be an empty string.
resource=data["blocked-uri"],
violatedDirective=data.get("violated-directive"),
effectiveDirective=data.get("effective-directive"),
policy=data["original-policy"],
disposition=data.get("disposition"),
status=data.get("status-code"),
sample=data.get("script-sample") or None,
source=source,
)
class CSPReportLogger(Resource):
isLeaf = True
_log = Logger()
def render(self, request):
if request.method != b"POST":
request.setResponseCode(405)
request.setHeader("Allow", "POST")
return b"HTTP 405: Method Not Allowed\n"
if request.requestHeaders.getRawHeaders("Content-Type") != ["application/csp-report"]:
request.setResponseCode(415)
return b"HTTP 415: Only application/csp-report requests are accepted\n"
# Process the JSON text produced per
# https://w3c.github.io/webappsec-csp/#deprecated-serialize-violation
report = CSPReport.fromJSON(json.load(io.TextIOWrapper(request.content, encoding="utf-8"))["csp-report"])
if report.sample and report.sample.startswith(";(function installGlobalHook(window) {"):
# This seems to be a misbehavior in some Firefox extension.
# I cannot reproduce it with a clean profile.
return b""
if report.sample and report.sample == "call to eval() or related function blocked by CSP":
# This is caused by Tridactyl due to a Firefox issue. It's quite
# chatty so we'll disable for now, even though the message is
# generated by the browser and might indicate a script injection.
# See <https://github.com/cmcaine/tridactyl/issues/109> and
# <https://bugzilla.mozilla.org/show_bug.cgi?id=1267027>.
return b""
self._log.debug(
"Content Security Policy violation reported by {userAgent!r}:\n{report}",
userAgent=", ".join(request.requestHeaders.getRawHeaders("User-Agent", [])),
report=report,
)
return b"" # Browser ignores the response.
class FallbackResource(Resource):
"""
Resource which falls back to an alternative resource tree if it doesn't
have a matching child resource.
"""
def __init__(self, fallback):
Resource.__init__(self)
self.fallback = fallback
def render(self, request):
"""
Render this path with the fallback resource.
"""
return self.fallback.render(request)
def getChild(self, path, request):
"""
Dispatch unhandled requests to the fallback resource.
"""
# Mutate the request path such that it's like FallbackResource didn't handle
# the request at all. This is a bit of a nasty hack, since we're
# relying on the t.w.server implementation's behavior to not break when
# we do this. A better way would be to create a wrapper for the request object
request.postpath.insert(0, request.prepath.pop())
return self.fallback
class Static(Resource):
"""
Serve up Yarrharr's static assets directory. The files in this directory
have names like::
In development, the files are served uncompressed and named like so::
main-afffb00fd22ca3ce0250.js
The second dot-delimited section is a hash of the file's contents or source
material. As the filename changes each time the content does, these files
are served with a long max-age and the ``immutable`` flag in the
`Cache-Control`_ header.
In production, each file has two pre-compressed variants: one with
a ``.gz`` extension, and one with a ``.br`` extension. For example::
main-afffb00fd22ca3ce0250.js
main-afffb00fd22ca3ce0250.js.br
main-afffb00fd22ca3ce0250.js.gz
The actual serving of the files is done by `twisted.web.static.File`, which
is fancy and supports range requests, conditional gets, etc.
.. note::
Several features used here are only available to HTTPS origins.
Cache-Control: immutable and Brotli compression both are in Firefox.
.. _cache-control: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
"""
_dir = FilePath(settings.STATIC_ROOT)
_validName = re.compile(rb"^[a-zA-Z0-9]+-[a-zA-Z0-9]+(\.[a-z]+)+$")
# NOTE: RFC 7231 § 5.3.4 is not completely clear about whether
# content-coding tokens are case-sensitive or not. The "identity" token
# appears in EBNF and is therefore definitely case-insensitive, but the
# other tokens only appear in IANA registry tables in lowercase form. In
# contrast, the transfer-coding possibilities are clearly defined in EBNF
# so are definitely case-insensitive. For content-coding every implementer
# seems to agree on lowercase, so I'm not going to worry about it.
_brToken = re.compile(rb"(:?^|[\s,])br(:?$|[\s,;])")
_gzToken = re.compile(rb"(:?^|[\s,])(:?x-)?gzip(:?$|[\s,;])")
_contentTypes = {
b".js": "application/javascript",
b".css": "text/css",
b".map": "application/octet-stream",
b".ico": "image/x-icon",
b".svg": "image/svg+xml",
b".png": "image/png",
}
def _file(self, path, type, encoding=None):
"""
Construct a `twisted.web.static.File` customized to serve Yarrharr
static assets.
:param path: `twisted.internet.filepath.FilePath` instance
:returns: `twisted.web.resource.IResource`
"""
f = File(path.path)
f.type = type
f.encoding = encoding
return f
def getChild(self, path, request):
"""
Serve a file for the given path.
The Content-Type header is set based on the file extension.
A limited form of content negotiation is done based on the
Accept-Encoding header and the files on disk. Apart from the default of
``identity``, two encodings are supported:
* ``br``, which selects any Brotli-compressed ``.br`` variant of
the file.
* ``gzip``, which selects any gzip-compressed ``.br`` variant of the
file. ``x-gzip`` is also supported.
qvalues are ignored as browsers don't use them. This may produce an
incorrect response if a variant is disabled like ``identity;q=0``.
"""
if not self._validName.match(path):
return NoResource("Not found.")
ext = path[path.rindex(b".") :]
try:
type = self._contentTypes[ext]
except KeyError:
return NoResource("Unknown type.")
acceptEncoding = request.getHeader(b"accept-encoding") or b"*"
file = None
if self._brToken.search(acceptEncoding):
br = self._dir.child(path + b".br")
if br.isfile():
file = self._file(br, type, "br")
if file is None and self._gzToken.search(acceptEncoding):
gz = self._dir.child(path + b".gz")
if gz.isfile():
file = self._file(gz, type, "gzip")
if file is None:
file = self._file(self._dir.child(path), type)
request.setHeader(b"Vary", b"accept-encoding")
request.setHeader(b"Cache-Control", b"public, max-age=31536000, immutable")
return file
class Root(FallbackResource):
"""
Root of the Yarrharr URL hierarchy.
"""
def __init__(self, reactor, threadpool):
wsgi = WSGIResource(reactor, threadpool, application)
FallbackResource.__init__(self, wsgi)
self.putChild(b"csp-report", CSPReportLogger())
self.putChild(b"static", Static())
# Handle requests for /favicon.ico and paths hit by script kiddies at
# the Twisted level so that they don't make it down to Django, which
# logs 404s as errors:
a404 = ErrorPage(404, "Not Found", "")
for path in (b"favicon.ico", b"index.php", b"wp-login.php"):
self.putChild(path, a404)
def getChildWithDefault(self, name, request):
# Disable the Referer header in some browsers. This is complemented by
# the injection of rel="noopener noreferrer" on all links by the HTML
# sanitizer.
request.setHeader(b"Referrer-Policy", b"same-origin")
request.setHeader(b"X-Content-Type-Options", b"nosniff")
request.setHeader(b"Cross-Origin-Opener-Policy", b"same-origin")
script_nonce = b64encode(os.urandom(32))
request.requestHeaders.setRawHeaders(b"Yarrharr-Script-Nonce", [script_nonce])
request.setHeader(
b"Content-Security-Policy",
(
# b"default-src 'none'; "
b"img-src *; "
b"script-src 'self' 'nonce-%s'; "
b"style-src 'self'; "
b"frame-ancestors 'none'; "
b"form-action 'self'; "
b"report-uri /csp-report"
)
% (script_nonce,),
)
return super().getChildWithDefault(name, request)
def updateFeeds(reactor, max_fetch=5):
"""
Poll any feeds due for a check.
"""
from .fetch import poll
def _failed(reason):
"""
Log unexpected errors and schedule a retry in one second.
"""
log.failure("Unexpected failure polling feeds", failure=reason)
return 1.0 # seconds until next poll
d = poll(reactor, max_fetch)
# Last gasp error handler to avoid terminating the LoopingCall.
d.addErrback(_failed)
return d
_txLevelToPriority = {
LogLevel.debug: "<7>",
LogLevel.info: "<6>",
LogLevel.warn: "<4>",
LogLevel.error: "<3>",
LogLevel.critical: "<2>",
}
def formatForSystemd(event):
# Events generated by twisted.python.log have a "system", while ones
# generated with twisted.logger have a "namespace" with similar
# meaning.
#
s = "[{}] ".format(event.get("log_system") or event.get("log_namespace") or "-")
s += formatEvent(event)
if not s:
return None
if "log_failure" in event:
try:
s += "\n" + event["log_failure"].getTraceback().rstrip("\n")
except: # noqa
pass
prefix = _txLevelToPriority.get(event.get("log_level")) or "<6>"
return prefix + s.replace("\n", "\n" + prefix + " ") + "\n"
@implementer(ILogFilterPredicate)
def dropUnhandledHTTP2Shutdown(event):
"""
Suppress the log messages which result from an unhandled error in HTTP/2
connection shutdown. See #282 and Twisted #9462.
This log message is relayed from the :mod:`twisted.python.log` so the
fields are a little odd:
* ``'log_namespace'`` is ``'log_legacy'``, and there is a ``'system'``
field with a value of ``'-'``.
* ``'log_text'`` contains the actual log text, including a pre-formatted
traceback.
* ``'failure'`` used instead of ``'log_failure'``.
"""
if event.get("log_namespace") != "log_legacy":
return PredicateResult.maybe
if event.get("log_level") != LogLevel.critical:
return PredicateResult.maybe
if "failure" not in event or not event["failure"].check(AttributeError):
return PredicateResult.maybe
if event["log_text"].startswith("Unhandled Error") and "no attribute 'shutdown'" in event["log_text"]:
return PredicateResult.no
return PredicateResult.maybe
class TwistedLoggerLogHandler(logging.Handler):
publisher = globalLogPublisher
def _mapLevel(self, levelno):
"""
Convert a stdlib logging level into a Twisted :class:`LogLevel`.
"""
if levelno <= logging.DEBUG:
return LogLevel.debug
elif levelno <= logging.INFO:
return LogLevel.info
elif levelno <= logging.WARNING:
return LogLevel.warn
elif levelno <= logging.ERROR:
return LogLevel.error
return LogLevel.critical
def emit(self, record):
self.publisher(
{
"log_level": self._mapLevel(record.levelno),
"log_namespace": record.name,
"log_format": "{msg}",
"msg": self.format(record),
}
)
class AdaptiveLoopingCall(object):
"""
:class:`AdaptiveLoopingCall` invokes a function periodically. Each time it
is called it returns the time to wait until the next invocation.
:ivar _clock: :class:`IReactorTime` implementer
:ivar _f: The function to call.
:ivar _deferred: Deferred returned by :meth:`.start()`.
:ivar _call: `IDelayedCall` when waiting for the next poll period.
Otherwise `None`.
:ivar bool _poked: `True` when the function should be immediately invoked
again after it completes.
:ivar bool _stopped: `True` once `stop()` has been called.
"""
_deferred = None
_call = None
_poked = False
_stopped = False
def __init__(self, clock, f):
"""
:param clock: :class:`IReactorTime` provider to use when scheduling
calls.
:param f: The function to call when the loop is started. It must return
the number of seconds to wait before calling it again, or
a deferred for the same.
"""
self._clock = clock
self._f = f
def start(self):
"""
Call the function immediately, and schedule future calls according to
its result.
:returns:
:class:`Deferred` which will succeed when :meth:`stop()` is called
and the loop cleanly exits, or fail when the function produces
a failure.
"""
assert self._deferred is None
assert self._call is None
assert not self._stopped
self._deferred = d = defer.Deferred()
self._callIt()
return d
def stop(self):
self._stopped = True
if self._call:
self._call.cancel()
self._deferred.callback(self)
def poke(self):
"""
Run the function as soon as possible: either immediately or once it has
finished any current execution. This is a no-op if the service has been
stopped. Pokes coalesce if received while the function is executing.
"""
if self._stopped or self._poked:
return
if self._call:
self._call.cancel()
self._callIt()
else:
self._poked = True
def _callIt(self):
self._call = None
d = defer.maybeDeferred(self._f)
d.addCallback(self._schedule)
d.addErrback(self._failLoop)
def _schedule(self, seconds):
"""
Schedule the next call.
"""
assert isinstance(seconds, (int, float))
if self._stopped:
d, self._deferred = self._deferred, None
d.callback(self)
elif self._poked:
self._poked = False
self._callIt()
else:
self._call = self._clock.callLater(seconds, self._callIt)
def _failLoop(self, failure):
"""
Terminate the loop due to an unhandled failure.
"""
d, self._deferred = self._deferred, None
d.errback(failure)
def run():
from twisted.internet import reactor
root = logging.getLogger()
logging.getLogger("django").setLevel(logging.INFO)
logging.raiseExceptions = settings.DEBUG
logging._srcfile = None # Disable expensive collection of location information.
root.setLevel(logging.DEBUG if settings.DEBUG else logging.INFO)
root.addHandler(TwistedLoggerLogHandler())
observer = FilteringLogObserver(
FileLogObserver(sys.stdout, formatForSystemd),
[dropUnhandledHTTP2Shutdown],
)
globalLogBeginner.beginLoggingTo([observer], redirectStandardIO=False)
log.info("Yarrharr {version} starting", version=__version__)
factory = Site(Root(reactor, reactor.getThreadPool()), logPath=None)
endpoint = serverFromString(reactor, settings.SERVER_ENDPOINT)
reactor.addSystemEventTrigger("before", "startup", endpoint.listen, factory)
updateLoop = AdaptiveLoopingCall(reactor, lambda: updateFeeds(reactor))
loopEndD = updateLoop.start()
loopEndD.addErrback(lambda f: log.failure("Polling loop broke", f))
@receiver(schedule_changed)
def threadPollNow(sender, **kwargs):
"""
When the `schedule_changed` signal is sent poke the polling loop. If it
is sleeping this will cause it to poll immediately. Otherwise this will
cause it to run the poll function immediately once it returns (running
it again protects against races).
"""
log.debug("Immediate poll triggered by {sender}", sender=sender)
reactor.callFromThread(updateLoop.poke)
def stopUpdateLoop():
updateLoop.stop()
return loopEndD
reactor.addSystemEventTrigger("before", "shutdown", stopUpdateLoop)
reactor.run()
| twm/yarrharr | yarrharr/application.py | Python | gpl-3.0 | 20,459 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Wed May 28 15:31:05 CEST 2014 -->
<title>Uses of Class nl.taico.tekkitrestrict.logging.TRForgeFilter</title>
<meta name="date" content="2014-05-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class nl.taico.tekkitrestrict.logging.TRForgeFilter";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../nl/taico/tekkitrestrict/logging/TRForgeFilter.html" title="class in nl.taico.tekkitrestrict.logging">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?nl/taico/tekkitrestrict/logging/class-use/TRForgeFilter.html" target="_top">Frames</a></li>
<li><a href="TRForgeFilter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class nl.taico.tekkitrestrict.logging.TRForgeFilter" class="title">Uses of Class<br>nl.taico.tekkitrestrict.logging.TRForgeFilter</h2>
</div>
<div class="classUseContainer">No usage of nl.taico.tekkitrestrict.logging.TRForgeFilter</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../nl/taico/tekkitrestrict/logging/TRForgeFilter.html" title="class in nl.taico.tekkitrestrict.logging">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?nl/taico/tekkitrestrict/logging/class-use/TRForgeFilter.html" target="_top">Frames</a></li>
<li><a href="TRForgeFilter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| EterniaLogic/TekkitRestrict | TekkitRestrict/doc/nl/taico/tekkitrestrict/logging/class-use/TRForgeFilter.html | HTML | gpl-3.0 | 4,356 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HighVoltz.HBRelog.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HighVoltz.HBRelog.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| aash/HBRelog | Properties/Resources.Designer.cs | C# | gpl-3.0 | 2,862 |
trainFeat=$1
blend_dir=$2
$blend_dir/tools/libsvm-3.22/svm-scale -l -1 -u 1 -s $trainFeat.range $trainFeat >$trainFeat.scale
$blend_dir/tools/libsvm-3.22/svm-train -s 3 $trainFeat.scale
| qingsongma/blend | scripts/train.sh | Shell | gpl-3.0 | 189 |
/**
* Hub Miner: a hubness-aware machine learning experimentation library.
* Copyright (C) 2014 Nenad Tomasev. Email: nenad.tomasev at gmail.com
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package util;
import data.representation.DataSet;
import data.representation.images.sift.LFeatRepresentation;
import java.util.ArrayList;
/**
* A utility class that joins several DataSet instances into one.
*
* @author Nenad Tomasev <nenad.tomasev at gmail.com>
*/
public class DataSetJoiner {
/**
* Joins an array of SIFTRepresentation instances into one.
*
* @param dsets An array of SIFTRepresentation objects.
* @return SIFTRepresentation containing all objects from all individual
* SIFTRepresentation-s in the array.
*/
public static LFeatRepresentation joinSIFTCollections(
LFeatRepresentation[] dsets) {
if (dsets == null || dsets.length == 0) {
return null;
} else {
LFeatRepresentation joinedDSet = new LFeatRepresentation(100, 10);
if (dsets[0].identifiers != null) {
DataSet[] identifiersArr = new DataSet[dsets.length];
for (int i = 0; i < dsets.length; i++) {
if (dsets[i] != null) {
identifiersArr[i] = dsets[i].getIdentifiers();
}
}
joinedDSet.setIdentifiers(DataSetJoiner.join(identifiersArr));
}
int numAllInstances = 0;
for (int i = 0; i < dsets.length; i++) {
if ((dsets[i] != null) && !dsets[i].isEmpty()) {
numAllInstances += dsets[i].data.size();
}
}
joinedDSet.data = new ArrayList<>(numAllInstances);
for (int i = 0; i < dsets.length; i++) {
if ((dsets[i] != null) && !dsets[i].isEmpty()) {
for (int j = 0; j < dsets[i].data.size(); j++) {
joinedDSet.addDataInstance(dsets[i].data.get(j));
}
}
}
return joinedDSet;
}
}
/**
* Joins an array of DataSet objects into one.
*
* @param dsets Array of DataSet objects.
* @return DataSet object that is joined from the passed array.
*/
public static DataSet join(DataSet[] dsets) {
if (dsets == null || dsets.length == 0) {
return null;
} else {
DataSet joineDSet = new DataSet();
joineDSet.fAttrNames = dsets[0].fAttrNames;
joineDSet.sAttrNames = dsets[0].sAttrNames;
joineDSet.iAttrNames = dsets[0].iAttrNames;
if (dsets[0].identifiers != null) {
DataSet[] identifiersArr = new DataSet[dsets.length];
for (int i = 0; i < dsets.length; i++) {
if (dsets[i] != null) {
identifiersArr[i] = dsets[i].getIdentifiers();
}
}
joineDSet.setIdentifiers(DataSetJoiner.join(identifiersArr));
}
int numAllInstances = 0;
for (int i = 0; i < dsets.length; i++) {
if ((dsets[i] != null) && !dsets[i].isEmpty()) {
numAllInstances += dsets[i].data.size();
}
}
joineDSet.data = new ArrayList<>(numAllInstances);
for (int i = 0; i < dsets.length; i++) {
if ((dsets[i] != null) && !dsets[i].isEmpty()) {
for (int j = 0; j < dsets[i].data.size(); j++) {
joineDSet.addDataInstance(dsets[i].data.get(j));
}
}
}
return joineDSet;
}
}
}
| datapoet/hubminer | src/main/java/util/DataSetJoiner.java | Java | gpl-3.0 | 4,361 |
/*
Copyright 2012, Bas Fagginger Auer.
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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <vector>
#include <tiny/math/vec.h>
namespace tiny
{
namespace mesh
{
struct StaticMeshVertex
{
StaticMeshVertex() :
textureCoordinate(0.0f, 0.0f),
tangent(1.0f, 0.0f, 0.0f),
normal(0.0f, 0.0f, 1.0f),
position(0.0f, 0.0f, 0.0f)
{
}
StaticMeshVertex(const vec2 &a_textureCoordinate,
const vec3 &a_tangent,
const vec3 &a_normal,
const vec3 &a_position) :
textureCoordinate(a_textureCoordinate),
tangent(a_tangent),
normal(a_normal),
position(a_position)
{
}
vec2 textureCoordinate;
vec3 tangent;
vec3 normal;
vec3 position;
};
class StaticMesh
{
public:
StaticMesh();
~StaticMesh();
static StaticMesh createCubeMesh(const float & = 1.0f);
static StaticMesh createCylinderMesh(const float & = 1.0f, const float & = 1.0f);
float getSize(const vec3 & = vec3(1.0f, 1.0f, 1.0f)) const;
std::vector<StaticMeshVertex> vertices;
std::vector<unsigned int> indices;
};
}
}
| takenu/tiny-game-engine | tiny/mesh/staticmesh.h | C | gpl-3.0 | 1,826 |
package plg.generator.engine;
/**
* This class represents a thread which execution can raise an exception. It is
* fundamental, however, to use this kind of thread in combination with a
* {@link ThreadContainer}.
*
* @author Andrea Burattin
* @param <T> the type returned by the computation of this thread
*/
public abstract class ThreadWithException<T> extends Thread {
private ThreadContainer tc = null;
private Exception thrownExeption = null;
private T computedValue = null;
/**
* This method can be used to set the thread container that will manage the
* eventual exceptions
*
* @param tc the thread container
*/
public void setErrorListener(ThreadContainer tc) {
this.tc = tc;
}
/**
* This method returns the exception thrown during the process generations
*
* @return the thrown exception, or <tt>null</tt> if no problem arose
*/
public Exception getThrownExeption() {
return thrownExeption;
}
/**
* This method returns the computed value
*
* @return
*/
public T getComputedValue() {
return computedValue;
}
/**
* This method is the actual executor of the computation
*
* @return the final result
* @throws Exception
*/
protected abstract T runWithException() throws Exception;
@Override
public void run() {
try {
computedValue = runWithException();
} catch (Exception e) {
tc.exceptionReceived(e);
thrownExeption = e;
}
}
}
| delas/plg | libPlgMaven/src/main/java/plg/generator/engine/ThreadWithException.java | Java | gpl-3.0 | 1,492 |
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* (Shared logic for modifications)
* LICENSE: See LICENSE in the top level directory
* FILE: mods/shared_logic/CClientDxFont.cpp
* PURPOSE: Custom font bucket
* DEVELOPERS: qwerty
*
*****************************************************************************/
#include <StdInc.h>
////////////////////////////////////////////////////////////////
//
// CClientDxFont::CClientDxFont
//
//
//
////////////////////////////////////////////////////////////////
CClientDxFont::CClientDxFont ( CClientManager* pManager, ElementID ID, CDxFontItem* pFontItem ) : ClassInit ( this ), CClientRenderElement ( pManager, ID )
{
SetTypeName ( "dx-font" );
m_pRenderItem = pFontItem;
}
////////////////////////////////////////////////////////////////
//
// CClientDxFont::GetD3DXFont
//
// Get D3DXFont for this custom font
//
////////////////////////////////////////////////////////////////
ID3DXFont* CClientDxFont::GetD3DXFont ( void )
{
return GetDxFontItem ()->m_pFntNormal;
}
| zneext/mtasa-blue | Client/mods/deathmatch/logic/CClientDxFont.cpp | C++ | gpl-3.0 | 1,135 |
import logging
from functools import reduce
import nanoget.utils as ut
import pandas as pd
import sys
import pysam
import re
from Bio import SeqIO
import concurrent.futures as cfutures
from itertools import repeat
def process_summary(summaryfile, **kwargs):
"""Extracting information from an albacore summary file.
Only reads which have a >0 length are returned.
The fields below may or may not exist, depending on the type of sequencing performed.
Fields 1-14 are for 1D sequencing.
Fields 1-23 for 2D sequencing.
Fields 24-27, 2-5, 22-23 for 1D^2 (1D2) sequencing
Fields 28-38 for barcoded workflows
1 filename
2 read_id
3 run_id
4 channel
5 start_time
6 duration
7 num_events
8 template_start
9 num_events_template
10 template_duration
11 num_called_template
12 sequence_length_template
13 mean_qscore_template
14 strand_score_template
15 complement_start
16 num_events_complement
17 complement_duration
18 num_called_complement
19 sequence_length_complement
20 mean_qscore_complement
21 strand_score_complement
22 sequence_length_2d
23 mean_qscore_2d
24 filename1
25 filename2
26 read_id1
27 read_id2
28 barcode_arrangement
29 barcode_score
30 barcode_full_arrangement
31 front_score
32 rear_score
33 front_begin_index
34 front_foundseq_length
35 rear_end_index
36 rear_foundseq_length
37 kit
38 variant
"""
logging.info("Nanoget: Collecting metrics from summary file {} for {} sequencing".format(
summaryfile, kwargs["readtype"]))
ut.check_existance(summaryfile)
if kwargs["readtype"] == "1D":
cols = ["channel", "start_time", "duration",
"sequence_length_template", "mean_qscore_template"]
elif kwargs["readtype"] in ["2D", "1D2"]:
cols = ["channel", "start_time", "duration", "sequence_length_2d", "mean_qscore_2d"]
if kwargs["barcoded"]:
cols.append("barcode_arrangement")
logging.info("Nanoget: Extracting metrics per barcode.")
try:
datadf = pd.read_csv(
filepath_or_buffer=summaryfile,
sep="\t",
usecols=cols,
)
except ValueError:
logging.error("Nanoget: did not find expected columns in summary file {}:\n {}".format(
summaryfile, ', '.join(cols)))
sys.exit("ERROR: expected columns in summary file {} not found:\n {}".format(
summaryfile, ', '.join(cols)))
if kwargs["barcoded"]:
datadf.columns = ["channelIDs", "time", "duration", "lengths", "quals", "barcode"]
else:
datadf.columns = ["channelIDs", "time", "duration", "lengths", "quals"]
logging.info("Nanoget: Finished collecting statistics from summary file {}".format(summaryfile))
return ut.reduce_memory_usage(datadf.loc[datadf["lengths"] != 0].copy())
def check_bam(bam, samtype="bam"):
"""Check if bam file is valid.
Bam file should:
- exists
- has an index (create if necessary)
- is sorted by coordinate
- has at least one mapped read
"""
ut.check_existance(bam)
samfile = pysam.AlignmentFile(bam, "rb")
if not samfile.has_index():
pysam.index(bam)
samfile = pysam.AlignmentFile(bam, "rb") # Need to reload the samfile after creating index
logging.info("Nanoget: No index for bam file could be found, created index.")
if not samfile.header['HD']['SO'] == 'coordinate':
logging.error("Nanoget: Bam file {} not sorted by coordinate!.".format(bam))
sys.exit("Please use a bam file sorted by coordinate.")
if samtype == "bam":
logging.info("Nanoget: Bam file {} contains {} mapped and {} unmapped reads.".format(
bam, samfile.mapped, samfile.unmapped))
if samfile.mapped == 0:
logging.error("Nanoget: Bam file {} does not contain aligned reads.".format(bam))
sys.exit("FATAL: not a single read was mapped in bam file {}".format(bam))
return samfile
def process_ubam(bam, **kwargs):
"""Extracting metrics from unaligned bam format
Extracting lengths
"""
logging.info("Nanoget: Starting to collect statistics from ubam file {}.".format(bam))
samfile = pysam.AlignmentFile(bam, "rb", check_sq=False)
if not samfile.has_index():
pysam.index(bam)
# Need to reload the samfile after creating index
samfile = pysam.AlignmentFile(bam, "rb", check_sq=False)
logging.info("Nanoget: No index for bam file could be found, created index.")
datadf = pd.DataFrame(
data=[(read.query_name, ut.ave_qual(read.query_qualities), read.query_length)
for read in samfile.fetch(until_eof=True)],
columns=["readIDs", "quals", "lengths"]) \
.dropna(axis='columns', how='all') \
.dropna(axis='index', how='any')
logging.info("Nanoget: ubam {} contains {} reads.".format(
bam, datadf["lengths"].size))
return ut.reduce_memory_usage(datadf)
def process_bam(bam, **kwargs):
"""Combines metrics from bam after extraction.
Processing function: calls pool of worker functions
to extract from a bam file the following metrics:
-lengths
-aligned lengths
-qualities
-aligned qualities
-mapping qualities
-edit distances to the reference genome scaled by read length
Returned in a pandas DataFrame
"""
logging.info("Nanoget: Starting to collect statistics from bam file {}.".format(bam))
samfile = check_bam(bam)
chromosomes = samfile.references
if len(chromosomes) > 100 or kwargs["huge"]:
logging.info("Nanoget: lots of contigs (>100) or --huge, not running in separate processes")
datadf = pd.DataFrame(
data=extract_from_bam(bam, None, kwargs["keep_supp"]),
columns=["readIDs", "quals", "aligned_quals", "lengths",
"aligned_lengths", "mapQ", "percentIdentity"]) \
.dropna(axis='columns', how='all') \
.dropna(axis='index', how='any')
else:
unit = chromosomes
with cfutures.ProcessPoolExecutor(max_workers=kwargs["threads"]) as executor:
datadf = pd.DataFrame(
data=[res for sublist in executor.map(extract_from_bam,
repeat(bam),
unit,
repeat(kwargs["keep_supp"]))
for res in sublist],
columns=["readIDs", "quals", "aligned_quals", "lengths",
"aligned_lengths", "mapQ", "percentIdentity"]) \
.dropna(axis='columns', how='all') \
.dropna(axis='index', how='any')
logging.info(f"Nanoget: bam {bam} contains {datadf['lengths'].size} primary alignments.")
return ut.reduce_memory_usage(datadf)
def process_cram(cram, **kwargs):
"""Combines metrics from cram after extraction.
Processing function: calls pool of worker functions
to extract from a cram file the following metrics:
-lengths
-aligned lengths
-qualities
-aligned qualities
-mapping qualities
-edit distances to the reference genome scaled by read length
Returned in a pandas DataFrame
"""
logging.info("Nanoget: Starting to collect statistics from cram file {}.".format(cram))
samfile = check_bam(cram, samtype="cram")
chromosomes = samfile.references
if len(chromosomes) > 100:
unit = [None]
logging.info("Nanoget: lots of contigs (>100), not running in separate processes")
else:
unit = chromosomes
with cfutures.ProcessPoolExecutor(max_workers=kwargs["threads"]) as executor:
datadf = pd.DataFrame(
data=[res for sublist in executor.map(extract_from_bam,
repeat(cram), unit, repeat(kwargs["keep_supp"]))
for res in sublist],
columns=["readIDs", "quals", "aligned_quals", "lengths",
"aligned_lengths", "mapQ", "percentIdentity"]) \
.dropna(axis='columns', how='all') \
.dropna(axis='index', how='any')
logging.info(f"Nanoget: cram {cram} contains {datadf['lengths'].size} primary alignments.")
return ut.reduce_memory_usage(datadf)
def extract_from_bam(bam, chromosome, keep_supplementary=True):
"""Extracts metrics from bam.
Worker function per chromosome
loop over a bam file and create list with tuples containing metrics:
-qualities
-aligned qualities
-lengths
-aligned lengths
-mapping qualities
-edit distances to the reference genome scaled by read length
"""
samfile = pysam.AlignmentFile(bam, "rb")
if keep_supplementary:
return [
(read.query_name,
ut.ave_qual(read.query_qualities),
ut.ave_qual(read.query_alignment_qualities),
read.query_length,
read.query_alignment_length,
read.mapping_quality,
get_pID(read))
for read in samfile.fetch(reference=chromosome, multiple_iterators=True)
if not read.is_secondary and not read.is_unmapped]
else:
return [
(read.query_name,
ut.ave_qual(read.query_qualities),
ut.ave_qual(read.query_alignment_qualities),
read.query_length,
read.query_alignment_length,
read.mapping_quality,
get_pID(read))
for read in samfile.fetch(reference=chromosome, multiple_iterators=True)
if not read.is_secondary and not read.is_unmapped and not read.is_supplementary]
def get_pID(read):
"""Return the percent identity of a read.
based on the NM tag if present,
if not calculate from MD tag and CIGAR string
read.query_alignment_length can be zero in the case of ultra long reads aligned with minimap2 -L
"""
match = reduce(lambda x, y: x + y[1] if y[0] in (0, 7, 8) else x, read.cigartuples, 0)
ins = reduce(lambda x, y: x + y[1] if y[0] == 1 else x, read.cigartuples, 0)
delt = reduce(lambda x, y: x + y[1] if y[0] == 2 else x, read.cigartuples, 0)
alignment_length = match + ins + delt
try:
return (1 - read.get_tag("NM") / alignment_length) * 100
except KeyError:
try:
return 100 * (1 - (parse_MD(read.get_tag("MD")) + parse_CIGAR(read.cigartuples)) /
alignment_length)
except KeyError:
return None
except ZeroDivisionError:
return None
def parse_MD(MDlist):
"""Parse MD string to get number of mismatches and deletions."""
return sum([len(item) for item in re.split('[0-9^]', MDlist)])
def parse_CIGAR(cigartuples):
"""Count the insertions in the read using the CIGAR string."""
return sum([item[1] for item in cigartuples if item[0] == 1])
def handle_compressed_input(inputfq, file_type="fastq"):
"""Return handles from compressed files according to extension.
Check for which fastq input is presented and open a handle accordingly
Can read from compressed files (gz, bz2, bgz) or uncompressed
Relies on file extensions to recognize compression
"""
ut.check_existance(inputfq)
if inputfq.endswith(('.gz', 'bgz')):
import gzip
logging.info("Nanoget: Decompressing gzipped {} {}".format(file_type, inputfq))
return gzip.open(inputfq, 'rt')
elif inputfq.endswith('.bz2'):
import bz2
logging.info("Nanoget: Decompressing bz2 compressed {} {}".format(file_type, inputfq))
return bz2.open(inputfq, 'rt')
elif inputfq.endswith(('.fastq', '.fq', 'fasta', '.fa', '.fas')):
return open(inputfq, 'r')
else:
logging.error("INPUT ERROR: Unrecognized file extension {}".format(inputfq))
sys.exit('INPUT ERROR:\nUnrecognized file extension in {}\n'
'Supported are gz, bz2, bgz, fastq, fq, fasta, fa and fas'.format(inputfq))
def process_fasta(fasta, **kwargs):
"""Combine metrics extracted from a fasta file."""
logging.info("Nanoget: Starting to collect statistics from a fasta file.")
inputfasta = handle_compressed_input(fasta, file_type="fasta")
return ut.reduce_memory_usage(pd.DataFrame(
data=[len(rec) for rec in SeqIO.parse(inputfasta, "fasta")],
columns=["lengths"]
).dropna())
def process_fastq_plain(fastq, **kwargs):
"""Combine metrics extracted from a fastq file."""
logging.info("Nanoget: Starting to collect statistics from plain fastq file.")
inputfastq = handle_compressed_input(fastq)
return ut.reduce_memory_usage(pd.DataFrame(
data=[res for res in extract_from_fastq(inputfastq) if res],
columns=["quals", "lengths"]
).dropna())
def extract_from_fastq(fq):
"""Extract metrics from a fastq file.
Return average quality and read length
"""
for rec in SeqIO.parse(fq, "fastq"):
yield ut.ave_qual(rec.letter_annotations["phred_quality"]), len(rec)
def stream_fastq_full(fastq, threads):
"""Generator for returning metrics extracted from fastq.
Extract from a fastq file:
-readname
-average and median quality
-read_lenght
"""
logging.info("Nanoget: Starting to collect full metrics from plain fastq file.")
inputfastq = handle_compressed_input(fastq)
with cfutures.ProcessPoolExecutor(max_workers=threads) as executor:
for results in executor.map(extract_all_from_fastq, SeqIO.parse(inputfastq, "fastq")):
yield results
logging.info("Nanoget: Finished collecting statistics from plain fastq file.")
def extract_all_from_fastq(rec):
"""Extract metrics from a fastq file.
Return identifier, read length, average quality and median quality
"""
return (rec.id,
len(rec),
ut.ave_qual(rec.letter_annotations["phred_quality"]),
None)
def info_to_dict(info):
"""Get the key-value pairs from the albacore/minknow fastq description and return dict"""
return {field.split('=')[0]: field.split('=')[1] for field in info.split(' ')[1:]}
def process_fastq_rich(fastq, **kwargs):
"""Extract metrics from a richer fastq file.
Extract information from fastq files generated by albacore or MinKNOW,
containing richer information in the header (key-value pairs)
read=<int> [72]
ch=<int> [159]
start_time=<timestamp> [2016-07-15T14:23:22Z] # UTC ISO 8601 ISO 3339 timestamp
Z indicates UTC time, T is the delimiter between date expression and time expression
dateutil.parser.parse("2016-07-15T14:23:22Z") imported as dparse
-> datetime.datetime(2016, 7, 15, 14, 23, 22, tzinfo=tzutc())
"""
logging.info("Nanoget: Starting to collect statistics from rich fastq file.")
inputfastq = handle_compressed_input(fastq)
res = []
for record in SeqIO.parse(inputfastq, "fastq"):
try:
read_info = info_to_dict(record.description)
res.append(
(ut.ave_qual(record.letter_annotations["phred_quality"]),
len(record),
read_info["ch"],
read_info["start_time"],
read_info["runid"]))
except KeyError:
logging.error("Nanoget: keyerror when processing record {}".format(record.description))
sys.exit("Unexpected fastq identifier:\n{}\n\n \
missing one or more of expected fields 'ch', 'start_time' or 'runid'".format(
record.description))
df = pd.DataFrame(
data=res,
columns=["quals", "lengths", "channelIDs", "timestamp", "runIDs"]).dropna()
df["channelIDs"] = df["channelIDs"].astype("int64")
return ut.reduce_memory_usage(df)
def readfq(fp):
"""Generator function adapted from https://github.com/lh3/readfq."""
last = None # this is a buffer keeping the last unprocessed line
while True: # mimic closure; is it a bad idea?
if not last: # the first record or a record following a fastq
for l in fp: # search for the start of the next record
if l[0] in '>@': # fasta/q header line
last = l[:-1] # save this line
break
if not last:
break
name, seqs, last = last[1:].partition(" ")[0], [], None
for l in fp: # read the sequence
if l[0] in '@+>':
last = l[:-1]
break
seqs.append(l[:-1])
if not last or last[0] != '+': # this is a fasta record
yield name, ''.join(seqs), None # yield a fasta record
if not last:
break
else: # this is a fastq record
seq, leng, seqs = ''.join(seqs), 0, []
for l in fp: # read the quality
seqs.append(l[:-1])
leng += len(l) - 1
if leng >= len(seq): # have read enough quality
last = None
yield name, seq, ''.join(seqs) # yield a fastq record
break
if last: # reach EOF before reading enough quality
yield name, seq, None # yield a fasta record instead
break
def fq_minimal(fq):
"""Minimal fastq metrics extractor.
Quickly parse a fasta/fastq file - but makes expectations on the file format
There will be dragons if unexpected format is used
Expects a fastq_rich format, but extracts only timestamp and length
"""
try:
while True:
time = next(fq)[1:].split(" ")[4][11:-1]
length = len(next(fq))
next(fq)
next(fq)
yield time, length
except StopIteration:
yield None
def process_fastq_minimal(fastq, **kwargs):
"""Swiftly extract minimal features (length and timestamp) from a rich fastq file"""
infastq = handle_compressed_input(fastq)
try:
df = pd.DataFrame(
data=[rec for rec in fq_minimal(infastq) if rec],
columns=["timestamp", "lengths"]
)
except IndexError:
logging.error("Fatal: Incorrect file structure for fastq_minimal")
sys.exit("Error: file does not match expected structure for fastq_minimal")
return ut.reduce_memory_usage(df)
| wdecoster/nanoget | nanoget/extraction_functions.py | Python | gpl-3.0 | 18,527 |
<?php
// NOTE: the query output should be passed through a variable $result
//loop thru the field names to print the correct headers
$i = 0;
if(mysql_num_rows($result)==0){
echo "<table id='table-search'><tr><td colspan='5'>There are no donations in this period.</td></tr></table>";
}
else{
echo "<table id='table-search'>";
echo "<thead><tr>";
while ($i < mysql_num_fields($result))
{
echo "<th>". mysql_field_name($result, $i) . "</th>";
$i++;
}
echo "</thead></tr>";
//display the data
$i = 1;
while ($rows = mysql_fetch_array($result,MYSQL_ASSOC))
{
echo "<tr>";
foreach ($rows as $data){echo "<td align=\"right\">".$data ."</td>";}
echo "</tr>";
$i++;
}
$totalrows=mysql_fetch_array($total);
echo "<tr style='text-align:right'><td></td><td><b>Total</b></td><td><b>$totalrows[sum]</b></td></table>";
}
?>
| rishisharan/mywork | display_table.php | PHP | gpl-3.0 | 852 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IPP.Oversea.CN.CustomerMgmt.SendRMAEveryDayList
{
/// <summary>
/// Interface of Log
/// </summary>
public interface ILog
{
/// <summary>
/// Write Log content to log file
/// </summary>
/// <param name="content"></param>
void WriteLog(string content);
/// <summary>
/// Write exception content to log file
/// </summary>
/// <param name="exception"></param>
void WriteLog(Exception exception);
}
}
| ZeroOne71/ql | 02_ECCentral/06_Job_Move/07_RMA/SendRMAEveryDayList/SendRMAEventDayList/ILog.cs | C# | gpl-3.0 | 603 |
<?php
/**
* Name:zsuper_mayi活动公告
* Date:20160608
* Version:1.0
* Description:用来显示活动公告
*/
class zsuper_mayi_widget_notice extends WP_Widget {
public function __construct() {
$widget_ops = array(
'classname' => 'zsuper_widget_notice',
'description' => __( 'zsuper_mayi活动公告' ),
'customize_selective_refresh' => true,
);
parent::__construct( 'zs_notice', __( '活动公告(zsuper)' ), $widget_ops );
}
function form( $instance ) {
$defaults = array(
'img1' => 'http://cdn.zhangsubo.cn/wp-content/themes/TBUed/images/top1.png',
'img2' => 'http://cdn.zhangsubo.cn/wp-content/themes/TBUed/images/top1.png',
'web1' => 'http://zhangsubo.cn',
'web2' => 'http://zhangsubo.cn'
);
$img1 = $instance[ 'img1' ];
$img2 = $instance[ 'img2' ];
$web1 = $instance[ 'web1' ];
$web2 = $instance[ 'web2' ];
// markup for form ?>
<p>注意:图片地址和活动地址都需要包括"http://",图片大小为270*120,圆角会更好看<br/>如有问题请联系<a href="http://zhangsubo.cn" traget="_blank">张小璋</a></p>
<p>
<label for="<?php echo $this->get_field_id( 'img1' ); ?>">活动1banner:</label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'img1' ); ?>" name="<?php echo $this->get_field_name( 'img1' ); ?>" value="<?php echo esc_attr( $img1 ); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id( 'web1' ); ?>">活动1地址:</label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'web1' ); ?>" name="<?php echo $this->get_field_name( 'web1' ); ?>" value="<?php echo esc_attr( $web1 ); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id( 'img2' ); ?>">活动2banner:</label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'img2' ); ?>" name="<?php echo $this->get_field_name( 'img2' ); ?>" value="<?php echo esc_attr( $img2 ); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id( 'web2' ); ?>">活动2地址:</label>
<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'web2' ); ?>" name="<?php echo $this->get_field_name( 'web2' ); ?>" value="<?php echo esc_attr( $web2 ); ?>">
</p>
<?
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[ 'img1' ] = strip_tags( $new_instance[ 'img1' ] );
$instance[ 'img2' ] = strip_tags( $new_instance[ 'img2' ] );
$instance[ 'web1' ] = strip_tags( $new_instance[ 'web1' ] );
$instance[ 'web2' ] = strip_tags( $new_instance[ 'web2' ] );
return $instance;
}
function widget( $args, $instance ) {
?>
<!-- 活动公告开始 -->
<div class="catalog clear">
<p>活动公告</p>
<div class="img">
<a href="<?php echo $instance['web1']; ?>"><img src="<?php echo $instance['img1']; ?>"></a>
</div>
<div class="img">
<a href="<?php echo $instance['web2']; ?>"><img src="<?php echo $instance['img2']; ?>"></a>
</div>
</div>
<!-- 活动公告结束 -->
<?php }
}
function zsuper_mayi_register__widget_notice() {
register_widget( 'zsuper_mayi_widget_notice' );
}
add_action( 'widgets_init', 'zsuper_mayi_register__widget_notice' );
?> | zhangsubo/subo3.0 | zsuper-framework/widgets/widgets-notice.php | PHP | gpl-3.0 | 3,377 |
<?php $stmt = $mysqli->prepare("SELECT textarea FROM pages WHERE categorie LIKE 'entreprise' AND nom LIKE 'rejoindre';");
$stmt->execute();
$stmt->bind_result($tarea);
$stmt->fetch();
?>
<h5 style="padding-top:6px;">Nous rejoindre</h5>
<div class="divider" style="margin-bottom:6px;"></div>
<?php echo $tarea; ?>
<?php
$stmt->free_result();
$stmt->close();
?>
<!-- TEXTE PAR DEFAUT DE TINYMCE -->
<!-- <div class="row s12 left-align">-->
<!-- <div class="col s5">-->
<!-- <b>Contact</b><br/>-->
<!-- </div>-->
<!-- <div class="col s7">-->
<!-- Madame Carole Blanchette<br/>-->
<!-- Téléphone: (418) 831-2390<br/>-->
<!-- Email: <mail>laboiteabouf@outlook.com</mail>-->
<!-- </div>-->
<!--</div>-->
<!--<div class="row s12 left-align">-->
<!-- <div class="col s5">-->
<!-- <b>Emplacement</b>-->
<!-- </div>-->
<!-- <div class="col s7">-->
<!-- 248 rue des pervenches<br/>-->
<!-- Saint-Nicolas<br/>-->
<!-- Québec, G7A 3M3<br/>-->
<!-- Canada-->
<!-- </div>-->
<!--</div>-->
| jwallet/CLL-Site-Magasin-PHP | home-contact-content.php | PHP | gpl-3.0 | 1,065 |
# test-drive-1
My first repository attempt
Did a test modification - also added a file. | ticktockdata/test-drive-1 | README.md | Markdown | gpl-3.0 | 87 |
<?php
/*
* SPIT: Simple PHP Issue Tracker
* Copyright (C) 2012 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file COPYING that should have accompanied this file.
*
* This package 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, see <http://www.gnu.org/licenses/>.
*/
namespace Spit\Models\Fields;
class Field {
public function __construct($name, $label) {
$this->name = $name;
$this->label = $label;
}
}
?>
| nbolton/spit | public/php/Spit/Models/Fields/Field.php | PHP | gpl-3.0 | 864 |
# Datascroll
Have to be updated...
| EduProArd/Datascroll | README.md | Markdown | gpl-3.0 | 35 |
/*
* Project: ImpishExploration
* Module: Placeholder_Game-Core_main
* File: GuiTextList.java
*
* Created by Tim on 11/06/17 13:54 on behalf of SmithsGaming
* Copyright (c) 2017. All rights reserved.
*
* Last modified 11/06/17 13:48
*/
package com.scoutgamestudio.placeholder.client.gui.components;
import com.scoutgamestudio.placeholder.client.Client;
import com.scoutgamestudio.placeholder.client.GameClient;
import com.scoutgamestudio.placeholder.client.gui.GuiComponent;
import com.scoutgamestudio.placeholder.client.util.MouseButtonEvent;
import com.scoutgamestudio.placeholder.client.util.MouseMoveEvent;
import com.scoutgamestudio.placeholder.common.util.GraphicUtils;
import com.scoutgamestudio.placeholder.common.util.maths.Vector2d;
import java.awt.*;
import java.util.ArrayList;
/**
* Created by Tim on 07/03/2016.
*/
public class GuiTextList extends GuiComponent implements ISliderListener {
private final ArrayList<String> textItems;
protected int height;
protected int width;
private GuiSliderVertical guiSlider;
private int itemSelected = -1;
private int maxDisplayed;
private int displayIndex = 0;
public GuiTextList(Vector2d position, ArrayList textItems, int width, int height) {
super(position);
if (textItems != null) {
this.textItems = textItems;
} else {
this.textItems = new ArrayList<>();
}
this.width = width;
this.height = height;
guiSlider = new GuiSliderVertical(0, new Vector2d(width - 17, 1), this, 15, height - 3, 0, 1);
maxDisplayed = (height - 2) / Client.getGameClient().getFontMetrics(GameClient.defaultFont).getHeight();
}
@Override
public void setOffset(Vector2d offset) {
super.setOffset(offset);
this.containedArea = new Rectangle((int) position.x + (int) offset.x, (int) position.y + (int) offset.y, width, height);
guiSlider.setOffset(new Vector2d(position.x + offset.x, position.y + offset.y));
}
@Override
public void update() {
}
@Override
public void render(Graphics g) {
g.setColor(Color.DARK_GRAY);
g.fillRect((int) position.x + (int) offset.x, (int) position.y + (int) offset.y, width, height);
g.setColor(new Color(65, 65, 65));
g.fillRect((int) position.x + (int) offset.x + 1, (int) position.y + (int) offset.y + 1, width - 2, height - 2);
g.setFont(GameClient.defaultFont);
g.setColor(Color.WHITE);
int spacing = g.getFontMetrics().getHeight();
int y = (int) this.offset.y + (int) this.position.y + spacing / 2;
if (!textItems.isEmpty()) {
for (int i = displayIndex; i < displayIndex + maxDisplayed; i++) {
if (textItems.size() > i) {
GraphicUtils.drawCenteredString(g, GraphicUtils.trimStringToLength(g, textItems.get(i), GameClient.defaultFont, width - 20), GameClient.defaultFont, (int) (position.x + width / 2), (int) position.y + y);
y += spacing;
} else {
break;
}
}
}
if (itemSelected >= 0) {
g.setColor(Color.WHITE);
g.drawRect((int) position.x + (int) offset.x + 1, (int) position.y + (int) offset.y + 1 + spacing * itemSelected, width - 20, spacing);
}
guiSlider.render(g);
}
public String getSelectedText() {
if (itemSelected >= 0) {
return textItems.get(itemSelected + displayIndex);
}
return null;
}
public void addString(String string) {
textItems.add(string);
}
@Override
public void mousePressed(MouseButtonEvent e) {
guiSlider.mousePressed(e);
}
@Override
public void mouseReleased(MouseButtonEvent e) {
guiSlider.mouseReleased(e);
}
@Override
public void mouseClicked(MouseButtonEvent e) {
guiSlider.mouseClicked(e);
if (!guiSlider.getContainedArea().contains(e.x, e.y)) {
int yRelative = e.y - (int) position.y - (int) offset.y;
int index = yRelative / Client.getGameClient().getFontMetrics(GameClient.defaultFont).getHeight();
if (index < textItems.size()) {
itemSelected = index;
}
}
}
@Override
public void mouseMoved(MouseMoveEvent e) {
guiSlider.mouseMoved(e);
}
@Override
public void mouseDragged(MouseMoveEvent e) {
guiSlider.mouseDragged(e);
}
@Override
public void sliderMoved(int id, GuiSlider slider, float amount) {
itemSelected = -1;
float itemSize = 1F / textItems.size();
if (textItems.size() > maxDisplayed) {
displayIndex = (int) (amount / itemSize);
}
}
} | Tim020/Placeholder-Game | Core/src/com/scoutgamestudio/placeholder/client/gui/components/GuiTextList.java | Java | gpl-3.0 | 4,812 |
<!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_24) on Wed May 25 20:45:32 CEST 2011 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
fspotcloud.peer.db Class Hierarchy (The Peer Bot 0.40-5.2.7 Test API)
</TITLE>
<META NAME="date" CONTENT="2011-05-25">
<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="fspotcloud.peer.db Class Hierarchy (The Peer Bot 0.40-5.2.7 Test 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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../fspotcloud/peer/package-tree.html"><B>PREV</B></A>
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?fspotcloud/peer/db/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.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>
<CENTER>
<H2>
Hierarchy For Package fspotcloud.peer.db
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL>
<LI TYPE="circle">junit.framework.Assert<UL>
<LI TYPE="circle">junit.framework.TestCase (implements junit.framework.Test)
<UL>
<LI TYPE="circle">fspotcloud.peer.db.<A HREF="../../../fspotcloud/peer/db/DataTest.html" title="class in fspotcloud.peer.db"><B>DataTest</B></A></UL>
</UL>
</UL>
</UL>
<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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../fspotcloud/peer/package-tree.html"><B>PREV</B></A>
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?fspotcloud/peer/db/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.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 © 2011. All Rights Reserved.
</BODY>
</HTML>
| slspeek/FSpotCloudSite | peer/testapidocs/fspotcloud/peer/db/package-tree.html | HTML | gpl-3.0 | 6,251 |
/**************************************************************************
* Butaca
* Copyright (C) 2011 - 2012 Simon Pena <spena@igalia.com>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
**************************************************************************/
#include "movielistmodel.h"
#include "movie.h"
#include <QDebug>
MovieListModel::MovieListModel(QObject* parent) :
QAbstractListModel(parent)
{
QHash<int, QByteArray> roles;
roles[MovieIdRole] = "id";
roles[MovieImdbIdRole] = "imdbId";
roles[MovieNameRole] = "name";
roles[MovieInfoRole] = "info";
roles[MovieTimesRole] = "showtimes";
roles[MovieDescriptionRole] = "description";
setRoleNames(roles);
}
MovieListModel::~MovieListModel()
{
}
QVariant MovieListModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid() || index.row() >= m_movies.count()) {
return QVariant();
}
const Movie& movie = m_movies.at(index.row());
switch (role) {
case MovieIdRole:
return QVariant::fromValue(movie.id());
case MovieImdbIdRole:
return QVariant::fromValue(movie.imdbId());
case MovieNameRole:
return QVariant::fromValue(movie.name());
case MovieInfoRole:
return QVariant::fromValue(movie.info());
case MovieTimesRole:
return QVariant::fromValue(movie.showtimes());
case MovieDescriptionRole:
return QVariant::fromValue(movie.description());
default:
qDebug() << Q_FUNC_INFO << "Unhandled role" << role;
return QVariant();
}
}
int MovieListModel::rowCount(const QModelIndex& index) const
{
Q_UNUSED(index)
return m_movies.count();
}
QVariantMap MovieListModel::get(const QModelIndex& index) const
{
QVariantMap mappedEntry;
if (!index.isValid() || index.row() >= m_movies.count()) {
return mappedEntry;
}
const Movie& movie = m_movies.at(index.row());
const QHash<int, QByteArray>& roles = roleNames();
mappedEntry[roles[MovieIdRole]] = movie.id();
mappedEntry[roles[MovieImdbIdRole]] = movie.imdbId();
mappedEntry[roles[MovieNameRole]] = movie.name();
mappedEntry[roles[MovieInfoRole]] = movie.info();
mappedEntry[roles[MovieTimesRole]] = movie.showtimes();
mappedEntry[roles[MovieDescriptionRole]] = movie.description();
return mappedEntry;
}
void MovieListModel::setMovieList(QList<Movie> movies)
{
if (m_movies.count() > 0) {
beginRemoveRows(QModelIndex(), 0, m_movies.count() - 1);
m_movies.clear();
endRemoveRows();
}
if (movies.count() > 0) {
beginInsertRows(QModelIndex(), 0, m_movies.count() - 1);
m_movies << movies;
endInsertRows();
}
emit countChanged();
}
| spenap/butaca | src/movielistmodel.cpp | C++ | gpl-3.0 | 3,378 |
// Copyright (c) The University of Dundee 2018-2019
// This file is part of the Research Data Management Platform (RDMP).
// RDMP 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.
// RDMP 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 RDMP. If not, see <https://www.gnu.org/licenses/>.
using MapsDirectlyToDatabaseTable;
using Rdmp.Core.Curation.Data;
using Rdmp.Core.DataFlowPipeline;
using ReusableLibraryCode.Progress;
using System;
namespace Rdmp.Core.DataExport.Data
{
/// <summary>
/// Records how far through a batch extraction a <see cref="SelectedDataSets"/> is. Also tracks which column is being
/// used for the batch splitting.
/// </summary>
public interface IExtractionProgress : IMapsDirectlyToDatabaseTable, ISaveable, INamed
{
/// <summary>
/// The absolute origin date of the dataset being extracted. This is the first day of the first batch
/// that is extracted when running a batch extraction
/// </summary>
DateTime? StartDate { get; set; }
/// <summary>
/// The absolute end date of the dataset after which there is assumed to be no data. If null then
/// the current datetime is expected
/// </summary>
DateTime? EndDate { get; set; }
/// <summary>
/// The column or transform which provides the date component of the extraction upon which
/// <see cref="StartDate"/>, <see cref="EndDate"/> etc relate
/// </summary>
int ExtractionInformation_ID { get; set; }
/// <summary>
/// When running a batch extraction this is the number of days to fetch/extract at a time
/// </summary>
int NumberOfDaysPerBatch { get; set; }
/// <summary>
/// The inclusive day at which the next batch should start at
/// </summary>
DateTime? ProgressDate { get; set; }
/// <summary>
/// The dataset as it is selected in an <see cref="ExtractionConfiguration"/> for which this class
/// documents the progress of it's batch extraction
/// </summary>
int SelectedDataSets_ID { get; set; }
/// <inheritdoc cref="SelectedDataSets_ID"/>
ISelectedDataSets SelectedDataSets { get; }
/// <inheritdoc cref="ExtractionInformation_ID"/>
ExtractionInformation ExtractionInformation { get; }
/// <summary>
/// When extraction fails, what is the policy on retrying
/// </summary>
RetryStrategy Retry { get; }
/// <summary>
/// Returns true if the progress is not completed yet
/// </summary>
/// <returns></returns>
bool MoreToFetch();
/// <summary>
/// Blocks for a suitable amount of time (if any) based on the <see cref="Retry"/>
/// strategy configured. Then returns true to retry or false to abandon retrying
/// </summary>
/// <param name="token">Cancellation token for if the user wants to abandon waiting</param>
/// <param name="listener"></param>
/// <param name="totalFailureCount"></param>
/// <param name="consecutiveFailureCount"></param>
/// <returns></returns>
bool ApplyRetryWaitStrategy(GracefulCancellationToken token, IDataLoadEventListener listener, int totalFailureCount, int consecutiveFailureCount);
}
} | HicServices/RDMP | Rdmp.Core/DataExport/Data/IExtractionProgress.cs | C# | gpl-3.0 | 3,800 |
package edu.princeton.cs.algs4.sorting;
import edu.princeton.cs.algs4.io.*;
/*************************************************************************
* Compilation: javac Insertion.java
* Execution: java Insertion < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: http://algs4.cs.princeton.edu/21sort/tiny.txt
* http://algs4.cs.princeton.edu/21sort/words3.txt
*
* Sorts a sequence of strings from standard input using insertion sort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Insertion < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java Insertion < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
*************************************************************************/
import java.util.Comparator;
/**
* The <tt>Insertion</tt> class provides static methods for sorting an
* array using insertion sort.
* <p>
* For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Insertion {
// This class should not be instantiated.
private Insertion() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {
exch(a, j, j-1);
}
assert isSorted(a, 0, i);
}
assert isSorted(a);
}
/**
* Rearranges the array in ascending order, using a comparator.
* @param a the array
* @param c the comparator specifying the order
*/
public static void sort(Object[] a, Comparator c) {
int N = a.length;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0 && less(c, a[j], a[j-1]); j--) {
exch(a, j, j-1);
}
assert isSorted(a, c, 0, i);
}
assert isSorted(a, c);
}
// return a permutation that gives the elements in a[] in ascending order
// do not change the original array a[]
/**
* Returns a permutation that gives the elements in the array in ascending order.
* @param a the array
* @return a permutation <tt>p[]</tt> such that <tt>a[p[0]]</tt>, <tt>a[p[1]]</tt>,
* ..., <tt>a[p[N-1]]</tt> are in ascending order
*/
public static int[] indexSort(Comparable[] a) {
int N = a.length;
int[] index = new int[N];
for (int i = 0; i < N; i++)
index[i] = i;
for (int i = 0; i < N; i++)
for (int j = i; j > 0 && less(a[index[j]], a[index[j-1]]); j--)
exch(index, j, j-1);
return index;
}
/***********************************************************************
* Helper sorting functions
***********************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return (v.compareTo(w) < 0);
}
// is v < w ?
private static boolean less(Comparator c, Object v, Object w) {
return (c.compare(v, w) < 0);
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
// exchange a[i] and a[j] (for indirect sort)
private static void exch(int[] a, int i, int j) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/***********************************************************************
* Check if array is sorted - useful for debugging
***********************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
// is the array sorted from a[lo] to a[hi]
private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
private static boolean isSorted(Object[] a, Comparator c) {
return isSorted(a, c, 0, a.length - 1);
}
// is the array sorted from a[lo] to a[hi]
private static boolean isSorted(Object[] a, Comparator c, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(c, a[i], a[i-1])) return false;
return true;
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; insertion sorts them;
* and prints them to standard output in ascending order.
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Insertion.sort(a);
show(a);
}
}
/*************************************************************************
* Copyright 2002-2012, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4-package.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4-package.jar 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.
*
* algs4-package.jar 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 algs4-package.jar. If not, see http://www.gnu.org/licenses.
*************************************************************************/
| bramfoo/algorithms | src/main/java/edu/princeton/cs/algs4/sorting/Insertion.java | Java | gpl-3.0 | 6,374 |
<?php
/*
* Flux Flow
* Copyright (C) 2017 Joao L. Ribeiro da Silva <joao.r.silva@gmail.com>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
namespace Fluxflow\Modules\Ff\Controllers;
use Phalcon\Http\Request as Request;
class AppactionsController extends ControllerBase
{
public $titleSinglular = "Action";
public $titlePlural = "Actions";
public function indexAction()
{
$this->tag->h3 = $this->titlePlural;
$this->tag->title = $this->tag->h3 . " | ";
$this->tag->h2 = "List of " . $this->titlePlural;
}
public function viewAction()
{
$this->tag->h3 = "View " . $this->titleSinglular;
$this->tag->title = $this->tag->h3 . " | ";
$this->tag->h2 = $this->titleSinglular;
}
public function editAction()
{
$this->tag->h3 = "Edit " . $this->titleSinglular;
$this->tag->title = $this->tag->h3 . " | ";
$this->tag->h2 = $this->titleSinglular;
}
}
| joaorsilva/fluxflow | app/modules/ff/controllers/AppactionsController.php | PHP | gpl-3.0 | 1,585 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2021 Evan Debenham
*
* 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 3 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, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.standard;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain;
import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter;
import com.shatteredpixel.shatteredpixeldungeon.levels.rooms.Room;
import com.watabou.utils.GameMath;
import com.watabou.utils.PathFinder;
import com.watabou.utils.Point;
import com.watabou.utils.PointF;
import com.watabou.utils.Random;
import com.watabou.utils.Rect;
import java.util.ArrayList;
public class SewerPipeRoom extends StandardRoom {
@Override
public int minWidth() {
return Math.max(7, super.minWidth());
}
@Override
public int minHeight() {
return Math.max(7, super.minHeight());
}
@Override
public float[] sizeCatProbs() {
return new float[]{4, 2, 1};
}
@Override
public boolean canMerge(Level l, Point p, int mergeTerrain) {
return false;
}
@Override
public boolean canConnect(Point p) {
//refuses connections next to corners
return super.canConnect(p) && ((p.x > left+1 && p.x < right-1) || (p.y > top+1 && p.y < bottom-1));
}
//FIXME this class is a total mess, lots of copy-pasta from tunnel and perimeter rooms here
@Override
public void paint(Level level) {
Painter.fill( level, this, Terrain.WALL );
Rect c = getConnectionSpace();
if (connected.size() <= 2) {
for (Door door : connected.values()) {
Point start;
Point mid;
Point end;
start = new Point(door);
if (start.x == left) start.x += 2;
else if (start.y == top) start.y += 2;
else if (start.x == right) start.x -= 2;
else if (start.y == bottom) start.y -= 2;
int rightShift;
int downShift;
if (start.x < c.left) rightShift = c.left - start.x;
else if (start.x > c.right) rightShift = c.right - start.x;
else rightShift = 0;
if (start.y < c.top) downShift = c.top - start.y;
else if (start.y > c.bottom) downShift = c.bottom - start.y;
else downShift = 0;
//always goes inward first
if (door.x == left || door.x == right) {
mid = new Point(start.x + rightShift, start.y);
end = new Point(mid.x, mid.y + downShift);
} else {
mid = new Point(start.x, start.y + downShift);
end = new Point(mid.x + rightShift, mid.y);
}
Painter.drawLine(level, start, mid, Terrain.WATER);
Painter.drawLine(level, mid, end, Terrain.WATER);
}
} else {
ArrayList<Point> pointsToFill = new ArrayList<>();
for (Point door : connected.values()) {
Point p = new Point(door);
if (p.y == top){
p.y+=2;
} else if (p.y == bottom) {
p.y-=2;
} else if (p.x == left){
p.x+=2;
} else {
p.x-=2;
}
pointsToFill.add( p );
}
ArrayList<Point> pointsFilled = new ArrayList<>();
pointsFilled.add(pointsToFill.remove(0));
Point from = null, to = null;
int shortestDistance;
while(!pointsToFill.isEmpty()){
shortestDistance = Integer.MAX_VALUE;
for (Point f : pointsFilled){
for (Point t : pointsToFill){
int dist = distanceBetweenPoints(f, t);
if (dist < shortestDistance){
from = f;
to = t;
shortestDistance = dist;
}
}
}
fillBetweenPoints(level, from, to, Terrain.WATER);
pointsFilled.add(to);
pointsToFill.remove(to);
}
}
for(Point p : getPoints()){
int cell = level.pointToCell(p);
if (level.map[cell] == Terrain.WATER){
for (int i : PathFinder.NEIGHBOURS8){
if (level.map[cell + i] == Terrain.WALL){
Painter.set(level, cell + i, Terrain.EMPTY);
}
}
}
}
for (Room r : connected.keySet()) {
if (r instanceof SewerPipeRoom){
Point door = connected.get(r);
Painter.fill(level, door.x-1, door.y-1, 3, 3, Terrain.EMPTY);
if (door.x == left || door.x == right){
Painter.fill(level, door.x-1, door.y, 3, 1, Terrain.WATER);
} else {
Painter.fill(level, door.x, door.y-1, 1, 3, Terrain.WATER);
}
connected.get(r).set( Door.Type.WATER );
} else {
connected.get(r).set( Door.Type.REGULAR );
}
}
}
//returns the space which all doors must connect to (usually 1 cell, but can be more)
//Note that, like rooms, this space is inclusive to its right and bottom sides
protected Rect getConnectionSpace(){
Point c = connected.size() <= 1 ? center() : getDoorCenter();
return new Rect(c.x, c.y, c.x, c.y);
}
@Override
public boolean canPlaceWater(Point p) {
return false;
}
//returns a point equidistant from all doors this room has
protected final Point getDoorCenter(){
PointF doorCenter = new PointF(0, 0);
for (Door door : connected.values()) {
doorCenter.x += door.x;
doorCenter.y += door.y;
}
Point c = new Point((int)doorCenter.x / connected.size(), (int)doorCenter.y / connected.size());
if (Random.Float() < doorCenter.x % 1) c.x++;
if (Random.Float() < doorCenter.y % 1) c.y++;
c.x = (int) GameMath.gate(left+2, c.x, right-2);
c.y = (int)GameMath.gate(top+2, c.y, bottom-2);
return c;
}
private int spaceBetween(int a, int b){
return Math.abs(a - b)-1;
}
//gets the path distance between two points
private int distanceBetweenPoints(Point a, Point b){
//on the same side
if (((a.x == left+2 || a.x == right-2) && a.y == b.y)
|| ((a.y == top+2 || a.y == bottom-2) && a.x == b.x)){
return Math.max(spaceBetween(a.x, b.x), spaceBetween(a.y, b.y));
}
//otherwise...
//subtract 1 at the end to account for overlap
return
Math.min(spaceBetween(left, a.x) + spaceBetween(left, b.x),
spaceBetween(right, a.x) + spaceBetween(right, b.x))
+
Math.min(spaceBetween(top, a.y) + spaceBetween(top, b.y),
spaceBetween(bottom, a.y) + spaceBetween(bottom, b.y))
-
1;
}
private Point[] corners;
//picks the smallest path to fill between two points
private void fillBetweenPoints(Level level, Point from, Point to, int floor){
//doors are along the same side
if (((from.x == left+2 || from.x == right-2) && from.x == to.x)
|| ((from.y == top+2 || from.y == bottom-2) && from.y == to.y)){
Painter.fill(level,
Math.min(from.x, to.x),
Math.min(from.y, to.y),
spaceBetween(from.x, to.x) + 2,
spaceBetween(from.y, to.y) + 2,
floor);
return;
}
//set up corners
if (corners == null){
corners = new Point[4];
corners[0] = new Point(left+2, top+2);
corners[1] = new Point(right-2, top+2);
corners[2] = new Point(right-2, bottom-2);
corners[3] = new Point(left+2, bottom-2);
}
//doors on adjacent sides
for (Point c : corners){
if ((c.x == from.x || c.y == from.y) && (c.x == to.x || c.y == to.y)){
Painter.drawLine(level, from, c, floor);
Painter.drawLine(level, c, to, floor);
return;
}
}
//doors on opposite sides
Point side;
if (from.y == top+2 || from.y == bottom-2){
//connect along the left, or right side
if (spaceBetween(left, from.x) + spaceBetween(left, to.x) <=
spaceBetween(right, from.x) + spaceBetween(right, to.x)){
side = new Point(left+2, top + height()/2);
} else {
side = new Point(right-2, top + height()/2);
}
} else {
//connect along the top, or bottom side
if (spaceBetween(top, from.y) + spaceBetween(top, to.y) <=
spaceBetween(bottom, from.y) + spaceBetween(bottom, to.y)){
side = new Point(left + width()/2, top+2);
} else {
side = new Point(left + width()/2, bottom-2);
}
}
//treat this as two connections with adjacent sides
fillBetweenPoints(level, from, side, floor);
fillBetweenPoints(level, side, to, floor);
}
}
| 00-Evan/shattered-pixel-dungeon | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/standard/SewerPipeRoom.java | Java | gpl-3.0 | 8,446 |
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<title>GLib.OutputStreamSpliceFlags.CLOSE_SOURCE -- Vala Binding Reference</title>
<link href="../style.css" rel="stylesheet" type="text/css"/><script src="../scripts.js" type="text/javascript">
</script>
</head>
<body>
<div class="site_header">GLib.OutputStreamSpliceFlags.CLOSE_SOURCE Reference Manual</div>
<div class="site_body">
<div class="site_navigation">
<ul class="navi_main">
<li class="package_index"><a href="../index.html">Packages</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="package"><a href="index.htm">gio-2.0</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="GLib.html">GLib</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="enum"><a href="GLib.OutputStreamSpliceFlags.html">OutputStreamSpliceFlags</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="enumvalue">CLOSE_SOURCE</li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
</ul>
</div>
<div class="site_content">
<h1 class="main_title">CLOSE_SOURCE</h1>
<hr class="main_hr"/>
<h2 class="main_title">Description:</h2>
<div class="main_code_definition"><b><span css="enumvalue">CLOSE_SOURCE</span></b>
</div>
</div>
</div><br/>
<div class="site_footer">Generated by <a href="http://www.valadoc.org/">Valadoc</a>
</div>
</body>
</html> | themightyug/ledborg-server | doc/gio-2.0/GLib.OutputStreamSpliceFlags.CLOSE_SOURCE.html | HTML | gpl-3.0 | 1,659 |
# Fair
An event that occurs over a few days to weeks.
## Convention hall
Users host events regularly with lots of users over a short period of time.
### Terminology
| Object | Description |
| ------ | ------ |
| Exhibitors | companies assigned to a space |
| Visitors | people visiting the fair |
| Fair (event) | the fair itself |
| Fair grounds | the location(s) used by the fair |
| Fair space | the location(s) polygons used by the exhibitor |
### Exhibitor
| Column | header |
| ------ | ------ |
| name | cell |
| company-name | cell |
| website-url | cell |
| logo | small logo max 250px |
| street | cell |
| street number | cell |
| postalcode | cell |
| city | cell |
| country | cell |
### Fair Space
| Column | header |
| ------ | ------ |
| name | cell |
| fk-fair-id | cell |
| fk-exhibitor-id | cell |
| geometry | cell |
### Fair Event
| Column | header |
| ------ | ------ |
| name | text |
| start-date | timestamp |
| end-date | timestamp |
| logo | image |
### Fair Ground
| Column | header |
| ------ | ------ |
| name | text |
| logo | image |
| geometry | MultiPolygon |
### Features
1. import exhibitor data excel csv
1. assign exhibitor to a fair space
1. crud fair
1. crud + copy event floor plan for new event
1. assign exhibitor to event and space
1. adjust walking routing network lines
| indrz/indrz-doc | legacy-content/fair.md | Markdown | gpl-3.0 | 1,330 |
var NAVTREE =
[
[ "MLX90621", "index.html", [
[ "MLX90621-Lite", "md__e_1__dropbox__projects__m_l_x90621-_lite__r_e_a_d_m_e.html", null ],
[ "Classes", "annotated.html", [
[ "Class List", "annotated.html", "annotated_dup" ],
[ "Class Index", "classes.html", null ],
[ "Class Members", "functions.html", [
[ "All", "functions.html", null ],
[ "Functions", "functions_func.html", null ],
[ "Variables", "functions_vars.html", null ]
] ]
] ],
[ "Files", null, [
[ "File List", "files.html", "files" ],
[ "File Members", "globals.html", [
[ "All", "globals.html", null ],
[ "Variables", "globals_vars.html", null ],
[ "Macros", "globals_defs.html", null ]
] ]
] ]
] ]
];
var NAVTREEINDEX =
[
"_m_l_x90621_8cpp.html"
];
var SYNCONMSG = 'click to disable panel synchronisation';
var SYNCOFFMSG = 'click to enable panel synchronisation'; | Leenix/MLX90621-Lite | doxy/html/navtreedata.js | JavaScript | gpl-3.0 | 946 |
# Bioinfo-tools
## interlace.py
Tool used to merge data matrix by column.
Example:
| RowName | Nb | Occ |
|---------|----|-----|
| Foo | 4 | 4 |
| Bar | 3 | 3 |
| Foobar | 3 | 3 |
and
| RowName | Nb | Occ |
|---------|----|-----|
| Foo | 8 | 1 |
| Bar | 2 | 4 |
| Foobar | 2 | 7 |
Will generate:
| RowName | Nb1 | Occ1 | Nb2 | Occ2 |
|---------|-----|------|-----|------|
| Foo | 4 | 4 | 8 | 1 |
| Bar | 3 | 3 | 2 | 4 |
| Foobar | 3 | 3 | 2 | 7 |
Warning: data matrix must be row-name sorted. The program won't index rownames and it will assume that they always come in the same order.
Warning2: this program isn't optimized ... it will consume a LOT of memory if you are playing with a lot of files
## pyVCF.py
Tool used in order to synchronize variants from two or more VCF files. Adapted to plug before Sciclone or QuantumClone.
Reads VCF files from any Tumor or Normal sample, looks up in BAM files for matching variants in any other sample, and outputs a result for every sample.
## Annotate_custom_rows.py
Tool used to add genomic information stored in a flat file database bgziped and tabix indexed to a generic other file containing genomic information.
Both files must be TSV-type files, though other separators may be really easy to implement.
Takes in input two files (the one that you want to annotate and the database), indexes (the indexes of the genomic regions for the file that you want to annotate and the index of the columns that you want to
add from your database). The program may remove trailing "chr" in order to ensure compatibility for all databases (in the same way, adding chr would be trivial, but I had no use for that).
Ex: python Annotate_custom_rows.py -i svdetect.txt -o - -c 4-5,7-8 --db ./genes.gz --remove-trailing-chr --db-index 2,3
=> This will take as genomic region input columns 4-5 and columns 7-8. The program will make it out for most situations, like chr3 in a first column, and 1:2 in a second column.
## remove_annot_*.py
Those scripts helps filtering snpEff annotated (either EFF format or new ANN format) vcf files.
They support either manual curation or batch removal of certain annotations.
## try_mutload.sh
Weird stuff that is supposed to help us filtering Integragen's variants... For now, we've tried like 10 different ways of filtering those variants and we still *NEVER* find the same number they find...
Usage: bash try_mutload.sh <in.snp> <in.indels> <out.somatics>
## collapse_files.py
This program will allow you to collapse N files by columns, without interlacing.
Example:
| RowName | Nb | Occ |
|---------|----|-----|
| Foo | 4 | 4 |
| Bar | 3 | 3 |
| Foobar | 3 | 3 |
and
| RowName | Nb | Occ |
|---------|----|-----|
| Foo | 8 | 1 |
| Bar | 2 | 4 |
| Foobar | 2 | 7 |
Will generate:
| RowName | Nb | Occ | RowName | Nb | Occ |
|---------|-----|------|---------|-----|------|
| Foo | 4 | 4 | Foo | 8 | 1 |
| Bar | 3 | 3 | Bar | 2 | 4 |
| Foobar | 3 | 3 | Foobar | 2 | 7 |
I just now get that it's looking awfully like interlace.py ...
Well, this one is very memory efficient (reads only one line per file at a time).
Warning: All files must have same number of lines
| OvoiDs/Bioinfo-tools | README.md | Markdown | gpl-3.0 | 3,327 |
<?php
/**
* ELIS(TM): Enterprise Learning Intelligence Suite
* Copyright (C) 2008-2012 Remote Learner.net Inc http://www.remote-learner.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 3 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, see <http://www.gnu.org/licenses/>.
*
* @package elis
* @subpackage curriculummanagement
* @author Remote-Learner.net Inc
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
* @copyright (C) 2008-2012 Remote Learner.net Inc http://www.remote-learner.net
*
*/
defined('MOODLE_INTERNAL') || die();
require_once elispm::lib('page.class.php');
require_once elispm::lib('lib.php');
/// The main management page.
class configpage extends pm_page {
var $pagename = 'cfg';
var $section = 'admn';
var $form_class = 'pmconfigform';
function can_do_default() {
$context = get_context_instance(CONTEXT_SYSTEM);
return has_capability('elis/program:config', $context);
}
function build_navbar_default($who = null) { // was build_navigation_default
global $CFG;
$page = $this->get_new_page(array('action' => 'default'), true);
$this->navbar->add(get_string('learningplan', 'elis_program'), "{$CFG->wwwroot}/elis/program/");
$this->navbar->add(get_string('notifications', 'elis_program'), $page->url);
}
function get_title_default() {
return get_string('configuration');
}
static function config_set_value($configdata, $key, $default = null) {
if (isset($configdata->$key)) {
$value = $configdata->$key;
} else {
$value = $default;
}
if ($value !== null) {
pm_set_config($key, $value);
}
}
function do_default() {
global $CFG, $DB;
$target = $this->get_new_page(array('action' => 'default'));
$configform = new $this->form_class($target->url);
if ($configform->is_cancelled()) {
$target = $this->get_new_page(array('action' => 'default'), true);
redirect($target->url);
return;
}
$configform->set_data(elis::$config->elis_program);
if ($configdata = $configform->get_data()) {
$old_cluster_groups = elis::$config->elis_program->cluster_groups;
$old_site_course_cluster_groups = elis::$config->elis_program->site_course_cluster_groups;
$old_cluster_groupings = elis::$config->elis_program->cluster_groupings;
// Track settings
self::config_set_value($configdata, 'userdefinedtrack', 0);
// Course catalog / Learning plan settings
self::config_set_value($configdata, 'disablecoursecatalog', 0);
self::config_set_value($configdata, 'catalog_collapse_count');
// Curriculum expiration settings (ELIS-1172)
$curassupdate = false;
// We need to check for an required update before setting the variable as the API call requires the
// variable to be set before the changes can take place.
if (isset($configdata->curriculum_expiration_start) &&
$configdata->curriculum_expiration_start != elis::$config->elis_program->curriculum_expiration_start) {
$curassupdate = true;
}
self::config_set_value($configdata, 'enable_curriculum_expiration', 0);
self::config_set_value($configdata, 'curriculum_expiration_start', '');
// If this setting is changed, we need to update the existing curriclum expiration values
if ($curassupdate) {
require_once elispm::lib('data/curriculumstudent.class.php');
if ($rs = $DB->get_recordset(curriculumstudent::TABLE, null, '', 'id, userid, curriculumid')) {
$timenow = time();
foreach ($rs as $curass) {
$update = new stdClass;
$update->id = $curass->id;
$update->timeexpired = calculate_curriculum_expiry(false, $curass->curriculumid, $curass->userid);
$update->timemodified = $timenow;
$DB->update_record(curriculumstudent::TABLE, $update);
}
$rs->close();
}
}
// Certificate settings
self::config_set_value($configdata, 'disablecertificates', 0);
self::config_set_value($configdata, 'certificate_border_image', 'Fancy1-blue.jpg');
self::config_set_value($configdata, 'certificate_seal_image', 'none');
self::config_set_value($configdata, 'certificate_template_file', 'default.php');
// Interface settings
self::config_set_value($configdata, 'time_format_12h', 0);
self::config_set_value($configdata, 'mymoodle_redirect', 0);
// User settings
self::config_set_value($configdata, 'auto_assign_user_idnumber', 0);
$old_cfg = elis::$config->elis_program->auto_assign_user_idnumber;
// if this setting is changed to true, synchronize the users
if (isset($configdata->auto_assign_user_idnumber)
&& $configdata->auto_assign_user_idnumber != 0
&& $old_cfg == 0) {
//TODO: Needs to be ported to ELIS 2
// cm_migrate_moodle_users(true, 0);
}
self::config_set_value($configdata, 'default_instructor_role', 0);
self::config_set_value($configdata, 'restrict_to_elis_enrolment_plugin', 0);
// Cluster settings
self::config_set_value($configdata, 'cluster_groups', 0);
self::config_set_value($configdata, 'site_course_cluster_groups', 0);
self::config_set_value($configdata, 'cluster_groupings', 0);
//settings specifically for the curriculum administration block
self::config_set_value($configdata, 'num_block_icons', 5);
self::config_set_value($configdata, 'display_clusters_at_top_level', 1);
self::config_set_value($configdata, 'display_curricula_at_top_level', 0);
//default role assignments on cm entities
self::config_set_value($configdata, 'default_cluster_role_id', 0);
self::config_set_value($configdata, 'default_curriculum_role_id', 0);
self::config_set_value($configdata, 'default_course_role_id', 0);
self::config_set_value($configdata, 'default_class_role_id', 0);
self::config_set_value($configdata, 'default_track_role_id', 0);
// TODO: ELIS 2 port of roles
//enrolment synchronization roles
/*$old_role_sync = elis::$config->elis_program->enrolment_role_sync_student_role;
self::config_set_value($configdata, 'enrolment_role_sync_student_role', 0);
if (isset($configdata->enrolment_role_sync_student_role)
&& $configdata->enrolment_role_sync_student_role != 0
&& $configdata->enrolment_role_sync_student_role != $old_role_sync) {
require_once CURMAN_DIRLOCATION . '/plugins/enrolment_role_sync/lib.php';
enrolment_role_sync::student_sync_role_set();
}
$old_role_sync = elis::$config->elis_program->enrolment_role_sync_instructor_role;
self::config_set_value($configdata, 'enrolment_role_sync_instructor_role', 0);
if (isset($configdata->enrolment_role_sync_instructor_role)
&& $configdata->enrolment_role_sync_instructor_role != 0
&& $configdata->enrolment_role_sync_instructor_role != $old_role_sync) {
require_once CURMAN_DIRLOCATION . '/plugins/enrolment_role_sync/lib.php';
enrolment_role_sync::instructor_sync_role_set();
}
*/
// autocreate settings
self::config_set_value($configdata, 'autocreated_unknown_is_yes', 0);
//trigger events
if(!empty($configdata->cluster_groups) && empty($old_cluster_groups)) {
events_trigger('crlm_cluster_groups_enabled', 0);
}
if(!empty($configdata->site_course_cluster_groups) && empty($old_site_course_cluster_groups)) {
events_trigger('crlm_site_course_cluster_groups_enabled', 0);
}
if(!empty($configdata->cluster_groupings) && empty($old_cluster_groupings)) {
events_trigger('crlm_cluster_groupings_enabled', 0);
}
}
//$configform->display();
$this->display('default');
}
/**
* handler for the edit action. Prints the edit form.
*/
function display_default() {
$target = $this->get_new_page(array('action' => 'default'));
$form = new $this->form_class($target->url);
// $form->set_data(array('id' => $parent_obj->id,
// 'association_id' => $obj->id));
$form->display();
}
}
?>
| msoni11/elismoodle | elis/program/configpage.class.php | PHP | gpl-3.0 | 9,593 |
# author David Sanchez david.sanchez@lapp.in2p3.fr
# ------ Imports --------------- #
import numpy
from Plot.PlotLibrary import *
from Catalog.ReadFermiCatalog import *
from environ import FERMI_CATALOG_DIR
# ------------------------------ #
#look for this 2FGL source
source = "2FGL J1015.1+4925"
#source = "1FHL J2158.8-3013"
#source = "3FGL J2158.8-3013"
Cat = FermiCatalogReader(source,FERMI_CATALOG_DIR,"e2dnde","TeV")
#print some information
print "2FGL association ",Cat.Association('3FGL')
print "3FGL Name ",Cat.Association('2FHL','3FGL_name')
print "3FGL Var Index ",Cat.GetVarIndex("3FGL")
#create a spectrum for a given catalog and compute the model+butterfly
Cat.MakeSpectrum("3FGL",1e-4,0.3)
enerbut,but,enerphi,phi = Cat.Plot("3FGL")
Cat.MakeSpectrum("2FGL",1e-4,0.3)
enerbut2FGL,but2FGL,enerphi2FGL,phi2FGL = Cat.Plot("2FGL")
Cat.MakeSpectrum("2FHL",5e-2,2)
enerbut2FHL,but2FHL,enerphi2FHL,phi2FHL = Cat.Plot("2FHL")
# read DATA Point
em,ep,flux,dflux = Cat.GetDataPoints('3FGL') #energy in TeV since the user ask for that in the call of Cat
ener = numpy.sqrt(em*ep)
dem = ener-em
dep = ep-ener
c=Cat.ReadPL('3FGL')[3]
dnde = (-c+1)*flux*numpy.power(ener*1e6,-c+2)/(numpy.power((ep*1e6),-c+1)-numpy.power((em*1e6),-c+1))*1.6e-6
ddnde = dnde*dflux/flux
#plot
import matplotlib.pyplot as plt
plt.loglog()
plt.plot(enerbut, but, 'b-',label = "3FGL")
plt.plot(enerphi,phi, 'b-')
plt.plot(enerbut2FGL,but2FGL,'g-',label = "2FGL")
plt.plot(enerphi2FGL,phi2FGL,'g-')
plt.plot(enerbut2FHL,but2FHL,'r-',label = "2FHL")
plt.plot(enerphi2FHL,phi2FHL,'r-')
plt.errorbar(ener, dnde, xerr= [dem,dep], yerr = ddnde,fmt='o')
plt.legend(loc = 3)
plt.ylabel('E2dN/dE(erg.cm-2.s-1)')
plt.xlabel('energy (TeV)')
plt.show()
| qpiel/python_estimation_source | Example/ExReadFermiCatalog.py | Python | gpl-3.0 | 1,737 |
/*
YUI 3.13.0 (build 508226d)
Copyright 2013 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('datasource-get', function (Y, NAME) {
/**
* Provides a DataSource implementation which can be used to retrieve data via the Get Utility.
*
* @module datasource
* @submodule datasource-get
*/
/**
* Get Utility subclass for the DataSource Utility.
* @class DataSource.Get
* @extends DataSource.Local
* @constructor
*/
var DSGet = function() {
DSGet.superclass.constructor.apply(this, arguments);
};
Y.DataSource.Get = Y.extend(DSGet, Y.DataSource.Local, {
/**
* Passes query string to Get Utility. Fires <code>response</code> event when
* response is received asynchronously.
*
* @method _defRequestFn
* @param e {Event.Facade} Event Facade with the following properties:
* <dl>
* <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>
* <dt>request (Object)</dt> <dd>The request.</dd>
* <dt>callback (Object)</dt> <dd>The callback object with the following properties:
* <dl>
* <dt>success (Function)</dt> <dd>Success handler.</dd>
* <dt>failure (Function)</dt> <dd>Failure handler.</dd>
* </dl>
* </dd>
* <dt>cfg (Object)</dt> <dd>Configuration object.</dd>
* </dl>
* @protected
*/
_defRequestFn: function(e) {
var uri = this.get("source"),
get = this.get("get"),
guid = Y.guid().replace(/\-/g, '_'),
generateRequest = this.get( "generateRequestCallback" ),
payload = e.details[0],
self = this;
/**
* Stores the most recent request id for validation against stale
* response handling.
*
* @property _last
* @type {String}
* @protected
*/
this._last = guid;
// Dynamically add handler function with a closure to the callback stack
// for access to guid
YUI.Env.DataSource.callbacks[guid] = function(response) {
delete YUI.Env.DataSource.callbacks[guid];
delete Y.DataSource.Local.transactions[e.tId];
var process = self.get('asyncMode') !== "ignoreStaleResponses" ||
self._last === guid;
if (process) {
payload.data = response;
self.fire("data", payload);
} else {
Y.log("DataSource ignored stale response for id " + e.tId + "(" + e.request + ")", "info", "datasource-get");
}
};
// Add the callback param to the request url
uri += e.request + generateRequest.call( this, guid );
Y.log("DataSource is querying URL " + uri, "info", "datasource-get");
Y.DataSource.Local.transactions[e.tId] = get.script(uri, {
autopurge: true,
// Works in Firefox only....
onFailure: function (o) {
delete YUI.Env.DataSource.callbacks[guid];
delete Y.DataSource.Local.transactions[e.tId];
payload.error = new Error(o.msg || "Script node data failure");
Y.log("Script node data failure", "error", "datasource-get");
self.fire("data", payload);
},
onTimeout: function(o) {
delete YUI.Env.DataSource.callbacks[guid];
delete Y.DataSource.Local.transactions[e.tId];
payload.error = new Error(o.msg || "Script node data timeout");
Y.log("Script node data timeout", "error", "datasource-get");
self.fire("data", payload);
}
});
return e.tId;
},
/**
* Default method for adding callback param to url. See
* generateRequestCallback attribute.
*
* @method _generateRequest
* @param guid {String} unique identifier for callback function wrapper
* @protected
*/
_generateRequest: function (guid) {
return "&" + this.get("scriptCallbackParam") +
"=YUI.Env.DataSource.callbacks." + guid;
}
}, {
/**
* Class name.
*
* @property NAME
* @type String
* @static
* @final
* @value "dataSourceGet"
*/
NAME: "dataSourceGet",
////////////////////////////////////////////////////////////////////////////
//
// DataSource.Get Attributes
//
////////////////////////////////////////////////////////////////////////////
ATTRS: {
/**
* Pointer to Get Utility.
*
* @attribute get
* @type Y.Get
* @default Y.Get
*/
get: {
value: Y.Get,
cloneDefaultValue: false
},
/**
* Defines request/response management in the following manner:
* <dl>
* <!--<dt>queueRequests</dt>
* <dd>If a request is already in progress, wait until response is
* returned before sending the next request.</dd>
* <dt>cancelStaleRequests</dt>
* <dd>If a request is already in progress, cancel it before
* sending the next request.</dd>-->
* <dt>ignoreStaleResponses</dt>
* <dd>Send all requests, but handle only the response for the most
* recently sent request.</dd>
* <dt>allowAll</dt>
* <dd>Send all requests and handle all responses.</dd>
* </dl>
*
* @attribute asyncMode
* @type String
* @default "allowAll"
*/
asyncMode: {
value: "allowAll"
},
/**
* Callback string parameter name sent to the remote script. By default,
* requests are sent to
* <URI>?<scriptCallbackParam>=callbackFunction
*
* @attribute scriptCallbackParam
* @type String
* @default "callback"
*/
scriptCallbackParam : {
value: "callback"
},
/**
* Accepts the DataSource instance and a callback ID, and returns a callback
* param/value string that gets appended to the script URI. Implementers
* can customize this string to match their server's query syntax.
*
* @attribute generateRequestCallback
* @type Function
*/
generateRequestCallback : {
value: function () {
return this._generateRequest.apply(this, arguments);
}
}
}
});
YUI.namespace("Env.DataSource.callbacks");
}, '3.13.0', {"requires": ["datasource-local", "get"]});
| ouyangyu/fdmoodle | lib/yuilib/3.13.0/datasource-get/datasource-get-debug.js | JavaScript | gpl-3.0 | 6,930 |
package com.xck.modules.weather.web;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.xck.modules.weather.entity.NowCity;
import com.xck.modules.weather.service.NowCityService;
/*
* 实时城市天气信息Controller
* @author xck503c
* @version 2017-1-18
* */
@Controller
@RequestMapping(value="/f/weather/nowCity")
public class NowCityController extends BaseCityController{
@Autowired
private NowCityService nowCityService;
@RequestMapping(value="/query", method={RequestMethod.POST, RequestMethod.GET})
public String query(HttpServletRequest request, String city, String provC, String provE, Model model) {
boolean result = nowCityService.query(city, provC, provE, model);
if(result){
return "weather/weather_now";
}
return "weather/weather_index";
}
@RequestMapping(value="/returnUp", method={RequestMethod.POST, RequestMethod.GET})
public String returnUp(HttpServletRequest request,String provC, String provE, String city, Model model) {
boolean result = nowCityService.returnUp(request, model, city, provC, provE);
if(result){
return "redirect:/f/weather/basicCity/prov";
}
return "weather/weather_city";
}
}
| xck503c/PersonTool | src/main/java/com/xck/modules/weather/web/NowCityController.java | Java | gpl-3.0 | 1,443 |
// ScanAllDll API
///////////////////////////////////////////////////////////////////////////////
#ifndef SCANALLDLL_H
#define SCANALLDLL_H
#ifdef __cplusplus
extern "C" {
#endif
/* Used for function prototypes */
#define _SADFUNC_
/*
#if (__FLAT__) || defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) || defined(__BORLANDC__)
#define _SADFUNC_ __stdcall
#error "1"
#else
#define _SADFUNC_
#error "2"
#endif
#else
#define _SADFUNC_ _far _pascal
#error "3"
#endif
*/
#ifndef DYNAMIC_SCANALLDLL_DRIVER // Static loading
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the SCANALLDLL_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// SCANALLDLL_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
#ifdef SCANALLDLL_EXPORTS
#define SCANALLDLL_API __declspec(dllexport)
#else
#define SCANALLDLL_API __declspec(dllimport)
#endif
#endif
//-----------------------------------------------------------------------------
// Definition
//-----------------------------------------------------------------------------
//----- Includes files -----
#include "deftypes.h"
// 8 bytes alignment
#pragma pack( push , 8)
//----- Handle definition -----
#define cSADInvalidHandle 0xFFFFFFFF
#define cSADAllHandle 0xFFFFFFFE
typedef U32 tSADHandle;
typedef U32 tSADGraphHandle;
//----- Constant definition -----
#define cSADMaxNameLength 128
//----- Command definition -----
typedef enum
{
cSADStart, // Customer cde
cSADStop, // Customer cde
cSADOpen, // TreeView cde
cSADToggleRealTimeDisplay, // Customer cde
cSADCreateSupplier, // TreeView cde
cSADSave, // Customer cde
cSADSerialize, // Customer cde
cSADGetStatus, // Customer cde
cSADGetCommandEnable, // Customer cde
cSADToggleTimeChronological, // Customer cde
cSADToggleTimeAbsolute, // Customer cde
cSADToggleTimeReal, // Customer cde
cSADClear, // Customer cde
cSADApplyCdeToAll, // Customer cde
cSADToggleHHSS, // Customer cde
} tSADCommandType;
//----- Customer command enable definition -----
typedef U32 tSADCustomerUserCommandEnable;
#define cSADStartStopEnable 0x0001
#define cSADToggleRealTimeDisplayEnable 0x0002
#define cSADSaveEnable 0x0004
#define cSADToggleTimeChronologicalEnable 0x0008
#define cSADToggleTimeAbsoluteEnable 0x0010
#define cSADToggleTimeRealEnable 0x0020
#define cSADClearEnable 0x0040
#define cSADHHSSEnable 0x0080
//----- Command status definition -----
typedef U32 tSADCustomerStatus;
#define cSADCustomerStarted 0x0001
#define cSADCustomerTraceConnected 0x0002
#define cSADCustomerTimeChronological 0x0004
#define cSADCustomerTimeAbsolute 0x0008
#define cSADCustomerRealTimeDisplay 0x0010
#define cSADCustomerTimeReal 0x0020
#define cSADCustomerApplyCdeToAll 0x0040
#define cSADCustomerHHSS 0x0080
//----- Customer command definition -----
typedef enum
{
cSADTx,
} tSADCallBackCommandType;
//----- Status definition -----
typedef enum
{
cSADOk,
cSADErrorMutex,
cSADDeactivated,
cSADNotConnected,
cSADAlreadyConnected,
cSADError,
} tSADStatus;
//----- Trace type definition -----
typedef enum
{
cSADUndefinedType,
cSADTextType,
cSADFrameType, // Buffer + length
cSADAdrFrameType, // Id + Buffer + length
cSADDoubleAdrFrameType, // Id1 + Id2 + Buffer + length
cSADGraphType, // Graph
} tSADTraceType;
//----- Common CallBack definition -----
typedef BOOL (*tSADCallBackCde)(tSADCallBackCommandType,void*,void*);
//----- Frame type definition -----
#define cSADTypeTxFlag 0x80 // Rx = 0, Tx = 1
#define cSADTypeFrameTextFlag 0x40 // FrameData = 0, FrameText = 1
#define cSADTypeTextFlag 0x20 // NoText = 1, Text = 1
#define cSADTypeErrorFlag 0x10 // NoError = 0, Error = 1
#define cSADTypeStartFlag 0x01 // INTERNAL: Started frame
typedef U8 tSADTypeFlag;
#define cSADFixedBufferSize 4096
//----- Text type definition -----
typedef struct
{
tSADTypeFlag Type;
U32 Time;
COLORREF Color;
} tSADTextInfo;
typedef struct
{
tSADTextInfo Info;
const char* Buffer;
} tSADTextType;
typedef struct
{
COLORREF Color;
char Buffer[cSADFixedBufferSize];
} tSADFixedTextType;
//----- Frame type definition -----
typedef struct
{
tSADTypeFlag Type; // RX/TX, Text,Buffer
U32 Time;
U32 Lng;
} tSADFrameInfo;
typedef struct
{
tSADFrameInfo Info;
const U8* Buffer;
} tSADFrameType;
typedef struct
{
U32 Lng;
U8 Buffer[cSADFixedBufferSize];
} tSADFixedFrameType;
//----- AdrFrame type definition -----
typedef struct
{
tSADTypeFlag Type;
U32 Time;
U32 Lng;
U32 Adr;
} tSADAdrFrameInfo;
typedef struct
{
tSADAdrFrameInfo Info;
const U8* Buffer;
} tSADAdrFrameType;
typedef struct
{
U32 Lng;
U32 Adr;
U8 Buffer[cSADFixedBufferSize];
} tSADFixedAdrFrameType;
//----- DoubleAdrFrame type definition -----
typedef struct
{
tSADTypeFlag Type;
U32 Time;
U32 Lng;
U32 Adr1;
U32 Adr2;
} tSADDoubleAdrFrameInfo;
typedef struct
{
tSADDoubleAdrFrameInfo Info;
const U8* Buffer;
} tSADDoubleAdrFrameType;
typedef struct
{
U32 Lng;
U32 Adr1;
U32 Adr2;
U8 Buffer[cSADFixedBufferSize];
} tSADFixedDoubleAdrFrameType;
//----- Graph type definition -----
typedef struct
{
tSADTypeFlag Type;
U32 Time;
U32 Adr;
U8 DataSize;
} tSADGraphInfo;
typedef struct
{
tSADGraphInfo Info;
U32 Data;
} tSADGraphType;
//----- Supplier info -----
typedef struct
{
char ProcessName[cSADMaxNameLength];
char TraceName[cSADMaxNameLength];
tSADTraceType Type;
} tSADSupplierInfo;
//-----------------------------------------------------------------------------
// DYNAMIC LOADING FUNCTION
//-----------------------------------------------------------------------------
#ifdef DYNAMIC_SCANALLDLL_DRIVER
//-----------------------------------------------------------------------------
// API type for all
//-----------------------------------------------------------------------------
typedef U16 (_SADFUNC_ *SADGETDLLVERSION)();
typedef U8 (_SADFUNC_ *SADENUMSUPPLIERS)(tSADSupplierInfo SupplierInfoList[]);
//-----------------------------------------------------------------------------
// API type for Supplier function
//-----------------------------------------------------------------------------
//----- Universal function -----
typedef tSADHandle (_SADFUNC_ *SADCONNECTSUPPLIER)(tSADTraceType Type,const char* Name);
typedef tSADStatus (_SADFUNC_ *SADDECONNECTSUPPLIER)(tSADHandle Handle);
typedef tSADStatus (_SADFUNC_ *SADSETCALLBACKCDE)(tSADHandle Handle,tSADCallBackCde CallBackCde, void* CallBackCdeParam);
//----- Specific functions -----
//----- Text type -----
typedef tSADStatus (_SADFUNC_ *SADTEXTTRACE)(tSADHandle Handle,tSADTextType* pText);
//----- Frame type -----
typedef tSADStatus (_SADFUNC_ *SADFRAMETRACE)(tSADHandle Handle,tSADFrameType* pFrame);
//----- AdrFrame type -----
typedef tSADStatus (_SADFUNC_ *SADADRFRAMETRACE)(tSADHandle Handle,tSADAdrFrameType* pAdrFrame);
//----- DoubleAdrFrame type -----
typedef tSADStatus (_SADFUNC_ *SADDOUBLEADRFRAMETRACE)(tSADHandle Handle,tSADDoubleAdrFrameType* pDoubleAdrFrame);
//----- Graph type -----
typedef tSADStatus (_SADFUNC_ *SADGRAPHTRACE)(tSADHandle Handle,tSADGraphType* pGraph);
//-----------------------------------------------------------------------------
// API for customer function
//-----------------------------------------------------------------------------
//----- Universal function -----
typedef tSADHandle (_SADFUNC_ *SADCONNECTCUSTOMER)(CWnd* pWndParent,UINT Id,const char* ProcessName,const char* TraceName);
typedef tSADStatus (_SADFUNC_ *SADDECONNECTCUSTOMER)(tSADHandle Handle);
typedef tSADStatus (_SADFUNC_ *SADCOMMANDCUSTOMER)(tSADHandle Handle,tSADCommandType Cde,void* Param);
typedef tSADStatus (_SADFUNC_ *SADGETCUSTOMERSTATUS)(tSADHandle Handle,tSADCustomerStatus* pStatus);
typedef tSADStatus (_SADFUNC_ *SADCONNECTVIEWER)(CWnd* pWndParent,UINT Id,UINT MessageCde);
typedef tSADStatus (_SADFUNC_ *SADDECONNECTVIEWER)();
typedef tSADStatus (_SADFUNC_ *SADCOMMANDTRACEVIEW)(tSADCommandType Cde);
//-----------------------------------------------------------------------------
// STATIC LOADING FUNCTION
//-----------------------------------------------------------------------------
#else
//-----------------------------------------------------------------------------
// API type for all
//-----------------------------------------------------------------------------
SCANALLDLL_API U16 SADGetDllVersion();
SCANALLDLL_API U8 SADEnumSuppliers(tSADSupplierInfo SupplierInfoList[]);
//-----------------------------------------------------------------------------
// API for Supplier function
//-----------------------------------------------------------------------------
//----- Universal function -----
SCANALLDLL_API tSADHandle SADConnectSupplier(tSADTraceType Type,const char* Name);
SCANALLDLL_API tSADStatus SADDeconnectSupplier(tSADHandle Handle);
SCANALLDLL_API tSADStatus SADSetCallBackCde(tSADHandle Handle,tSADCallBackCde CallBackCde, void* CallBackCdeParam);
//----- Specific functions -----
//----- Text type -----
SCANALLDLL_API tSADStatus SADTextTrace(tSADHandle Handle,tSADTextType* pText);
//----- Frame type -----
SCANALLDLL_API tSADStatus SADFrameTrace(tSADHandle Handle,tSADFrameType* pFrame);
//----- AdrFrame type -----
SCANALLDLL_API tSADStatus SADAdrFrameTrace(tSADHandle Handle,tSADAdrFrameType* pAdrFrame);
//----- DoubleAdrFrame type -----
SCANALLDLL_API tSADStatus SADDoubleAdrFrameTrace(tSADHandle Handle,tSADDoubleAdrFrameType* pDoubleAdrFrame);
//----- Graph type -----
SCANALLDLL_API tSADStatus SADGraphTrace(tSADHandle Handle,tSADGraphType* pGraph);
//-----------------------------------------------------------------------------
// API type for customer function
//-----------------------------------------------------------------------------
//----- Universal function -----
SCANALLDLL_API tSADHandle SADConnectCustomer(CWnd* pWndParent,UINT Id,const char* ProcessName,const char* TraceName);
SCANALLDLL_API tSADStatus SADDeconnectCustomer(tSADHandle Handle);
SCANALLDLL_API tSADStatus SADCommandCustomer(tSADHandle Handle,tSADCommandType Cde,void* Param);
SCANALLDLL_API tSADStatus SADGetCustomerStatus(tSADHandle Handle,tSADCustomerStatus* pStatus);
SCANALLDLL_API tSADStatus SADConnectTraceView(CWnd* pWndParent,UINT Id,UINT MessageCde);
SCANALLDLL_API tSADStatus SADDeconnectTraceView();
SCANALLDLL_API tSADStatus SADCommandTraceView(tSADCommandType Cde,void* Param);
#endif
//-----------------------------------------------------------------------------
// END OF LOADING FUNCTION
//-----------------------------------------------------------------------------
#ifdef __cplusplus
}
#endif // _cplusplus
// Default alignment
#pragma pack( pop )
#endif // SCANALLDLL_H
| dmanev/ArchExtractor | jilTester/Tester/Build/Simulation/Kernel/SCANALLDLL.H | C++ | gpl-3.0 | 13,829 |
/*
* Copyright (C) 2012 Yee Young Han <websearch@naver.com> (http://blog.naver.com/websearch)
*
* 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 3 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 _SIP_UTILITY_H_
#define _SIP_UTILITY_H_
#include <string>
void SipSetSystemId( const char * pszId );
void SipMakeTag( char * pszTag, int iTagSize );
void SipMakeBranch( char * pszBranch, int iBranchSize );
void SipMakeCallIdName( char * pszCallId, int iCallIdSize );
bool SipMakePrintString( const unsigned char * pszInput, int iInputSize, char * pszOutput, int iOutputSize );
void SipMd5String21( char * string, char result[22] );
void SipIpv6Parse( std::string & strHost );
int SipIpv6Print( std::string & strHost, char * pszText, int iTextSize, int iLen );
#endif
| YeeYoungHan/cppsipstack | SipParser/SipUtility.h | C | gpl-3.0 | 1,431 |
package tmp.generated_gcide;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class Mult1 extends Mult {
public Mult1(OneOrMore oneOrMore, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<OneOrMore>("oneOrMore", oneOrMore)
}, firstToken, lastToken);
}
public Mult1(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public IASTNode deepCopy() {
return new Mult1(cloneProperties(),firstToken,lastToken);
}
public OneOrMore getOneOrMore() {
return ((PropertyOne<OneOrMore>)getProperty("oneOrMore")).getValue();
}
}
| ckaestne/CIDE | CIDE_Language_gCIDE/src/tmp/generated_gcide/Mult1.java | Java | gpl-3.0 | 705 |
---
categoría: Académicos
caso: A7
---
# Generar Acta de Examen de Candidatura
Se abrirá una pantalla con los datos del estudiante:
- Nombre del Estudiante
- Tutor Principal del Estudiante
- Titulo de Proyecto
- Miembros del Jurado y sus respectivos cargos.
Habrá un campo libre para que el secretario en consenso con los demás
miembros asiente las recomendaciones al estudiante y dos botones para
elegir: "apobado" o "no aprobado".
| sostenibilidad-unam/posgrado | posgradmin/docs/academicos/secretario_dictamina_la_evaluacion_de_candidatura.md | Markdown | gpl-3.0 | 447 |
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2010 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source
// & Institut Laue - Langevin
// SPDX - License - Identifier: GPL - 3.0 +
#ifndef SINGLE_VALUE_PARAMETER_PARSER_H_
#define SINGLE_VALUE_PARAMETER_PARSER_H_
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidKernel/System.h"
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Document.h>
#include <Poco/DOM/Element.h>
#include <Poco/DOM/NodeFilter.h>
#include <Poco/DOM/NodeIterator.h>
#include <Poco/DOM/NodeList.h>
#include <Poco/File.h>
#include <Poco/Path.h>
#include "MantidAPI/ImplicitFunctionParameterParser.h"
#ifndef Q_MOC_RUN
#include <boost/lexical_cast.hpp>
#endif
namespace Mantid {
namespace API {
/**
XML Parser for single value parameter types
@author Owen Arnold, Tessella plc
@date 01/10/2010
*/
template <class SingleValueParameterType>
class DLLExport SingleValueParameterParser
: public Mantid::API::ImplicitFunctionParameterParser {
public:
Mantid::API::ImplicitFunctionParameter *
createParameter(Poco::XML::Element *parameterElement) override;
SingleValueParameterType *
createWithoutDelegation(Poco::XML::Element *parameterElement);
void setSuccessorParser(
Mantid::API::ImplicitFunctionParameterParser *paramParser) override;
};
//////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
/* Creates a parameter from an xml element, otherwise defers to a successor
parser.
@param parameterElement : xml Element
@return A fully constructed ImplicitFunctionParameter.
*/
template <class SingleValueParameterType>
Mantid::API::ImplicitFunctionParameter *
SingleValueParameterParser<SingleValueParameterType>::createParameter(
Poco::XML::Element *parameterElement) {
using ValType = typename SingleValueParameterType::ValueType;
std::string typeName = parameterElement->getChildElement("Type")->innerText();
if (SingleValueParameterType::parameterName() != typeName) {
return m_successor->createParameter(parameterElement);
} else {
std::string sParameterValue =
parameterElement->getChildElement("Value")->innerText();
ValType value = boost::lexical_cast<ValType>(sParameterValue);
return new SingleValueParameterType(value);
}
}
//------------------------------------------------------------------------------
/* Creates a parameter from an xml element. This is single-shot. Does not defer
to successor if it fails!.
@param parameterElement : xml Element
@return A fully constructed SingleValueParameterType.
*/
template <class SingleValueParameterType>
SingleValueParameterType *
SingleValueParameterParser<SingleValueParameterType>::createWithoutDelegation(
Poco::XML::Element *parameterElement) {
using ValType = typename SingleValueParameterType::ValueType;
std::string typeName = parameterElement->getChildElement("Type")->innerText();
if (SingleValueParameterType::parameterName() != typeName) {
throw std::runtime_error("The attempted ::createWithoutDelegation failed. "
"The type provided does not match this parser.");
} else {
std::string sParameterValue =
parameterElement->getChildElement("Value")->innerText();
ValType value = boost::lexical_cast<ValType>(sParameterValue);
return new SingleValueParameterType(value);
}
}
//------------------------------------------------------------------------------
/* Sets the successor parser
@param parameterParser : the parser to defer to if the current instance can't
handle the parameter type.
*/
template <class SingleValueParameterType>
void SingleValueParameterParser<SingleValueParameterType>::setSuccessorParser(
Mantid::API::ImplicitFunctionParameterParser *paramParser) {
Mantid::API::ImplicitFunctionParameterParser::SuccessorType temp(paramParser);
m_successor.swap(temp);
}
} // namespace API
} // namespace Mantid
#endif
| mganeva/mantid | Framework/API/inc/MantidAPI/SingleValueParameterParser.h | C | gpl-3.0 | 4,198 |
/*
* This file is part of JGrasstools (http://www.jgrasstools.org)
* (C) HydroloGIS - www.hydrologis.com
*
* JGrasstools 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.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.jgrasstools.hortonmachine.models.hm;
import java.util.HashMap;
import org.geotools.coverage.grid.GridCoverage2D;
import org.jgrasstools.gears.utils.coverage.CoverageUtilities;
import org.jgrasstools.hortonmachine.modules.geomorphology.aspect.OmsAspect;
import org.jgrasstools.hortonmachine.utils.HMTestCase;
import org.jgrasstools.hortonmachine.utils.HMTestMaps;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
/**
* Test the {@link OmsAspect} module.
*
* @author Andrea Antonello (www.hydrologis.com)
*/
public class TestAspect extends HMTestCase {
public void testAspectDegrees() throws Exception {
double[][] pitData = HMTestMaps.pitData;
HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
CoordinateReferenceSystem crs = HMTestMaps.getCrs();
GridCoverage2D pitCoverage = CoverageUtilities.buildCoverage("pit", pitData, envelopeParams, crs, true);
OmsAspect aspect = new OmsAspect();
aspect.inElev = pitCoverage;
aspect.doRound = true;
aspect.pm = pm;
aspect.process();
GridCoverage2D aspectCoverage = aspect.outAspect;
checkMatrixEqual(aspectCoverage.getRenderedImage(), HMTestMaps.aspectDataDegrees, 0.01);
}
public void testAspectRadiants() throws Exception {
double[][] pitData = HMTestMaps.pitData;
HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
CoordinateReferenceSystem crs = HMTestMaps.getCrs();
GridCoverage2D pitCoverage = CoverageUtilities.buildCoverage("pit", pitData, envelopeParams, crs, true);
OmsAspect aspect = new OmsAspect();
aspect.inElev = pitCoverage;
aspect.doRadiants = true;
aspect.pm = pm;
aspect.process();
GridCoverage2D aspectCoverage = aspect.outAspect;
checkMatrixEqual(aspectCoverage.getRenderedImage(), HMTestMaps.aspectDataRadiants, 0.01);
}
}
| silviafranceschi/jgrasstools | hortonmachine/src/test/java/org/jgrasstools/hortonmachine/models/hm/TestAspect.java | Java | gpl-3.0 | 2,726 |
require 'wmonk/version.rb'
require 'pathname'
require 'uri'
#require 'addressable/uri'
require 'cgi'
require 'logger'
require 'sqlite3'
require 'anemone'
require 'content_urls'
require 'webrick'
require 'rack'
require 'yaml'
require 'sinatra/base'
require 'slim'
require 'wmonk/project'
require 'wmonk/copy'
require 'wmonk/anemone_storage'
require 'wmonk/server'
module Wmonk
CONF_FILENAME = 'wmonk.yaml'
CONF_TEMPLATE = 'wmonk.yaml.template'
SUPPORTED_URI_SCHEMES = ['http', 'https']
WELL_KNOWN_FILES_FILENAME = 'well_known_files.yaml'
def self.assets_path(filename = nil)
path = File.join(File.dirname(__FILE__), '../assets/')
path = path + filename if ! filename.nil?
path
end
# List of well known files often found on websites
# @return [Array] the list of well known files
def self.well_known_files
@@well_known_files ||= nil
if @@well_known_files.nil?
@@well_known_files = []
YAML::load(File.open(assets_path(WELL_KNOWN_FILES_FILENAME)), 'r').each {|f| @@well_known_files << f}
end
@@well_known_files
end
# List of root URLs for a list of URLs
# @option options [Array] :urls ([]) list of URLs
# @return [Array] the list of root URLs for the supplied list URLs
def self.root_urls(urls)
urls ||= []
root_urls = []
urls.each do |url|
url = URI.parse(url)
url.path = '/'
url.query = nil
url.fragment = nil
root_urls << url.to_s
end
root_urls.uniq
end
end
| sutch/wmonk | lib/wmonk.rb | Ruby | gpl-3.0 | 1,550 |
---
layout: politician2
title: zakirhussain gulamnabi khalifa
profile:
party: IND
constituency: Kheda
state: Gujarat
education:
level: 10th Pass
details:
photo:
sex:
caste:
religion:
current-office-title:
crime-accusation-instances: 0
date-of-birth: 1972
profession:
networth:
assets: 95,000
liabilities: 2,77,384
pan:
twitter:
website:
youtube-interview:
wikipedia:
candidature:
- election: Lok Sabha 2009
myneta-link: http://myneta.info/ls2009/candidate.php?candidate_id=2621
affidavit-link:
expenses-link:
constituency: Kheda
party: IND
criminal-cases: 0
assets: 95,000
liabilities: 2,77,384
result:
crime-record:
date: 2014-01-28
version: 0.0.5
tags:
---
##Summary
##Education
{% include "education.html" %}
##Political Career
{% include "political-career.html" %}
##Criminal Record
{% include "criminal-record.html" %}
##Personal Wealth
{% include "personal-wealth.html" %}
##Public Office Track Record
{% include "track-record.html" %}
##References
{% include "references.html" %} | vaibhavb/wisevoter | site/politicians/_posts/2013-12-18-zakirhussain-gulamnabi-khalifa.md | Markdown | gpl-3.0 | 1,116 |
$(function() {
$( "#save" ).click(function(){
bval = true;
bval = bval && $( "#nombres" ).required();
bval = bval && $( "#apellidop" ).required();
bval = bval && $( "#apellidom" ).required();
bval = bval && $( "#dni" ).required();
bval = bval && $( "#sexo" ).required();
bval = bval && $( "#direccion" ).required();
bval = bval && $( "#telefono" ).required();
if ( bval ) {
$("#frm").submit();
alert("DATOS GUARDADOS");
window.close();
}
else{alert("LLENAR TODOS LOS CAMPOS!!!");}
return false;
});
});
| AnthonyWainer/sisacreditacion | web/js/app/evt_form_docente_cca.js | JavaScript | gpl-3.0 | 687 |
/** \file
* Copyright (c) 2002 D.Ingamells
* Copyright (c) 1999, 2000 Carlo Wood. All rights reserved. <br>
* Copyright (c) 1994, 1996, 1997 Joseph Arceneaux. All rights reserved. <br>
* Copyright (c) 1992, 2002, 2008 Free Software Foundation, Inc. All rights reserved. <br>
*
* Copyright (c) 1980 The Regents of the University of California. <br>
* Copyright (c) 1976 Board of Trustees of the University of Illinois. All rights reserved.
* Copyright (c) 1985 Sun Microsystems, Inc.
* All rights reserved.<br>
*
* 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.
* - 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.<br>
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*
* 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 3
* of the License, or (at your option) any later version.
*
* This file is subject to the terms of the GNU General Public License as
* published by the Free Software Foundation. A copy of this license is
* included with this software distribution in the file COPYING. If you
* do not have a copy, you may obtain a copy by writing to the Free
* Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* File: output.c
* Purpose: Interface to the output file for the indent tool.
*
* History:
* - 2002-03-04 D.Ingamells Creation.
* - 2002-11-10 Cristalle Azundris Sabon <cristalle@azundris.com>
* Added --preprocessor-indentation (ppi) if set, will indent nested
* preprocessor-statements with n spaces per level. overrides -lps.
* -2007-11-11 Jean-Christophe Dubois <jcd@tribudubois.net>
* Added --indent-label and --linux-style options.
*/
#define _LARGEFILE64_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <utime.h>
#include <time.h>
#include <sys/stat.h>
#include "indent.h"
#include "sys.h"
#include "globs.h"
#include "code_io.h"
#include "output.h"
RCSTAG_CC ("$Id$");
static FILE * output = NULL;
static BOOLEAN inhibited = 0;
static buf_break_st_ty * buf_break_list = NULL;
/** Priority mask bits */
static const int boolean_operator = 1;
buf_break_st_ty * buf_break = NULL;
int out_lines = 0; /*!< used in output.c indent.c */
int com_lines = 0; /*!< used in output.c indent.c comments.c */
int prev_target_col_break = 0;
int buf_break_used = 0;
int preproc_indent = 0;
/**
* Returns `true' when `b1' is a better place to break the code than `b2'.
* `b1' must be newer.
*
* When `lineup_to_parens' is true, do not break more then 1 level deeper
* unless that doesn't cost us "too much" indentation.
* What is "too much" is determined in a fuzzy way as follows:
* Consider the example,
* while (!(!(!(!(!(!(mask
* || (((a_very_long_expression_that_cant_be_broken
* here we prefer to break after `mask' instead of after `while'.
* This is because the `target_col' is pretty close to the break point
* of the `while': "mask"->target_col - "while"->col == 15 == "mask"->level * 2 + 1.
*/
static BOOLEAN better_break (
buf_break_st_ty *b1,
const buf_break_st_ty *b2)
{
static int first_level;
BOOLEAN is_better;
if (!b2)
{
first_level = b1->level;
b1->first_level = first_level;
is_better = true;
}
else
{
if (b2->target_col >= b2->col + 1)
{
is_better = true;
}
else if (settings.honour_newlines && b2->priority_newline)
{
is_better = false;
}
else if (settings.honour_newlines && b1->priority_newline)
{
is_better = true;
}
else
{
int only_parens_till_b2 = 0;
is_better = (b1->priority > b2->priority);
if (is_better)
{
char *p;
for (p = &s_code[b2->offset]; p >= s_code; --p)
{
if (*p == '!')
{
--p;
}
if (*p != '(')
{
break;
}
}
if (p < s_code)
{
only_parens_till_b2 = 1;
}
}
if (settings.lineup_to_parens && (b1->level > (first_level + 1)) &&
!(only_parens_till_b2 &&
(b1->target_col <= (b2->col + (1 + 2 * b1->level)))) &&
(b1->level > b2->level))
{
is_better = false;
}
}
if (is_better)
{
b1->first_level = first_level;
}
}
return is_better;
}
/**
* Calculate break priority.
*
* Example:
* e_code (`s_code' buffer, at the moment
* set_buf_break() is called)
* ptr (`s_code' buffer)
* corresponds_to (input buffer)
* Left most column col+1 (the column (31 here)).
* | |
* 1234567890123456789012345678901234567890
* if (!(mask[0] == '\\0'
* |
* target_col (assuming `lineup_to_parens' is true in this example)
* 1 2 3 2 | level == 2
* <--------------------->
* priority_code_length
*/
static void set_priority (
buf_break_st_ty *bb)
{
bb->priority = bb->priority_code_length;
switch (bb->priority_code)
{
case bb_semicolon:
bb->priority += 6000;
break;
case bb_before_boolean_binary_op:
bb->priority += 5000;
break;
case bb_after_boolean_binary_op:
if (bb->priority_code_length > 2)
{
bb->priority += 5000;
}
if (settings.break_before_boolean_operator)
{
bb->priority -= 3;
}
break;
case bb_after_equal_sign:
bb->priority += 4000;
break;
case bb_attribute:
bb->priority += 3000;
break;
case bb_comma:
bb->priority += 2000;
break;
case bb_comparisation:
bb->priority += 1000;
break;
case bb_proc_call:
bb->priority -= 1000;
break;
case bb_operator6:
bb->priority += 600;
break;
case bb_operator5:
bb->priority += 500;
break;
case bb_operator4:
bb->priority += 400;
break;
case bb_operator2:
bb->priority += 200;
break;
case bb_doublecolon:
bb->priority += 100;
break;
default:
break;
}
}
/**
* This function is called at every position where we possibly want
* to break a line (if it gets too long).
*/
void set_buf_break (
bb_code_ty code,
int paren_targ)
{
int target_col, level;
int code_target = compute_code_target (paren_targ);
buf_break_st_ty *bb;
/* First, calculate the column that code following e_code would be
* printed in if we'd break the line here.
* This is done quite simular to compute_code_target(). */
/* Base indentation level (number of open left-braces) */
target_col = parser_state_tos->i_l_follow + 1;
/* Did we just parse a brace that will be put on the next line
* by this line break? */
if (*token == '{')
{
target_col -= settings.ind_size; /* Use `ind_size' because this only happens
* for the first brace of initializer blocks. */
}
/* Number of open brackets */
level = parser_state_tos->p_l_follow;
/* Did we just parse a bracket that will be put on the next line
* by this line break? */
if ((*token == '(') || (*token == '['))
{
--level; /* then don't take it into account */
}
/* Procedure name of function declaration? */
if (parser_state_tos->procname[0] &&
(token == parser_state_tos->procname))
{
target_col = 1;
}
else if (level == 0) /* No open brackets? */
{
if (parser_state_tos->in_stmt) /* Breaking a statement? */
{
target_col += settings.continuation_indent;
}
}
else if (!settings.lineup_to_parens)
{
target_col += settings.continuation_indent +
(settings.paren_indent * (level - 1));
}
else
{
if (parser_state_tos->paren_indents[level - 1] < 0)
{
target_col = -parser_state_tos->paren_indents[level - 1];
}
else
{
target_col = code_target + parser_state_tos->paren_indents[level - 1];
}
}
/* Store the position of `e_code' as the place to break this line. */
bb = (buf_break_st_ty *) xmalloc (sizeof (buf_break_st_ty));
bb->offset = e_code - s_code;
bb->level = level;
bb->target_col = target_col;
bb->corresponds_to = token;
*e_code = 0;
bb->col = count_columns (code_target, s_code, NULL_CHAR) - 1;
/* Calculate default priority. */
bb->priority_code_length = (e_code - s_code);
bb->priority_newline = (parser_state_tos->last_saw_nl &&
!parser_state_tos->broken_at_non_nl);
if (buf_break)
{
bb->first_level = buf_break->first_level;
}
switch (parser_state_tos->last_token)
{
case binary_op:
if ( ((e_code - s_code) >= 3) &&
(e_code[-3] == ' ') &&
(((e_code[-1] == '&') && (e_code[-2] == '&')) ||
((e_code[-1] == '|') && (e_code[-2] == '|'))))
{
bb->priority_code = bb_after_boolean_binary_op;
}
else if ( (e_code - s_code >= 2) && (e_code[-1] == '=') &&
( (e_code[-2] == ' ') ||
( (e_code - s_code >= 3) &&
(e_code[-3] == ' ') &&
( (e_code[-2] == '%') ||
(e_code[-2] == '^') ||
(e_code[-2] == '&') ||
(e_code[-2] == '*') ||
(e_code[-2] == '-') ||
(e_code[-2] == '+') ||
(e_code[-2] == '|')))))
{
bb->priority_code = bb_after_equal_sign;
}
else if ( ( ( (e_code - s_code) >= 2) &&
(e_code[-2] == ' ') &&
( (e_code[-1] == '<') ||
(e_code[-1] == '>'))) ||
( ( (e_code - s_code) >= 3) &&
(e_code[-3] == ' ') &&
(e_code[-1] == '=') &&
( (e_code[-2] == '=') ||
(e_code[-2] == '!') ||
(e_code[-2] == '<') ||
(e_code[-2] == '>'))))
{
bb->priority_code = bb_comparisation;
}
else if ( (e_code[-1] == '+') ||
(e_code[-1] == '-'))
{
bb->priority_code = bb_operator6;
}
else if ( (e_code[-1] == '*') || (e_code[-1] == '/') || (e_code[-1] == '%'))
{
bb->priority_code = bb_operator5;
}
else
{
bb->priority_code = bb_binary_op;
}
break;
case comma:
bb->priority_code = bb_comma;
break;
default:
if ( (code == bb_binary_op) &&
( (*token == '&') ||
(*token == '|')) &&
(*token == token[1]))
{
bb->priority_code = bb_before_boolean_binary_op;
}
else if (e_code[-1] == ';')
{
bb->priority_code = bb_semicolon;
}
else
{
bb->priority_code = code;
if (code == bb_struct_delim) /* . -> .* or ->* */
{
if (e_code[-1] == '*')
{
bb->priority_code = bb_operator4;
}
else
{
bb->priority_code = bb_operator2;
}
}
}
}
set_priority (bb);
/* Add buf_break to the list */
if (buf_break_list)
{
buf_break_list->next = bb;
}
bb->prev = buf_break_list;
bb->next = NULL;
buf_break_list = bb;
if (!buf_break || (bb->col <= settings.max_col))
{
if (better_break (bb, buf_break))
{
/* Found better buf_break. Get rid of all previous possible breaks. */
buf_break = bb;
for (bb = bb->prev; bb;)
{
buf_break_st_ty *obb = bb;
bb = bb->prev;
free (obb);
}
buf_break->prev = NULL;
}
}
}
/**
*
*/
void clear_buf_break_list (
BOOLEAN * pbreak_line)
{
buf_break_st_ty *bb;
for (bb = buf_break_list; bb;)
{
buf_break_st_ty *obb = bb;
bb = bb->prev;
free (obb);
}
buf_break = buf_break_list = NULL;
*pbreak_line = false;
}
/**
* @verbatim
* prev_code_target
* | prev_code_target + offset
* | |
* <----->if ((aaa == bbb) && xxx
* && xxx
* |
* new_code_target
* @endverbatim
*/
static void set_next_buf_break (
int prev_code_target,
int new_code_target,
int offset,
BOOLEAN * pbreak_line)
{
buf_break_st_ty *bb;
better_break (buf_break, NULL); /* Reset first_level */
if (buf_break_list == buf_break)
{
clear_buf_break_list (pbreak_line);
}
else
{
/* Correct all elements of the remaining buf breaks: */
for (bb = buf_break_list; bb; bb = bb->prev)
{
if (bb->target_col > buf_break->target_col && settings.lineup_to_parens)
{
bb->target_col -= ((prev_code_target + offset) - new_code_target);
}
bb->col -= ((prev_code_target + offset) - new_code_target);
bb->offset -= offset;
bb->priority_code_length -= offset;
bb->first_level = buf_break->first_level;
if (!buf_break->priority_newline)
{
bb->priority_newline = false;
}
set_priority (bb);
if (bb->prev == buf_break)
{
break;
}
}
free (buf_break);
/* Set buf_break to first break in the list */
buf_break = bb;
/* GDB_HOOK_buf_break */
buf_break->prev = NULL;
/* Find a better break of the existing breaks */
for (bb = buf_break; bb; bb = bb->next)
{
if (bb->col > settings.max_col)
{
continue;
}
if (better_break (bb, buf_break))
{
/* Found better buf_break. Get rid of all previous possible breaks. */
buf_break = bb;
for (bb = bb->prev; bb;)
{
buf_break_st_ty *obb = bb;
bb = bb->prev;
free (obb);
}
bb = buf_break;
buf_break->prev = NULL;
}
}
}
}
/**
* Name: pad_output
* Description: Fill the output line with whitespace up to TARGET_COLUMN,
* given that the line is currently in column CURRENT_COLUMN.
*
* Returns: the ending column number.
*
* History:
*/
static int pad_output(
int current_column,
int target_column)
{
if (current_column < target_column)
{
if (settings.use_tabs && (settings.tabsize > 1))
{
int offset = settings.tabsize - (current_column - 1) % settings.tabsize;
while (current_column + offset <= target_column)
{
putc(TAB, output);
current_column += offset;
offset = settings.tabsize;
}
}
while (current_column < target_column)
{
putc(' ', output);
current_column++;
}
}
return current_column;
}
/**
* output the sequence of characters starting at begin and
* ending at the character _before_ end (the character at end is not output)
* to file.
*/
static void output_substring(
FILE * file,
const char * begin,
const char * end)
{
const char * p;
for (p = begin; p < end; p++)
{
putc (*p, file);
}
}
/**
* Name: dump_line_label
* Description: routine that actually effects the printing of the new source's label section.
*
* Returns: current column number..
*
* History:
*/
static int dump_line_label(void)
{
int cur_col;
/* print lab, if any */
while ((e_lab > s_lab) && ((e_lab[-1] == ' ') ||
(e_lab[-1] == TAB)))
{
e_lab--;
}
cur_col = pad_output(1, compute_label_target());
/* force indentation of preprocessor directives.
* this happens when force_preproc_width > 0 */
if ((settings.force_preproc_width > 0) &&
(s_lab[0] == '#'))
{
int preproc_postcrement;
char *p = &s_lab[1];
while(*p == ' ')
{
p++;
}
preproc_postcrement = settings.force_preproc_width;
if (strncmp(p, "else", 4) == 0)
{
preproc_indent-=settings.force_preproc_width;
}
else if ((strncmp(p, "if", 2) == 0) ||
(strncmp(p, "ifdef", 5) == 0))
{
}
else if (strncmp(p, "elif", 4) == 0)
{
preproc_indent -= settings.force_preproc_width;
}
else if (strncmp(p, "endif", 5) == 0)
{
preproc_indent -= settings.force_preproc_width;
preproc_postcrement = 0;
}
else
{
preproc_postcrement = 0;
}
if (preproc_indent == 0)
{
fprintf (output, "#");
}
else
{
fprintf (output, "#%*s", preproc_indent, " ");
}
fprintf (output, "%.*s", (int) (e_lab - p), p);
cur_col = count_columns (cur_col + preproc_indent + 1, p, NULL_CHAR);
preproc_indent += preproc_postcrement;
}
else if ((s_lab[0] == '#') && ((strncmp (&s_lab[1], "else", 4) == 0) ||
(strncmp (&s_lab[1], "endif", 5) == 0)))
{
/* Treat #else and #endif as a special case because any text
* after #else or #endif should be converted to a comment. */
char *s = s_lab;
if (e_lab[-1] == EOL) /* Don't include EOL in the comment */
{
e_lab--;
}
do
{
putc (*s++, output);
++cur_col;
} while ((s < e_lab) && ('a' <= *s) && (*s <= 'z'));
while (((*s == ' ') || (*s == TAB)) && (s < e_lab))
{
s++;
}
if (s < e_lab)
{
if (settings.tabsize > 1)
{
cur_col = pad_output (cur_col, cur_col + settings.tabsize -
(cur_col - 1) % settings.tabsize);
}
else
{
cur_col = pad_output (cur_col, cur_col + 2);
}
if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
{
fprintf (output, "%.*s", e_lab - s, s);
}
else
{
fprintf (output, "/* %.*s */", e_lab - s, s);
}
/* no need to update cur_col: the very next thing will
be a new-line (or end of file) */
}
}
else
{
fprintf (output, "%.*s", (int) (e_lab - s_lab), s_lab);
cur_col = count_columns (cur_col, s_lab, NULL_CHAR);
}
return cur_col;
}
/**
*
*/
static int count_parens(
const char * string)
{
int paren_level = 0;
while (*string)
{
switch (*string)
{
case '(':
case '[':
paren_level++;
break;
case ')':
case ']':
paren_level--;
break;
default:
break;
}
string++;
}
return paren_level;
}
/**
*
*/
static void dump_line_code(
int * pcur_col,
int * pnot_truncated,
int paren_targ,
BOOLEAN * pbreak_line,
int target_col_break)
{
int saved_cur_col = *pcur_col;
int paren_level = 0;
if (s_code != e_code)
{ /* print code section, if any */
int i;
int target_col = 0;
/* If a comment begins this line, then indent it to the correct
* column for comments, otherwise the line starts with code,
* so indent it for code. */
if (embedded_comment_on_line == 1)
{
target_col = parser_state_tos->com_col;
}
else if (target_col_break != -1)
{
target_col = target_col_break;
}
else
{
target_col = compute_code_target (paren_targ);
}
if (paren_level > 0)
{
target_col += parser_state_tos->paren_indents[parser_state_tos->p_l_follow + paren_level- 1];
}
/* If a line ends in an lparen character, the following line should
* not line up with the parenthesis, but should be indented by the
* usual amount. */
if (parser_state_tos->last_token == lparen)
{
parser_state_tos->paren_indents[parser_state_tos->p_l_follow - 1] +=
settings.ind_size - 1;
}
*pcur_col = pad_output (*pcur_col, target_col);
if (*pbreak_line && (s_com == e_com) &&
(buf_break->target_col <= buf_break->col))
{
int offset;
int len;
char c;
char *ptr = &s_code[buf_break->offset];
if (*ptr != ' ')
{
--ptr;
}
/* Add target_col (and negate) the brackets that are
* actually printed. The remaining brackets must
* be given an offset of . */
offset = ptr - s_code + 1;
for (i = 0; i < parser_state_tos->p_l_follow; i++)
{
if (parser_state_tos->paren_indents[i] >= 0)
{
if (parser_state_tos->paren_indents[i] < ptr - s_code)
{
parser_state_tos->paren_indents[i] =
-(parser_state_tos->paren_indents[i] + target_col);
}
else
{
parser_state_tos->paren_indents[i] -= offset;
}
}
}
for (i = parser_state_tos->p_l_follow;
i < parser_state_tos->paren_indents_size; ++i)
{
if (parser_state_tos->paren_indents[i] >= (ptr - s_code))
{
parser_state_tos->paren_indents[i] -= offset;
}
}
output_substring(output, s_code, s_code + buf_break->offset);
c = s_code[buf_break->offset];
s_code[buf_break->offset] = '\0';
*pcur_col = count_columns (*pcur_col, s_code, NULL_CHAR);
paren_level += count_parens(s_code);
s_code[buf_break->offset] = c;
*pnot_truncated = 0;
len = (e_code - ptr - 1);
memmove (s_code, ptr + 1, len);
e_code = s_code + len;
#if COLOR_DEBUG
fputs (" \e[31m", output);
output_substring(output, s_code, e_code);
fputs (" \e[0m", output);
#endif
*e_code = '\0';
s_code_corresponds_to = buf_break->corresponds_to;
prev_target_col_break = buf_break->target_col;
if (!buf_break->priority_newline)
{
parser_state_tos->broken_at_non_nl = true;
}
set_next_buf_break (target_col, buf_break->target_col,
offset, pbreak_line);
buf_break_used = 1;
*pbreak_line = (buf_break != NULL) &&
(output_line_length() > settings.max_col);
}
else
{
for (i = 0; i < parser_state_tos->p_l_follow; i++)
{
if (parser_state_tos->paren_indents[i] >= 0)
{
parser_state_tos->paren_indents[i] =
-(parser_state_tos->paren_indents[i] +
target_col);
}
}
output_substring(output, s_code, e_code);
*pcur_col = count_columns (*pcur_col, s_code, NULL_CHAR);
clear_buf_break_list (pbreak_line);
}
}
}
/**
* Name: dump_line
* Description: routine that actually effects the printing of the new source.
* It prints the label section, followed by the code section with
* the appropriate nesting level, followed by any comments.
*
* Returns: None.
*
* History:
*/
extern void dump_line (
int force_nl,
int * paren_targ,
BOOLEAN * pbreak_line)
{
int cur_col;
int not_truncated = 1;
int target_col_break = -1;
if (buf_break_used)
{
buf_break_used = 0;
target_col_break = prev_target_col_break;
}
else if (force_nl)
{
parser_state_tos->broken_at_non_nl = false;
}
if (parser_state_tos->procname[0] && !parser_state_tos->classname[0] &&
(s_code_corresponds_to == parser_state_tos->procname))
{
parser_state_tos->procname = "\0";
}
else if (parser_state_tos->procname[0] && parser_state_tos->classname[0] &&
(s_code_corresponds_to == parser_state_tos->classname))
{
parser_state_tos->procname = "\0";
parser_state_tos->classname = "\0";
}
/* A blank line */
if ((s_code == e_code) && (s_lab == e_lab) && (s_com == e_com))
{
/* If we have a formfeed on a blank line, we should just output it,
* rather than treat it as a normal blank line. */
if (parser_state_tos->use_ff)
{
putc ('\014', output);
parser_state_tos->use_ff = false;
}
else
{
n_real_blanklines++;
}
}
else
{
if (prefix_blankline_requested && (n_real_blanklines == 0))
{
n_real_blanklines = 1;
}
else if (settings.swallow_optional_blanklines && (n_real_blanklines > 1))
{
n_real_blanklines = 1;
}
while (--n_real_blanklines >= 0)
{
putc (EOL, output);
}
n_real_blanklines = 0;
if ((e_lab != s_lab) || (e_code != s_code))
{
++code_lines; /* keep count of lines with code */
}
if (e_lab != s_lab)
{
cur_col = dump_line_label();
}
else
{
cur_col = 1; /* there is no label section */
}
parser_state_tos->pcase = false;
/* Remove trailing spaces */
while ((*(e_code - 1) == ' ') && (e_code > s_code))
{
*(--e_code) = NULL_CHAR;
}
dump_line_code(&cur_col, ¬_truncated, *paren_targ, pbreak_line,
target_col_break);
if (s_com != e_com)
{
{
/* Here for comment printing. */
int target = parser_state_tos->com_col;
char *com_st = s_com;
if (cur_col > target)
{
putc (EOL, output);
cur_col = 1;
++out_lines;
}
cur_col = pad_output (cur_col, target);
fwrite (com_st, e_com - com_st, 1, output);
cur_col += e_com - com_st;
com_lines++;
}
}
else if (embedded_comment_on_line)
{
com_lines++;
}
embedded_comment_on_line = 0;
if (parser_state_tos->use_ff)
{
putc ('\014', output);
parser_state_tos->use_ff = false;
}
else
{
putc (EOL, output);
}
++out_lines;
if ((parser_state_tos->just_saw_decl == 1) &&
settings.blanklines_after_declarations)
{
prefix_blankline_requested = 1;
prefix_blankline_requested_code = decl;
parser_state_tos->just_saw_decl = 0;
}
else
{
prefix_blankline_requested = postfix_blankline_requested;
prefix_blankline_requested_code = postfix_blankline_requested_code;
}
postfix_blankline_requested = 0;
}
/* if we are in the middle of a declaration, remember that fact
* for proper comment indentation */
parser_state_tos->decl_on_line = parser_state_tos->in_decl;
/* next line should be indented if we have not completed this stmt */
parser_state_tos->ind_stmt = parser_state_tos->in_stmt;
e_lab = s_lab;
*s_lab = '\0'; /* reset buffers */
if (not_truncated)
{
e_code = s_code;
*s_code = '\0';
s_code_corresponds_to = NULL;
}
e_com = s_com;
*s_com = '\0';
parser_state_tos->ind_level = parser_state_tos->i_l_follow;
parser_state_tos->paren_level = parser_state_tos->p_l_follow;
if (parser_state_tos->paren_level > 0)
{
/* If we broke the line and the following line will
* begin with a rparen, the indentation is set for
* the column of the rparen *before* the break - reset
* the column to the position after the break. */
if (!not_truncated && ((*s_code == '(') || (*s_code == '[')) &&
(parser_state_tos->paren_level >= 2))
{
*paren_targ = -parser_state_tos->paren_indents[parser_state_tos->paren_level - 2];
}
else
{
*paren_targ = -parser_state_tos->paren_indents[parser_state_tos->paren_level - 1];
}
}
else
{
*paren_targ = 0;
}
if (inhibited)
{
char *p = cur_line;
while (--n_real_blanklines >= 0)
{
putc (EOL, output);
}
n_real_blanklines = 0;
do
{
while ((*p != '\0') && (*p != EOL))
{
putc (*p++, output);
}
if ((*p == '\0') &&
((unsigned long) (p - current_input->data) == current_input->size))
{
in_prog_pos = p;
buf_end = p;
buf_ptr = p;
had_eof = true;
return;
}
if (*p == EOL)
{
cur_line = p + 1;
line_no++;
}
putc (*p++, output);
while ((*p == ' ') || (*p == TAB))
{
putc (*p, output);
p++;
}
if ((*p == '/') && ((*(p + 1) == '*') ||
(*(p + 1) == '/')))
{
/* We've hit a comment. See if turns formatting
back on. */
putc (*p++, output);
putc (*p++, output);
while ((*p == ' ') || (*p == TAB))
{
putc (*p, output);
p++;
}
if (!strncmp (p, "*INDENT-ON*", 11))
{
do
{
while ((*p != '\0') && (*p != EOL))
{
putc (*p++, output);
}
if ((*p == '\0') &&
(((unsigned long) (p - current_input->data) ==
current_input->size)))
{
in_prog_pos = p;
buf_end = p;
buf_ptr = p;
had_eof = true;
return;
}
else
{
if (*p == EOL)
{
inhibited = false;
cur_line = p + 1;
line_no++;
}
putc (*p++, output);
}
} while (inhibited);
}
}
} while (inhibited);
in_prog_pos = cur_line;
buf_end = cur_line;
buf_ptr = cur_line;
fill_buffer ();
}
/* Output the rest already if we really wanted a new-line after this code. */
if (buf_break_used && (s_code != e_code) && force_nl)
{
prefix_blankline_requested = 0;
dump_line (true, paren_targ, pbreak_line);
}
return;
}
/**
* Name: flush_output
* Description: Flushes any buffered output to the output file.
*
* Returns: None
*
* History:
*/
extern void flush_output(void)
{
fflush (output);
}
/**
* Name: open_output
* Description: Opens the output file in read/write mode.
*
* Returns: None
*
* History:
*/
void open_output(
const char * filename,
const char * mode)
{
if (filename == NULL)
{
output = stdout;
}
else
{
output = fopen(filename, mode); /* open the file for read + write
* (but see the trunc function) */
if (output == NULL)
{
fprintf (stderr, _("indent: can't create %s\n"), filename);
exit (indent_fatal);
}
}
}
/**
* Name: reopen_output_trunc
* Description: Reopens the output file truncated.
*
* Returns: None
*
* History:
*/
extern void reopen_output_trunc(
const char * filename)
{
output = freopen(filename, "w", output);
}
/**
* Name: close_output
* Description: Closes the output file.
*
* Returns: None
*
* History:
*/
extern void close_output(
struct stat64 * file_stats,
const char * filename)
{
if (output != stdout)
{
if (fclose(output) != 0)
{
fatal(_("Can't close output file %s"), filename);
}
else
{
#ifdef PRESERVE_MTIME
if (file_stats != NULL)
{
struct utimbuf buf;
buf.actime = time (NULL);
buf.modtime = file_stats->st_mtime;
if (utime(filename, &buf) != 0)
{
WARNING(_("Can't preserve modification time on output file %s"),
filename, 0);
}
}
#endif
}
}
}
/**
*
*/
extern void inhibit_indenting(
BOOLEAN flag)
{
inhibited = flag;
}
/**
* Return the column in which we should place the code in s_code.
*/
int compute_code_target (
int paren_targ)
{
int target_col;
if (buf_break_used)
{
return prev_target_col_break;
}
if (parser_state_tos->procname[0] &&
(s_code_corresponds_to == parser_state_tos->procname))
{
target_col = 1;
if (!parser_state_tos->paren_level)
{
return target_col;
}
}
else
{
target_col = parser_state_tos->ind_level + 1;
}
if (!parser_state_tos->paren_level)
{
if (parser_state_tos->ind_stmt)
{
target_col += settings.continuation_indent;
}
return target_col;
}
if (!settings.lineup_to_parens)
{
return target_col + settings.continuation_indent +
(settings.paren_indent * (parser_state_tos->paren_level - 1));
}
return paren_targ;
}
/**
*
*/
int count_columns (
int column,
char *bp,
int stop_char)
{
while (*bp != stop_char && *bp != NULL_CHAR)
{
switch (*bp++)
{
case EOL:
case '\f': /* form feed */
column = 1;
break;
case TAB:
column += settings.tabsize - (column - 1) % settings.tabsize;
break;
case 010: /* backspace */
--column;
break;
#ifdef COLOR_DEBUG
case '\e': /* ANSI color */
while (*bp++ != 'm')
{
}
break;
#endif
default:
++column;
break;
}
}
return column;
}
/**
*
*/
int compute_label_target (void)
{
/* maybe there should be some option to tell indent where to put public:,
* private: etc. ? */
if (*s_lab == '#')
{
return 1;
}
if (parser_state_tos->pcase)
{
return parser_state_tos->cstk[parser_state_tos->tos] + 1;
}
if (settings.c_plus_plus && parser_state_tos->in_decl)
{
/* FIXME: does this belong here at all? */
return 1;
}
else if (settings.label_offset < 0)
{
return parser_state_tos->ind_level + settings.label_offset + 1;
}
else
{
return settings.label_offset + 1;
}
}
/**
* Compute the length of the line we will be outputting.
*/
int output_line_length (void)
{
int code_length = 0;
int com_length = 0;
int length;
if (s_lab == e_lab)
{
length = 0;
}
else
{
length = count_columns (compute_label_target (), s_lab, EOL) - 1;
}
if (s_code != e_code)
{
int code_col = compute_code_target(paren_target);
code_length = count_columns(code_col, s_code, EOL) - code_col;
}
if (s_com != e_com)
{
int com_col = parser_state_tos->com_col;
com_length = count_columns(com_col, s_com, EOL) - com_col;
}
if (code_length != 0)
{
length += compute_code_target(paren_target) - 1 + code_length;
if (embedded_comment_on_line)
{
length += com_length;
}
}
return length;
}
| ericfischer/indent | src/output.c | C | gpl-3.0 | 40,093 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Automatically generated strings for Moodle 2.1 installer
*
* Do not edit this file manually! It contains just a subset of strings
* needed during the very first steps of installation. This file was
* generated automatically by export-installer.php (which is part of AMOS
* {@link http://docs.moodle.org/dev/Languages/AMOS}) using the
* list of strings defined in /install/stringnames.txt.
*
* @package installer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['admindirname'] = 'Adresář se soubory pro správu serveru';
$string['availablelangs'] = 'Dostupné jazykové balíčky';
$string['chooselanguagehead'] = 'Vyberte jazyk';
$string['chooselanguagesub'] = 'Zvolte si jazyk tohoto průvodce instalací. Vybraný jazyk bude též nastaven jako výchozí jazyk stránek, ale to půjde případně později změnit.';
$string['clialreadyinstalled'] = 'Soubor config.php již existuje. Spusťte admin/cli/upgrade.php, pokud chcete provést upgrade vašich stránek.';
$string['cliinstallheader'] = 'Moodle {$a} - průvodce instalací z příkazové řádky';
$string['databasehost'] = 'Databázový server';
$string['databasename'] = 'Název databáze';
$string['databasetypehead'] = 'Vyberte databázový ovladač';
$string['dataroot'] = 'Datový adresář';
$string['datarootpermission'] = 'Přístupová práva k datovému adresáři';
$string['dbprefix'] = 'Předpona tabulek';
$string['dirroot'] = 'Adresář Moodlu';
$string['environmenthead'] = 'Kontrola programového prostředí...';
$string['environmentsub2'] = 'Každé vydání Moodle vyžaduje určitou minimální verzi PHP a několik povinných rozšíření PHP. Plná kontrola prostředí se provádí před každým instalací a upgrade. Prosím, kontaktujte správce serveru, pokud nevíte, jak nainstalovat novou verzi, nebo povolit rozšíření PHP.';
$string['errorsinenvironment'] = 'Kontrola serverového prostředí selhala!';
$string['installation'] = 'Instalace';
$string['langdownloaderror'] = 'Bohužel, jazyk "{$a}" se nepodařilo nainstalovat. Instalace bude pokračovat v angličtine.';
$string['memorylimithelp'] = '<p>Limit paměti pro PHP skripty je na vašem serveru momentálně nastaven na hodnotu {$a}.</p>
<p>To může později způsobovat Moodlu problémy, zvláště při větším množství modulů a/nebo uživatelů.</p>
<p>Je-li to možné, doporučujeme vám nastavit v PHP vyšší limit, např. 40M. Můžete to provést několika způsoby:
<ol>
<li>Můžete-li, překompilujte PHP s volbou <i>--enable-memory-limit</i>.
Moodle si tak bude sám moci nastavit potřebný limit.</li>
<li>Máte-li přístup k souboru php.ini, změňte nastavení <b>memory_limit</b>
na hodnotu blízkou 40M. Nemáte-li taková práva, požádejte správce vašeho webového serveru, aby toto nastavení provedl on.</li>
<li>Na některých serverech můžete v kořenovém adresáři Moodlu vytvořit soubor .htaccess s následujícím řádkem:
<p><blockquote>php_value memory_limit 40M</blockquote></p>
<p>Bohužel, v některých případech tím vyřadíte z provozu <b>všechny</b> PHP stránky (při jejich prohlížení uvidíte chybová hlášení), takže budete muset soubor .htaccess zase odstranit.</li>
</ol>';
$string['paths'] = 'Cesty';
$string['pathserrcreatedataroot'] = 'Datový adresář ({$a->dataroot}) nemůže být tímto průvodcem instalací vytvořen.';
$string['pathshead'] = 'Potvrdit cesty';
$string['pathsrodataroot'] = 'Do datového adresáře nelze zapisovat.';
$string['pathsroparentdataroot'] = 'Do nadřazeného adresáře ({$a->parent}) nelze zapisovat. Datový adresář ({$a->dataroot}) nemůže být tímto průvodcem instalací vytvořen.';
$string['pathssubdirroot'] = 'Absolutní cesta k adresáři s instalací Moodle';
$string['pathsunsecuredataroot'] = 'Umístění datového adresáře není bezpečné';
$string['pathswrongadmindir'] = 'Adresář pro správu serveru (admin) neexistuje';
$string['phpextension'] = '{$a} PHP rozšíření';
$string['phpversion'] = 'Verze PHP';
$string['phpversionhelp'] = '<p>Moodle vyžaduje PHP alespoň verze 4.3.0 nebo 5.1.0 (PHP 5.0.x obsahuje množství chyb).</p>
<p>Nyní používáte PHP verze {$a}.</p>
<p>Musíte PHP upgradovat, nebo přejít k hostiteli s vyšší verzí!<br />
(U PHP 5.0.x můžete také přejít na nižší verzi 4.4.x či 4.3.x.)</p>';
$string['welcomep10'] = '{$a->installername} ({$a->installerversion})';
$string['welcomep20'] = 'Podařilo se vám úspěšně nainstalovat a spustit balíček <strong>{$a->packname} {$a->packversion}</strong>. Gratulujeme!';
$string['welcomep30'] = '<strong>{$a->installername}</strong> obsahuje aplikace k vytvoření prostředí, ve kterém bude provozován váš <strong>Moodle</strong>. Jmenovitě se jedná o:';
$string['welcomep40'] = 'Balíček rovněž obsahuje <strong>Moodle ve verzi {$a->moodlerelease} ({$a->moodleversion})</strong>.';
$string['welcomep50'] = 'Použití všech aplikací v tomto balíčku je vázáno jejich příslušnými licencemi. Kompletní balíček <strong>{$a->installername}</strong> je software s <a href="http://www.opensource.org/docs/definition_plain.html"> otevřeným kódem (open source)</a> a je šířen pod licencí <a href="http://www.gnu.org/copyleft/gpl.html">GPL</a>.';
$string['welcomep60'] = 'Následující stránky vás v několik jednoduchých krocích nastavením <strong>Moodlu</strong> na vašem počítači. Můžete přijmout výchozí nastavení, nebo si je upravit podle svých potřeb.';
$string['welcomep70'] = 'Stisknutím níže uvedeného tlačítka "Další" pokračujte v nastavení vaší instalace Moodlu.';
$string['wwwroot'] = 'Webová adresa';
| whitireia/moodle | install/lang/cs/install.php | PHP | gpl-3.0 | 6,437 |
package com.example.questioninterface;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioSource;
import android.os.Environment;
import android.util.Log;
public class AudioRecorder
{
private final static int[] sampleRates = {44100, 22050, 11025, 16000};
public static AudioRecorder getInstanse(Boolean recordingCompressed)
{
AudioRecorder result = null;
if(recordingCompressed)
{
result = new AudioRecorder( false,
AudioSource.MIC,
sampleRates[3],
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
}
else
{
int i=0;
do
{
result = new AudioRecorder( true,
AudioSource.MIC,
sampleRates[i],
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
} while((++i<sampleRates.length) & !(result.getState() == AudioRecorder.State.INITIALIZING));
}
return result;
}
/**
* INITIALIZING : recorder is initialising;
* READY : recorder has been initialised, recorder not yet started
* RECORDING : recording
* ERROR : reconstruction needed
* STOPPED: reset needed
*/
public enum State {INITIALIZING, READY, RECORDING, ERROR, STOPPED};
public static final boolean RECORDING_UNCOMPRESSED = true;
public static final boolean RECORDING_COMPRESSED = false;
// The interval in which the recorded samples are output to the file
// Used only in uncompressed mode
private static final int TIMER_INTERVAL = 120;
// Toggles uncompressed recording on/off; RECORDING_UNCOMPRESSED / RECORDING_COMPRESSED
private boolean rUncompressed;
// Recorder used for uncompressed recording
private AudioRecord audioRecorder = null;
// Recorder used for compressed recording
private MediaRecorder mediaRecorder = null;
// Stores current amplitude (only in uncompressed mode)
private int cAmplitude= 0;
// Output file path
private String filePath = null;
// Recorder state; see State
private State state;
// File writer (only in uncompressed mode)
private RandomAccessFile randomAccessWriter;
// Number of channels, sample rate, sample size(size in bits), buffer size, audio source, sample size(see AudioFormat)
private short nChannels;
private int sRate;
private short bSamples;
private int bufferSize;
private int aSource;
private int aFormat;
// Number of frames written to file on each output(only in uncompressed mode)
private int framePeriod;
// Buffer for output(only in uncompressed mode)
private byte[] buffer;
// Number of bytes written to file after header(only in uncompressed mode)
// after stop() is called, this size is written to the header/data chunk in the wave file
private int payloadSize;
/**
*
* Returns the state of the recorder in a RehearsalAudioRecord.State typed object.
* Useful, as no exceptions are thrown.
*
* @return recorder state
*/
public State getState()
{
return state;
}
/*
*
* Method used for recording.
*/
private AudioRecord.OnRecordPositionUpdateListener updateListener = new AudioRecord.OnRecordPositionUpdateListener()
{
public void onPeriodicNotification(AudioRecord recorder)
{
audioRecorder.read(buffer, 0, buffer.length); // Fill buffer
try
{
randomAccessWriter.write(buffer); // Write buffer to file
payloadSize += buffer.length;
if (bSamples == 16)
{
for (int i=0; i<buffer.length/2; i++)
{ // 16bit sample size
short curSample = getShort(buffer[i*2], buffer[i*2+1]);
if (curSample > cAmplitude)
{ // Check amplitude
cAmplitude = curSample;
}
}
}
else
{ // 8bit sample size
for (int i=0; i<buffer.length; i++)
{
if (buffer[i] > cAmplitude)
{ // Check amplitude
cAmplitude = buffer[i];
}
}
}
}
catch (IOException e)
{
Log.e(AudioRecorder.class.getName(), "Error occured in updateListener, recording is aborted");
//stop();
}
}
public void onMarkerReached(AudioRecord recorder)
{
// NOT USED
}
};
/**
*
*
* Default constructor
*
* Instantiates a new recorder, in case of compressed recording the parameters can be left as 0.
* In case of errors, no exception is thrown, but the state is set to ERROR
*
*/
public AudioRecorder(boolean uncompressed, int audioSource, int sampleRate, int channelConfig, int audioFormat)
{
Log.d("Tag", ".......................Calling the class here");
try
{
rUncompressed = uncompressed;
if (rUncompressed)
{ // RECORDING_UNCOMPRESSED
if (audioFormat == AudioFormat.ENCODING_PCM_16BIT)
{
bSamples = 16;
}
else
{
bSamples = 8;
}
if (channelConfig == AudioFormat.CHANNEL_CONFIGURATION_MONO)
{
nChannels = 1;
}
else
{
nChannels = 2;
}
aSource = audioSource;
sRate = sampleRate;
aFormat = audioFormat;
framePeriod = sampleRate * TIMER_INTERVAL / 1000;
bufferSize = framePeriod * 2 * bSamples * nChannels / 8;
if (bufferSize < AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat))
{ // Check to make sure buffer size is not smaller than the smallest allowed one
bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
// Set frame period and timer interval accordingly
framePeriod = bufferSize / ( 2 * bSamples * nChannels / 8 );
Log.w(AudioRecorder.class.getName(), "Increasing buffer size to " + Integer.toString(bufferSize));
}
audioRecorder = new AudioRecord(audioSource, sampleRate, channelConfig, audioFormat, bufferSize);
if (audioRecorder.getState() != AudioRecord.STATE_INITIALIZED)
throw new Exception("AudioRecord initialization failed");
audioRecorder.setRecordPositionUpdateListener(updateListener);
audioRecorder.setPositionNotificationPeriod(framePeriod);
} else
{ // RECORDING_COMPRESSED
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
cAmplitude = 0;
filePath = null;
state = State.INITIALIZING;
} catch (Exception e)
{
if (e.getMessage() != null)
{
Log.e(AudioRecorder.class.getName(), e.getMessage());
}
else
{
Log.e(AudioRecorder.class.getName(), "Unknown error occured while initializing recording");
}
state = State.ERROR;
}
}
/**
* Sets output file path, call directly after construction/reset.
*
* @param output file path
*
*/
public void setOutputFile(String filename)
{
try
{
if (state == State.INITIALIZING)
{
// filePath = argPath;
/** Save the recording to SD card */
filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
//File mydir = new File(filePath + "Answers");
//if(!mydir.exists()) {
// mydir.mkdirs();
//}
filePath += "/Answers/" + filename + ".wav";
Log.d("Outfilepath---------------", filePath);
if (!rUncompressed)
{
mediaRecorder.setOutputFile(filePath);
}
}
}
catch (Exception e)
{
if (e.getMessage() != null)
{
Log.e(AudioRecorder.class.getName(), e.getMessage());
}
else
{
Log.e(AudioRecorder.class.getName(), "Unknown error occured while setting output path");
}
state = State.ERROR;
}
}
/**
*
* Returns the largest amplitude sampled since the last call to this method.
*
* @return returns the largest amplitude since the last call, or 0 when not in recording state.
*
*/
public int getMaxAmplitude()
{
if (state == State.RECORDING)
{
if (rUncompressed)
{
int result = cAmplitude;
cAmplitude = 0;
return result;
}
else
{
try
{
return mediaRecorder.getMaxAmplitude();
}
catch (IllegalStateException e)
{
return 0;
}
}
}
else
{
return 0;
}
}
/**
*
* Prepares the recorder for recording, in case the recorder is not in the INITIALIZING state and the file path was not set
* the recorder is set to the ERROR state, which makes a reconstruction necessary.
* In case uncompressed recording is toggled, the header of the wave file is written.
* In case of an exception, the state is changed to ERROR
*
*/
public void prepare()
{
try
{
if (state == State.INITIALIZING)
{
if (rUncompressed)
{
if ((audioRecorder.getState() == AudioRecord.STATE_INITIALIZED) & (filePath != null))
{
// write file header
randomAccessWriter = new RandomAccessFile(filePath, "rw");
randomAccessWriter.setLength(0); // Set file length to 0, to prevent unexpected behaviour in case the file already existed
randomAccessWriter.writeBytes("RIFF");
randomAccessWriter.writeInt(0); // Final file size not known yet, write 0
randomAccessWriter.writeBytes("WAVE");
randomAccessWriter.writeBytes("fmt ");
randomAccessWriter.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
randomAccessWriter.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
randomAccessWriter.writeShort(Short.reverseBytes(nChannels));// Number of channels, 1 for mono, 2 for stereo
randomAccessWriter.writeInt(Integer.reverseBytes(sRate)); // Sample rate
randomAccessWriter.writeInt(Integer.reverseBytes(sRate*bSamples*nChannels/8)); // Byte rate, SampleRate*NumberOfChannels*BitsPerSample/8
randomAccessWriter.writeShort(Short.reverseBytes((short)(nChannels*bSamples/8))); // Block align, NumberOfChannels*BitsPerSample/8
randomAccessWriter.writeShort(Short.reverseBytes(bSamples)); // Bits per sample
randomAccessWriter.writeBytes("data");
randomAccessWriter.writeInt(0); // Data chunk size not known yet, write 0
buffer = new byte[framePeriod*bSamples/8*nChannels];
state = State.READY;
}
else
{
Log.e(AudioRecorder.class.getName(), "prepare() method called on uninitialized recorder");
state = State.ERROR;
}
}
else
{
mediaRecorder.prepare();
state = State.READY;
}
}
else
{
Log.e(AudioRecorder.class.getName(), "prepare() method called on illegal state");
release();
state = State.ERROR;
}
}
catch(Exception e)
{
if (e.getMessage() != null)
{
Log.e(AudioRecorder.class.getName(), e.getMessage());
}
else
{
Log.e(AudioRecorder.class.getName(), "Unknown error occured in prepare()");
}
state = State.ERROR;
}
}
/**
*
*
* Releases the resources associated with this class, and removes the unnecessary files, when necessary
*
*/
public void release()
{
if (state == State.RECORDING)
{
stop();
}
else
{
if ((state == State.READY) & (rUncompressed))
{
try
{
randomAccessWriter.close(); // Remove prepared file
}
catch (IOException e)
{
Log.e(AudioRecorder.class.getName(), "I/O exception occured while closing output file");
}
(new File(filePath)).delete();
}
}
if (rUncompressed)
{
if (audioRecorder != null)
{
audioRecorder.release();
}
}
else
{
if (mediaRecorder != null)
{
mediaRecorder.release();
}
}
}
/**
*
*
* Resets the recorder to the INITIALIZING state, as if it was just created.
* In case the class was in RECORDING state, the recording is stopped.
* In case of exceptions the class is set to the ERROR state.
*
*/
public void reset()
{
try
{
if (state != State.ERROR)
{
release();
filePath = null; // Reset file path
cAmplitude = 0; // Reset amplitude
if (rUncompressed)
{
audioRecorder = new AudioRecord(aSource, sRate, nChannels+1, aFormat, bufferSize);
}
else
{
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
state = State.INITIALIZING;
}
}
catch (Exception e)
{
Log.e(AudioRecorder.class.getName(), e.getMessage());
state = State.ERROR;
}
}
/**
*
*
* Starts the recording, and sets the state to RECORDING.
* Call after prepare().
*
*/
public void start()
{
if (state == State.READY)
{
if (rUncompressed)
{
payloadSize = 0;
audioRecorder.startRecording();
audioRecorder.read(buffer, 0, buffer.length);
}
else
{
mediaRecorder.start();
}
state = State.RECORDING;
}
else
{
Log.e(AudioRecorder.class.getName(), "start() called on illegal state");
state = State.ERROR;
}
}
/**
*
*
* Stops the recording, and sets the state to STOPPED.
* In case of further usage, a reset is needed.
* Also finalizes the wave file in case of uncompressed recording.
*
*/
public void stop()
{
if (state == State.RECORDING)
{
if (rUncompressed)
{
audioRecorder.stop();
try
{
randomAccessWriter.seek(4); // Write size to RIFF header
randomAccessWriter.writeInt(Integer.reverseBytes(36+payloadSize));
randomAccessWriter.seek(40); // Write size to Subchunk2Size field
randomAccessWriter.writeInt(Integer.reverseBytes(payloadSize));
randomAccessWriter.close();
}
catch(IOException e)
{
Log.e(AudioRecorder.class.getName(), "I/O exception occured while closing output file");
state = State.ERROR;
}
}
else
{
mediaRecorder.stop();
}
state = State.STOPPED;
}
else
{
Log.e(AudioRecorder.class.getName(), "stop() called on illegal state");
state = State.ERROR;
}
}
/*
*
* Converts a byte[2] to a short, in LITTLE_ENDIAN format
*
*/
private short getShort(byte argB1, byte argB2)
{
return (short)(argB1 | (argB2 << 8));
}
}
| sirisharallabandi/Voice_Recorder | QuestionInterface/QuestionInterface/src/com/example/questioninterface/AudioRecorder.java | Java | gpl-3.0 | 18,760 |
namespace Mine.NET.conversations;
import org.bukkit.plugin.Plugin;
import java.util.List;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The Conversation class is responsible for tracking the current state of a
* conversation, displaying prompts to the user, and dispatching the user's
* response to the appropriate place. Conversation objects are not typically
* instantiated directly. Instead a {@link ConversationFactory} is used to
* construct identical conversations on demand.
* <p>
* Conversation flow consists of a directed graph of {@link Prompt} objects.
* Each time a prompt gets input from the user, it must return the next prompt
* in the graph. Since each Prompt chooses the next Prompt, complex
* conversation trees can be implemented where the nature of the player's
* response directs the flow of the conversation.
* <p>
* Each conversation has a {@link ConversationPrefix} that prepends all output
* from the conversation to the player. The ConversationPrefix can be used to
* display the plugin name or conversation status as the conversation evolves.
* <p>
* Each conversation has a timeout measured in the number of inactive seconds
* to wait before abandoning the conversation. If the inactivity timeout is
* reached, the conversation is abandoned and the user's incoming and outgoing
* chat is returned to normal.
* <p>
* You should not construct a conversation manually. Instead, use the {@link
* ConversationFactory} for access to all available options.
*/
public class Conversation {
private Prompt firstPrompt;
private bool abandoned;
protected Prompt currentPrompt;
protected ConversationContext context;
protected bool modal;
protected bool localEchoEnabled;
protected ConversationPrefix prefix;
protected List<ConversationCanceller> cancellers;
protected List<ConversationAbandonedListener> abandonedListeners;
/**
* Initializes a new Conversation.
*
* @param plugin The plugin that owns this conversation.
* @param forWhom The entity for whom this conversation is mediating.
* @param firstPrompt The first prompt in the conversation graph.
*/
public Conversation(Plugin plugin, Conversable forWhom, Prompt firstPrompt) {
this(plugin, forWhom, firstPrompt, new Dictionary<Object, Object>());
}
/**
* Initializes a new Conversation.
*
* @param plugin The plugin that owns this conversation.
* @param forWhom The entity for whom this conversation is mediating.
* @param firstPrompt The first prompt in the conversation graph.
* @param initialSessionData Any initial values to put in the conversation
* context sessionData map.
*/
public Conversation(Plugin plugin, Conversable forWhom, Prompt firstPrompt, Dictionary<Object, Object> initialSessionData) {
this.firstPrompt = firstPrompt;
this.context = new ConversationContext(plugin, forWhom, initialSessionData);
this.modal = true;
this.localEchoEnabled = true;
this.prefix = new NullConversationPrefix();
this.cancellers = new List<ConversationCanceller>();
this.abandonedListeners = new List<ConversationAbandonedListener>();
}
/**
* Gets the entity for whom this conversation is mediating.
*
* @return The entity.
*/
public Conversable getForWhom() {
return context.getForWhom();
}
/**
* Gets the modality of this conversation. If a conversation is modal, all
* messages directed to the player are suppressed for the duration of the
* conversation.
*
* @return The conversation modality.
*/
public bool isModal() {
return modal;
}
/**
* Sets the modality of this conversation. If a conversation is modal,
* all messages directed to the player are suppressed for the duration of
* the conversation.
*
* @param modal The new conversation modality.
*/
void setModal(bool modal) {
this.modal = modal;
}
/**
* Gets the status of local echo for this conversation. If local echo is
* enabled, any text submitted to a conversation gets echoed back into the
* submitter's chat window.
*
* @return The status of local echo.
*/
public bool isLocalEchoEnabled() {
return localEchoEnabled;
}
/**
* Sets the status of local echo for this conversation. If local echo is
* enabled, any text submitted to a conversation gets echoed back into the
* submitter's chat window.
*
* @param localEchoEnabled The status of local echo.
*/
public void setLocalEchoEnabled(bool localEchoEnabled) {
this.localEchoEnabled = localEchoEnabled;
}
/**
* Gets the {@link ConversationPrefix} that prepends all output from this
* conversation.
*
* @return The ConversationPrefix in use.
*/
public ConversationPrefix getPrefix() {
return prefix;
}
/**
* Sets the {@link ConversationPrefix} that prepends all output from this
* conversation.
*
* @param prefix The ConversationPrefix to use.
*/
void setPrefix(ConversationPrefix prefix) {
this.prefix = prefix;
}
/**
* Adds a {@link ConversationCanceller} to the cancellers collection.
*
* @param canceller The {@link ConversationCanceller} to add.
*/
void addConversationCanceller(ConversationCanceller canceller) {
canceller.setConversation(this);
this.cancellers.add(canceller);
}
/**
* Gets the list of {@link ConversationCanceller}s
*
* @return The list.
*/
public List<ConversationCanceller> getCancellers() {
return cancellers;
}
/**
* Returns the Conversation's {@link ConversationContext}.
*
* @return The ConversationContext.
*/
public ConversationContext getContext() {
return context;
}
/**
* Displays the first prompt of this conversation and begins redirecting
* the user's chat responses.
*/
public void begin() {
if (currentPrompt == null) {
abandoned = false;
currentPrompt = firstPrompt;
context.getForWhom().beginConversation(this);
}
}
/**
* Returns Returns the current state of the conversation.
*
* @return The current state of the conversation.
*/
public ConversationState getState() {
if (currentPrompt != null) {
return ConversationState.STARTED;
} else if (abandoned) {
return ConversationState.ABANDONED;
} else {
return ConversationState.UNSTARTED;
}
}
/**
* Passes player input into the current prompt. The next prompt (as
* determined by the current prompt) is then displayed to the user.
*
* @param input The user's chat text.
*/
public void acceptInput(String input) {
if (currentPrompt != null) {
// Echo the user's input
if (localEchoEnabled) {
context.getForWhom().sendRawMessage(prefix.getPrefix(context) + input);
}
// Test for conversation abandonment based on input
foreach (ConversationCanceller canceller in cancellers) {
if (canceller.cancelBasedOnInput(context, input)) {
abandon(new ConversationAbandonedEvent(this, canceller));
return;
}
}
// Not abandoned, output the next prompt
currentPrompt = currentPrompt.acceptInput(context, input);
outputNextPrompt();
}
}
/**
* Adds a {@link ConversationAbandonedListener}.
*
* @param listener The listener to add.
*/
public synchronized void addConversationAbandonedListener(ConversationAbandonedListener listener) {
abandonedListeners.add(listener);
}
/**
* Removes a {@link ConversationAbandonedListener}.
*
* @param listener The listener to remove.
*/
public synchronized void removeConversationAbandonedListener(ConversationAbandonedListener listener) {
abandonedListeners.remove(listener);
}
/**
* Abandons and resets the current conversation. Restores the user's
* normal chat behavior.
*/
public void abandon() {
abandon(new ConversationAbandonedEvent(this, new ManuallyAbandonedConversationCanceller()));
}
/**
* Abandons and resets the current conversation. Restores the user's
* normal chat behavior.
*
* @param details Details about why the conversation was abandoned
*/
public synchronized void abandon(ConversationAbandonedEvent details) {
if (!abandoned) {
abandoned = true;
currentPrompt = null;
context.getForWhom().abandonConversation(this);
foreach (ConversationAbandonedListener listener in abandonedListeners) {
listener.conversationAbandoned(details);
}
}
}
/**
* Displays the next user prompt and abandons the conversation if the next
* prompt is null.
*/
public void outputNextPrompt() {
if (currentPrompt == null) {
abandon(new ConversationAbandonedEvent(this));
} else {
context.getForWhom().sendRawMessage(prefix.getPrefix(context) + currentPrompt.getPromptText(context));
if (!currentPrompt.blocksForInput(context)) {
currentPrompt = currentPrompt.acceptInput(context, null);
outputNextPrompt();
}
}
}
public enum ConversationState {
UNSTARTED,
STARTED,
ABANDONED
}
}
| NorbiPeti/Mine.NET | Mine.NET/conversations/Conversation.java.cs | C# | gpl-3.0 | 9,853 |
-- Based on the same bricks as the regular cargo mission
include "cargo_common.lua"
include "numstring.lua"
-- A set of GLOBAL variables properly named to save the event parameters
evtSave_System = nil
evtSave_RefPlanet = nil
evtSave_CommodityName = nil
evtSave_OriginalPrice = 0
evtSave_OriginalPriceSet = true
evtSave_EventPrice = 0
evtSave_TimerMin = 0
evtSave_TimerMax = 0
lang = naev.lang()
if lang == 'es' then --not translated atm
else --default english
events = {
{
{"famine", "Famine"}, --event name/type
{3,5}, --prices begin to return to normal in 5-10 STP
{"Food", 2.0}, --commodity and it's new price relative to the old one
50 -- Percentage of event being selected if match
},
{
{"bumper harvest", "Bumper Harvest"},
{3,5},
{"Food", .5},
50
},
{
{"workers' strike","Workers' Strike"},
{3,5},
{"Goods", 1.5},
50
},
{
{"miners' strike","Miners' Strike"},
{3,5},
{"Ore", 1.5},
50
},
{
{"cat convention","Cat Convention"},
{3,5},
{"Medicine",1.25},
50
},
{
{"disease outbreak","Disease Outbreak"},
{3,5},
{"Medicine",2.5},
50
}
}
end
function create()
make_event()
evt.save(true)
end
-- Make the news event for the selected event and system
function make_article(sys, event, evtSave_CommodityName)
-- Local variables
local body = ""
local title = ""
local timer = nil
-- Set event parameters
title = event[1][2].." on "..sys:name()
body = "System "..sys:name().." recently experienced a "..event[1][1]..", changing "
timer = time.create(0,event[2][2],0)+time.get() -- Mark maximum timer for removing the event
-- Say how the prices have changed
body = body.."the price of "..evtSave_CommodityName..string.format(" from %.0f credits per ton to %.0f.",math.abs(evtSave_OriginalPrice),econ.getPrice(evtSave_CommodityName, sys))
body = body.." Prices are expected to begin to settle around "..timer:str()
-- Make the article
article = news.add("Generic", title, body, timer)
article:bind("economic event")
end
-- Make a single economic event
function make_event()
-- Local variables
local traveldist = 0
local tier = 0
local numjumps = 0
local eventEnd = 0
-- Debug printout
-- print ( string.format ( "\tEconomic Event : entering make_event()" ) )
-- Calculate the route, distance, jumps and cargo to take
-- Seect the commodity from those sold at the target planet
-- This way, we always use an existing good on at least one planet in the target system
evtSave_RefPlanet, evtSave_System, numjumps, traveldist, evtSave_CommodityName, tier = cargo_calculateRoute(true)
if evtSave_RefPlanet == nil then
-- print ( string.format ( "\tEconomic Event : no suitable reference destination planet found" ) )
evt.finish(false)
return
end
-- print ( string.format ( "\tEconomic Event : selected system \"%s\"", evtSave_System:name() ) )
-- Prevent a system from having multiple events
economic_articles = news.get("economic events")
for i=1,#economic_articles do
if string.match( article:title(), evtSave_System:name()) then
-- print ( string.format ( "\tEconomic Event : system \"%s\" is already taken", evtSave_System:name() ) )
evt.finish(false)
return
end
end
-- Get the corresponding event
local found = false
local event = nil
local comm_name = ""
local multiplier = 1
local keyword = ""
for i=1,#events do
event = events[i]
for j=3,#event-1 do
keyword = event[j][1]
if string.match( evtSave_CommodityName, keyword ) then
-- print ( string.format ( "\tEconomic Event : \tkeyword \"%s\" matches against comodity name \"%s\"", keyword, evtSave_CommodityName ) )
if rnd.rnd()*100 < event[#event] then
-- print ( string.format ( "\tEconomic Event : \t\tevent selected, chances were %i%%.", event[#event] ) )
found = true
comm_name = evtSave_CommodityName
multiplier = event[j][2]
break
else
-- print ( string.format ( "\tEconomic Event : \t\tevent rejected, chances were %i%%.", event[#event] ) )
end
else
-- print ( string.format ( "\tEconomic Event : \tkeyword \"%s\" does not match against comodity name \"%s\"", keyword, evtSave_CommodityName ) )
end
end
if found then
break
end
end
if not found then
-- print ( string.format ( "\tEconomic Event : no event selected." ) )
evt.finish(false)
return
end
-- Debug printout
-- print ( string.format ( "\tEconomic Event : creating event \"%s\" in system \"%s\"", event[1][1], evtSave_System:name() ) )
-- Setup new prie, update prices and make the article
evtSave_OriginalPrice = econ.getPrice(comm_name, evtSave_System)
evtSave_OriginalPriceSet = econ.isPriceSet(comm_name, evtSave_System)
evtSave_EventPrice = evtSave_OriginalPrice*multiplier
econ.setPrice(comm_name, evtSave_System, evtSave_EventPrice)
-- econ.updatePrices() -- Remove to prevent extra CPU usage
make_article(evtSave_System, event, evtSave_CommodityName)
--set up the event ending and save timer parameters
evtSave_TimerMin = event[2][1]
evtSave_TimerMax = event[2][2]
local evtTimer = rnd.rnd(event[2][1], event[2][2])
hook.date( time.create(0, evtTimer, 0), "adjustPrices", str )
-- Debug printout
-- print ( string.format ( "\tEconomic Event : exiting make_event()" ) )
end
-- May end the event, returning the price to its original value
-- or may only reduce prie difference to make it more progressive
function adjustPrices(str)
-- First get all the information we'll need
local commodity = commodity.get(evtSave_CommodityName)
local currentPrice = econ.getPrice(commodity, evtSave_System)
local currentPriceDiff = currentPrice - evtSave_OriginalPrice
local originalPriceDiff = evtSave_EventPrice - evtSave_OriginalPrice
-- Debug printout
-- print ( string.format ( "\tEconEvent End : entering regulation hook." ) )
-- print ( string.format ( "\tEconEvent End : \tSystem = \"%s\".", evtSave_System:name() ) )
-- print ( string.format ( "\tEconEvent End : \tRef Planet = \"%s\".", evtSave_RefPlanet:name() ) )
-- print ( string.format ( "\tEconEvent End : \tCommodity = \"%s\"", evtSave_CommodityName ) )
-- print ( string.format ( "\tEconEvent End : \t\tPrices :" ) )
-- print ( string.format ( "\tEconEvent End : \t\t\tOriginal = %f.", evtSave_OriginalPrice ) )
-- print ( string.format ( "\tEconEvent End : \t\t\tEvent = %f.", evtSave_EventPrice ) )
-- print ( string.format ( "\tEconEvent End : \t\t\tCurrent = %f.", currentPrice ) )
-- print ( string.format ( "\tEconEvent End : \t\tDiffs :" ) )
-- print ( string.format ( "\tEconEvent End : \t\t\tOriginal = %f.", originalPriceDiff ) )
-- print ( string.format ( "\tEconEvent End : \t\t\tCurrent = %f.", currentPriceDiff ) )
if math.abs(currentPriceDiff) > math.abs(originalPriceDiff)*0.1 then
-- Set intermdiate price
local newPriceDiff = currentPriceDiff * 0.5
econ.setPrice(commodity, evtSave_System, evtSave_OriginalPrice+newPriceDiff)
-- print ( string.format ( "\tEconEvent End : \thalving price difference from %f (%f-%f) to %f (%f-%f).", currentPriceDiff, currentPrice, evtSave_OriginalPrice, newPriceDiff, evtSave_OriginalPrice+newPriceDiff, evtSave_OriginalPrice ) )
-- Set a timer for further price regulation
local evtTimer = rnd.rnd(evtSave_TimerMin, evtSave_TimerMax)
hook.date( time.create(0, evtTimer, 0), "adjustPrices", str )
else
-- Reset prices to their original states
if evtSave_OriginalPriceSet then
econ.unsetPrice(commodity, evtSave_System)
-- print ( string.format ( "\tEconEvent End : unsetting price." ) )
else
econ.setPrice(commodity, evtSave_System, evtSave_OriginalPrice)
-- print ( string.format ( "\tEconEvent End : restoring price." ) )
end
-- Finish the event
-- print ( string.format ( "\tEconEvent End : closing and exiting regulation hook." ) )
evt.finish()
end
-- print ( string.format ( "\tEconEvent End : exiting regulation hook." ) )
end
| Mutos/StarsOfCall-NAEV | dat/events/economy/base_econ_events.lua | Lua | gpl-3.0 | 8,171 |
LogServer
=========
Antergos LogServer BackEnd
# Dependencies
* mongodb
* mongojs
* request
| Antergos/LogServer | Backend/README.md | Markdown | gpl-3.0 | 94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.