repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
grevit-dev/DynamoPDF | DynamoPDF/Content/Annotation.cs | 8157 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.DesignScript.Geometry;
using iTextSharp.text.pdf;
using Autodesk.DesignScript.Runtime;
using Autodesk.DesignScript.Geometry;
namespace DynamoPDF.Content
{
/// <summary>
/// Annotation Object
/// </summary>
public class Annotation
{
/// <summary>
/// Date Created
/// </summary>
private DateTime Created;
/// <summary>
/// Date Updated
/// </summary>
private DateTime Updated;
/// <summary>
/// Contents
/// </summary>
private string Contents;
/// <summary>
/// Author
/// </summary>
private string Author;
/// <summary>
/// Dynamo Geometry
/// </summary>
private Geometry Geometry;
/// <summary>
/// Subject
/// </summary>
private string Subject;
/// <summary>
/// Color
/// </summary>
private DSCore.Color Color;
/// <summary>
/// Get Annotation Color
/// </summary>
public DSCore.Color GetColor { get { return this.Color; } }
/// <summary>
/// Get Subject
/// </summary>
public string GetSubject { get { return this.Subject; } }
/// <summary>
/// Get Author
/// </summary>
public string GetAuthor { get { return this.Author; } }
/// <summary>
/// Get Contents
/// </summary>
public string GetContents { get { return this.Contents; } }
/// <summary>
/// Get Updated Date
/// </summary>
public DateTime GetUpdated { get { return this.Updated; } }
/// <summary>
/// Get Created Date
/// </summary>
public DateTime GetCreated { get { return this.Created; } }
/// <summary>
/// Get Geometry
/// </summary>
public Geometry GetGeometry { get { return this.Geometry; } }
/// <summary>
/// Annotation Object
/// </summary>
/// <param name="created"></param>
/// <param name="updated"></param>
/// <param name="contents"></param>
/// <param name="author"></param>
/// <param name="geometry"></param>
public Annotation(string contents, string author, string subject,Geometry geometry, DSCore.Color color)
{
this.Created = DateTime.Now;
this.Updated = DateTime.Now;
this.Contents = contents;
this.Author = author;
this.Geometry = geometry;
this.Color = color;
this.Subject = subject;
}
/// <summary>
/// Annotation Object
/// </summary>
/// <param name="annotation"></param>
/// <param name="geometry"></param>
[IsVisibleInDynamoLibrary(false)]
public Annotation(PdfDictionary annotation, Geometry geometry)
{
this.Geometry = geometry;
PdfString createdString = annotation.GetAsString(PdfName.CREATIONDATE);
this.Created = (createdString == null) ? DateTime.MinValue : createdString.ToString().ToDateTime();
PdfString updatedString = annotation.GetAsString(PdfName.M);
this.Updated = (updatedString == null) ? DateTime.MinValue : updatedString.ToString().ToDateTime();
PdfString contents = annotation.GetAsString(PdfName.CONTENTS);
this.Contents = (contents == null) ? string.Empty : contents.ToString();
PdfString author = annotation.GetAsString(PdfName.T);
this.Author = (author == null) ? string.Empty : author.ToString();
PdfString subject = annotation.GetAsString(PdfName.SUBJECT);
this.Subject = (subject == null) ? string.Empty : subject.ToString();
PdfArray color = annotation.GetAsArray(PdfName.C);
if (color != null && color.Size == 3)
{
var pdfcolor = new iTextSharp.text.BaseColor(color[0].ToFloat(), color[1].ToFloat(), color[2].ToFloat());
this.Color = pdfcolor.ToDSColor();
}
if (this.Color == null)
{
PdfString ds = annotation.GetAsString(PdfName.DS);
//font: Helvetica 12pt; text-align:left; margin:3pt; line-height:13.8pt; color:#000000
if (ds != null)
{
if (ds.ToString().Contains(';'))
{
string[] data = ds.ToString().Split(';');
Dictionary<string, string> datadict = new Dictionary<string, string>();
foreach (string d in data)
{
if (d.Contains(':'))
{
string[] vp = d.Split(':');
string key = vp[0].Replace(" ", "");
string val = vp[1].Replace(" ", "");
if (!datadict.ContainsKey(key))
datadict.Add(key, val);
}
}
if (datadict.ContainsKey("color"))
{
var syscolor = System.Drawing.ColorTranslator.FromHtml(datadict["color"].ToUpper());
if (syscolor != null)
this.Color = DSCore.Color.ByARGB(syscolor.A, syscolor.R, syscolor.G, syscolor.B);
}
}
}
if (this.Color == null)
this.Color = DSCore.Color.ByARGB(255, 255, 0, 0);
}
}
/// <summary>
/// Stamp Annotation to PDF
/// </summary>
/// <param name="stamper"></param>
/// <param name="page"></param>
/// <param name="scale"></param>
[IsVisibleInDynamoLibrary(false)]
public void StampAnnotation(PdfStamper stamper, int page, double scale)
{
PdfAnnotation annotation = null;
if (Geometry == null)
{
throw new Exception(Properties.Resources.NoGeometry);
}
else if (Geometry.GetType() == typeof(Autodesk.DesignScript.Geometry.Line))
{
var line = Geometry as Autodesk.DesignScript.Geometry.Line;
annotation = line.ToPDFLine(Contents, stamper.Writer);
}
else if (Geometry.GetType() == typeof(Autodesk.DesignScript.Geometry.Polygon))
{
var polygon = Geometry as Autodesk.DesignScript.Geometry.Polygon;
annotation = polygon.ToPDFPolygon(Contents, stamper.Writer);
}
else if (Geometry.GetType() == typeof(Autodesk.DesignScript.Geometry.PolyCurve))
{
var polycurve = Geometry as Autodesk.DesignScript.Geometry.PolyCurve;
annotation = polycurve.ToPDFPolygon(Contents, stamper.Writer);
}
else if (Geometry.GetType() == typeof(Autodesk.DesignScript.Geometry.Circle))
{
var circle = Geometry as Autodesk.DesignScript.Geometry.Circle;
annotation = circle.ToPDFCircle(Contents, stamper.Writer);
}
else
{
throw new Exception(Properties.Resources.NotSupported);
}
annotation.Put(PdfName.T, new PdfString(Author));
annotation.Put(PdfName.M, new PdfDate(DateTime.Now));
annotation.Put(PdfName.CREATIONDATE, new PdfDate(DateTime.Now));
annotation.Put(PdfName.CONTENTS, new PdfString(Contents));
float[] floatdata = { Convert.ToSingle(Color.Red), Convert.ToSingle(Color.Green), Convert.ToSingle(Color.Blue)};
annotation.Put(PdfName.C, new PdfArray(floatdata));
stamper.AddAnnotation(annotation, page);
}
}
}
| gpl-3.0 |
GustavoPB/CeCe | cece/plugins/python/Program.hpp | 3507 | /* ************************************************************************ */
/* Georgiev Lab (c) 2015 */
/* ************************************************************************ */
/* Department of Cybernetics */
/* Faculty of Applied Sciences */
/* University of West Bohemia in Pilsen */
/* ************************************************************************ */
/* */
/* This file is part of CeCe. */
/* */
/* CeCe 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. */
/* */
/* CeCe 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 CeCe. If not, see <http://www.gnu.org/licenses/>. */
/* */
/* ************************************************************************ */
#pragma once
/* ************************************************************************ */
// This must be first
#include "cece/plugins/python/Python.hpp"
// CeCe
#include "cece/core/Units.hpp"
#include "cece/program/Program.hpp"
// Plugin
#include "cece/plugins/python/Source.hpp"
/* ************************************************************************ */
namespace cece {
namespace plugin {
namespace python {
/* ************************************************************************ */
/**
* @brief Simple wrapper functor for Python code.
*/
class Program : public program::Program
{
// Public Operations
public:
/**
* @brief Clone program.
*
* @return
*/
UniquePtr<program::Program> clone() const override;
/**
* @brief Load program configuration.
*
* @param simulation Current simulation.
* @param config Source configuration.
*/
void loadConfig(simulator::Simulation& simulation, const config::Configuration& config) override;
/**
* @brief Call program for given object.
*
* @param simulation Simulation object.
* @param object Object.
* @param dt Simulation time step.
*/
void call(simulator::Simulation& simulation, object::Object& object, units::Time dt) override;
// Private Data Members
private:
/// Source.
Source m_source;
/// Call function.
Handle<PyObject> m_call;
};
/* ************************************************************************ */
}
}
}
/* ************************************************************************ */
| gpl-3.0 |
toxicaliens/hsmis | resources/views/layouts/wizard.blade.php | 6534 | <!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield('title') | Test</title>
<!-- Bootstrap -->
<link href="assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
<!-- Select2 -->
<link href="assets/select2/dist/css/select2.min.css" rel="stylesheet">
<!-- Custom Theme Style -->
<link href="css/custom.css" rel="stylesheet">
<link href="assets/bootstrap-fileupload/bootstrap-fileupload.css" rel="stylesheet">
@stack('css')
</head>
<body class="nav-md">
<div class="container body">
<div class="main_container">
<div class="col-md-3 left_col">
<div class="left_col scroll-view">
<!-- menu profile quick info -->
@include('layouts.includes.quickinfo')
<!-- /menu profile quick info -->
<br />
<!-- sidebar menu -->
@include('layouts.includes.sidebar_menu')
<!-- /sidebar menu -->
<!-- /menu footer buttons -->
@include('layouts.includes.menu_footer_buttons')
<!-- /menu footer buttons -->
</div>
</div>
<!-- top navigation -->
@include('layouts.includes.top_nav')
<!-- /top navigation -->
<!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="page-title">
<div class="title_left">
<h3>
@yield('page-title')
<small>
@yield('page-desc')
</small>
</h3>
</div>
@include('layouts.includes.search')
</div>
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
@yield('content')
</div>
</div>
</div>
<!-- /page content -->
<!-- footer content -->
@include('layouts.includes.footer')
<!-- /footer content -->
</div>
</div>
<!-- jQuery -->
<script src="assets/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="assets/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- FastClick -->
<script src="assets/fastclick/lib/fastclick.js"></script>
<!-- NProgress -->
<script src="assets/nprogress/nprogress.js"></script>
<!-- jQuery Smart Wizard -->
<script src="assets/jQuery-Smart-Wizard/js/jquery.smartWizard.js"></script>
<!-- Custom Theme Scripts -->
<script src="js/custom.js"></script>
<!-- validator -->
<script src="assets/validator/validator.min.js"></script>
<!-- bootstrap-daterangepicker -->
<script src="js/moment/moment.min.js"></script>
<script src="js/datepicker/daterangepicker.js"></script>
<!-- Select2 -->
<script src="assets/select2/dist/js/select2.full.min.js"></script>
<!-- validator -->
<script src="assets/validator/validator.min.js"></script>
<!-- custom js -->
<script type="text/javascript" src="assets/bootstrap-fileupload/bootstrap-fileupload.js"></script>
<!-- jQuery Smart Wizard -->
<script>
$(document).ready(function() {
$('#wizard').smartWizard();
$('#wizard_verticle').smartWizard({
transitionEffect: 'slide'
});
$('.buttonNext').addClass('btn btn-success');
$('.buttonPrevious').addClass('btn btn-primary');
$('.buttonFinish').addClass('btn btn-default');
});
</script>
<!-- /jQuery Smart Wizard -->
<script>
$(document).ready(function() {
$('#single_cal1').daterangepicker({
singleDatePicker: true,
calender_style: "picker_1"
}, function(start, end, label) {
console.log(start.toISOString(), end.toISOString(), label);
});
$('#single_cal2').daterangepicker({
singleDatePicker: true,
calender_style: "picker_2"
}, function(start, end, label) {
console.log(start.toISOString(), end.toISOString(), label);
});
$('#single_cal3').daterangepicker({
singleDatePicker: true,
calender_style: "picker_3"
}, function(start, end, label) {
console.log(start.toISOString(), end.toISOString(), label);
});
$('#single_cal4').daterangepicker({
singleDatePicker: true,
calender_style: "picker_4"
}, function(start, end, label) {
console.log(start.toISOString(), end.toISOString(), label);
});
});
</script>
<!-- Select2 -->
<script>
$(document).ready(function() {
$(".select2_single").select2({
placeholder: "Select an Option",
allowClear: true
});
$(".select2_group").select2({});
$(".select2_multiple").select2({
maximumSelectionLength: 4,
placeholder: "With Max Selection limit 4",
allowClear: true
});
});
</script>
<!-- /Select2 -->
<!-- validator -->
<script>
// initialize the validator function
validator.message.date = 'not a real date';
// validate a field on "blur" event, a 'select' on 'change' event & a '.reuired' classed multifield on 'keyup':
$('form')
.on('blur', 'input[required], input.optional, select.required', validator.checkField)
.on('change', 'select.required', validator.checkField)
.on('keypress', 'input[required][pattern]', validator.keypress);
$('.multi.required').on('keyup blur', 'input', function() {
validator.checkField.apply($(this).siblings().last()[0]);
});
$('form').submit(function(e) {
e.preventDefault();
var submit = true;
// evaluate the form using generic validaing
if (!validator.checkAll($(this))) {
submit = false;
}
if (submit)
this.submit();
return false;
});
</script>
<!-- /validator -->
@stack('scripts')
</body>
</html>
| gpl-3.0 |
rvega/morphasynth | vendors/pd-extended-0.43.4/externals/Gem/src/Pixes/pix_a_2grey.cpp | 3267 | ////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// zmoelnig@iem.kug.ac.at
//
// Implementation file
//
// Copyright (c) 1997-2000 Mark Danks.
// Copyright (c) Günther Geiger.
// Copyright (c) 2001-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at
// Copyright (c) 2002 James Tittle & Chris Clepper
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "GEM.LICENSE.TERMS" in this distribution.
//
/////////////////////////////////////////////////////////
#include "pix_a_2grey.h"
#include "Gem/PixConvert.h"
CPPEXTERN_NEW_WITH_ONE_ARG(pix_a_2grey, t_floatarg, A_DEFFLOAT);
/////////////////////////////////////////////////////////
//
// pix_a_2grey
//
/////////////////////////////////////////////////////////
// Constructor
//
/////////////////////////////////////////////////////////
pix_a_2grey :: pix_a_2grey(t_floatarg alpha)
{
m_mode = static_cast<int>(alpha * 255.f);
inlet_new(this->x_obj, &this->x_obj->ob_pd, gensym("float"), gensym("ft1"));
}
/////////////////////////////////////////////////////////
// Destructor
//
/////////////////////////////////////////////////////////
pix_a_2grey :: ~pix_a_2grey()
{ }
/////////////////////////////////////////////////////////
// alphaMess
//
/////////////////////////////////////////////////////////
void pix_a_2grey :: alphaMess(float alphaval)
{
if (alphaval > 1.f)
alphaval = 1.f;
if (alphaval < -1.f)
alphaval = -1.f;
m_mode = static_cast<int>(alphaval*255.f);
setPixModified();
}
/////////////////////////////////////////////////////////
// processImage
//
/////////////////////////////////////////////////////////
void pix_a_2grey :: processRGBAImage(imageStruct &image)
{
if (!m_mode)return;
unsigned char *pixels = image.data;
int count = image.ysize * image.xsize;
if (m_mode < 0){
const int realVal = -m_mode;
while (count--) {
if (pixels[chAlpha] < realVal){
const int grey = (pixels[chRed] * RGB2GRAY_RED + pixels[chGreen] * RGB2GRAY_GREEN + pixels[chBlue] * RGB2GRAY_BLUE)>>8;
pixels[chRed] = pixels[chGreen] = pixels[chBlue] = (unsigned char)grey;
}
pixels += 4;
}
}else{
while (count--){
if (pixels[chAlpha] > m_mode){
const int grey = (pixels[chRed] * RGB2GRAY_RED + pixels[chGreen] * RGB2GRAY_GREEN + pixels[chBlue] * RGB2GRAY_BLUE)>>8;
pixels[chRed] = pixels[chGreen] = pixels[chBlue] = (unsigned char)grey;
}
pixels += 4;
}
}
}
/////////////////////////////////////////////////////////
// static member function
//
/////////////////////////////////////////////////////////
void pix_a_2grey :: obj_setupCallback(t_class *classPtr)
{
class_addcreator(reinterpret_cast<t_newmethod>(create_pix_a_2grey),
gensym("pix_a_2gray"), A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&pix_a_2grey::alphaMessCallback),
gensym("ft1"), A_FLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&pix_a_2grey::alphaMessCallback),
gensym("alpha"), A_FLOAT, A_NULL);
}
void pix_a_2grey :: alphaMessCallback(void *data, t_floatarg alphaval)
{
GetMyClass(data)->alphaMess(alphaval);
}
| gpl-3.0 |
2014c2g4/2015cda0623 | wsgi.py | 51405 | # coding=utf-8
# 上面的程式內容編碼必須在程式的第一或者第二行才會有作用
################# (1) 模組導入區
# 導入 cherrypy 模組, 為了在 OpenShift 平台上使用 cherrypy 模組, 必須透過 setup.py 安裝
import cherrypy
# 導入 Python 內建的 os 模組, 因為 os 模組為 Python 內建, 所以無需透過 setup.py 安裝
import os
# 導入 random 模組
import random
import math
from cherrypy.lib.static import serve_file
# 導入 gear 模組
#import gear
import man
import man2
import man3
################# (2) 廣域變數設定區
# 確定程式檔案所在目錄, 在 Windows 下有最後的反斜線
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
# 設定在雲端與近端的資料儲存目錄
if 'OPENSHIFT_REPO_DIR' in os.environ.keys():
# 表示程式在雲端執行
download_root_dir = os.environ['OPENSHIFT_DATA_DIR']
data_dir = os.environ['OPENSHIFT_DATA_DIR']
else:
# 表示程式在近端執行
download_root_dir = _curdir + "/local_data/"
data_dir = _curdir + "/local_data/"
'''以下為近端 input() 與 for 迴圈應用的程式碼, 若要將程式送到 OpenShift 執行, 除了採用 CherryPy 網際框架外, 還要轉為 html 列印
# 利用 input() 取得的資料型別為字串
toprint = input("要印甚麼內容?")
# 若要將 input() 取得的字串轉為整數使用, 必須利用 int() 轉換
repeat_no = int(input("重複列印幾次?"))
for i in range(repeat_no):
print(toprint)
'''
################# (3) 程式類別定義區
# 以下改用 CherryPy 網際框架程式架構
# 以下為 Hello 類別的設計內容, 其中的 object 使用, 表示 Hello 類別繼承 object 的所有特性, 包括方法與屬性設計
class Hello(object):
# Hello 類別的啟動設定
_cp_config = {
'tools.encode.encoding': 'utf-8',
'tools.sessions.on' : True,
'tools.sessions.storage_type' : 'file',
#'tools.sessions.locking' : 'explicit',
# session 以檔案儲存, 而且位於 data_dir 下的 tmp 目錄
'tools.sessions.storage_path' : data_dir+'/tmp',
# session 有效時間設為 60 分鐘
'tools.sessions.timeout' : 60
}
#@+others
#@+node:2014fall.20141212095015.2004: *3* __init__
def __init__(self):
# 配合透過案例啟始建立所需的目錄
if not os.path.isdir(data_dir+'/tmp'):
os.mkdir(data_dir+'/tmp')
if not os.path.isdir(data_dir+"/downloads"):
os.mkdir(data_dir+"/downloads")
if not os.path.isdir(data_dir+"/images"):
os.mkdir(data_dir+"/images")
#@+node:2014fall.20141212095015.1778: *3* index_orig
# 以 @ 開頭的 cherrypy.expose 為 decorator, 用來表示隨後的成員方法, 可以直接讓使用者以 URL 連結執行
@cherrypy.expose
# index 方法為 CherryPy 各類別成員方法中的內建(default)方法, 當使用者執行時未指定方法, 系統將會優先執行 index 方法
# 有 self 的方法為類別中的成員方法, Python 程式透過此一 self 在各成員方法間傳遞物件內容
def index_orig(self, toprint="Hello World!"):
return toprint
#@+node:2014fall.20141212095015.1779: *3* hello
@cherrypy.expose
def a_40223138(self, toprint="a_40223138"):
return toprint
#@+node:.20150518203620.1: *3* index
@cherrypy.expose
def index(self, guess=None):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
第17周考試內容<br />
<a href="mygeartest3">題目1</a><br />
<a href="mygeartest4">題目2(黃道明與丁軍華)</a><br />
</body>
</html>
'''
return outstring
#@+node:2014fall.20141215194146.1791: *3* index2
@cherrypy.expose
def index2(self, guess=None):
# 將標準答案存入 answer session 對應區
theanswer = random.randint(1, 100)
thecount = 0
# 將答案與計算次數變數存進 session 對應變數
cherrypy.session['answer'] = theanswer
cherrypy.session['count'] = thecount
# 印出讓使用者輸入的超文件表單
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.0-20150301-090019/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<form method=POST action=doCheck>
請輸入您所猜的整數:<input type=text name=guess><br />
<input type=submit value=send>
</form>
<hr>
<!-- 以下在網頁內嵌 Brython 程式 -->
<script type="text/python">
from browser import document, alert
def echo(ev):
alert(document["zone"].value)
# 將文件中名稱為 mybutton 的物件, 透過 click 事件與 echo 函式 bind 在一起
document['mybutton'].bind('click',echo)
</script>
<input id="zone"><button id="mybutton">click !</button>
<hr>
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
import math
# 畫布指定在名稱為 plotarea 的 canvas 上
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
# 用紅色畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
ctx.moveTo(0, 0)
ctx.lineTo(0, 500)
ctx.strokeStyle = "red"
ctx.stroke()
# 用藍色再畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
ctx.moveTo(0, 0)
ctx.lineTo(500, 0)
ctx.strokeStyle = "blue"
ctx.stroke()
# 用綠色再畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
ctx.moveTo(0, 0)
ctx.lineTo(500, 500)
ctx.strokeStyle = "green"
ctx.stroke()
# 用黑色畫一個圓
ctx.beginPath()
ctx.lineWidth = 3
ctx.strokeStyle = "black"
ctx.arc(250,250,50,0,2*math.pi)
ctx.stroke()
</script>
<canvas id="plotarea" width="800" height="600"></canvas>
</body>
</html>
'''
return outstring
#@+node:2015.20150330144929.1713: *3* twoDgear
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def twoDgear(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.0-20150301-090019/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<form method=POST action=do2Dgear>
齒數:<input type=text name=N><br />
模數:<input type=text name=M><br />
壓力角:<input type=text name=P><br />
<input type=submit value=send>
</form>
</body>
</html>
'''
return outstring
#@+node:2015.20150331094055.1733: *3* threeDgear
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def threeDgear(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.0-20150301-090019/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<form method=POST action=do3Dgear>
齒數:<input type=text name=N><br />
模數:<input type=text name=M><br />
壓力角:<input type=text name=P><br />
<input type=submit value=send>
</form>
</body>
</html>
'''
return outstring
#@+node:2015.20150330144929.1762: *3* do2Dgear
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def do2Dgear(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.0-20150301-090019/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
import math
# 畫布指定在名稱為 plotarea 的 canvas 上
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
# 用紅色畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
'''
outstring += '''
ctx.moveTo('''+str(N)+","+str(M)+")"
outstring += '''
ctx.lineTo(0, 500)
ctx.strokeStyle = "red"
ctx.stroke()
# 用藍色再畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
ctx.moveTo(0, 0)
ctx.lineTo(500, 0)
ctx.strokeStyle = "blue"
ctx.stroke()
# 用綠色再畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
ctx.moveTo(0, 0)
ctx.lineTo(500, 500)
ctx.strokeStyle = "green"
ctx.stroke()
# 用黑色畫一個圓
ctx.beginPath()
ctx.lineWidth = 3
ctx.strokeStyle = "black"
ctx.arc(250,250,50,0,2*math.pi)
ctx.stroke()
</script>
<canvas id="plotarea" width="800" height="600"></canvas>
</body>
</html>
'''
return outstring
#@+node:2015.20150331094055.1735: *3* do3Dgear
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def do3Dgear(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.0-20150301-090019/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
import math
# 畫布指定在名稱為 plotarea 的 canvas 上
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
# 用紅色畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
'''
outstring += '''
ctx.moveTo('''+str(N)+","+str(M)+")"
outstring += '''
ctx.lineTo(0, 500)
ctx.strokeStyle = "red"
ctx.stroke()
# 用藍色再畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
ctx.moveTo(0, 0)
ctx.lineTo(500, 0)
ctx.strokeStyle = "blue"
ctx.stroke()
# 用綠色再畫一條直線
ctx.beginPath()
ctx.lineWidth = 3
ctx.moveTo(0, 0)
ctx.lineTo(500, 500)
ctx.strokeStyle = "green"
ctx.stroke()
# 用黑色畫一個圓
ctx.beginPath()
ctx.lineWidth = 3
ctx.strokeStyle = "black"
ctx.arc(250,250,50,0,2*math.pi)
ctx.stroke()
</script>
<canvas id="plotarea" width="800" height="600"></canvas>
</body>
</html>
'''
return outstring
#@+node:2015.20150330144929.1765: *3* mygeartest
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def mygeartest(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.0-20150301-090019/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
from math import *
# 準備在 id="plotarea" 的 canvas 中繪圖
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
def create_line(x1, y1, x2, y2, width=3, fill="red"):
ctx.beginPath()
ctx.lineWidth = width
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = fill
ctx.stroke()
# 導入數學函式後, 圓周率為 pi
# deg 為角度轉為徑度的轉換因子
deg = pi/180.
#
# 以下分別為正齒輪繪圖與主 tkinter 畫布繪圖
#
# 定義一個繪正齒輪的繪圖函式
# midx 為齒輪圓心 x 座標
# midy 為齒輪圓心 y 座標
# rp 為節圓半徑, n 為齒數
def gear(midx, midy, rp, n, 顏色):
# 將角度轉換因子設為全域變數
global deg
# 齒輪漸開線分成 15 線段繪製
imax = 15
# 在輸入的畫布上繪製直線, 由圓心到節圓 y 軸頂點畫一直線
create_line(midx, midy, midx, midy-rp)
# 畫出 rp 圓, 畫圓函式尚未定義
#create_oval(midx-rp, midy-rp, midx+rp, midy+rp, width=2)
# a 為模數 (代表公制中齒的大小), 模數為節圓直徑(稱為節徑)除以齒數
# 模數也就是齒冠大小
a=2*rp/n
# d 為齒根大小, 為模數的 1.157 或 1.25倍, 這裡採 1.25 倍
d=2.5*rp/n
# ra 為齒輪的外圍半徑
ra=rp+a
print("ra:", ra)
# 畫出 ra 圓, 畫圓函式尚未定義
#create_oval(midx-ra, midy-ra, midx+ra, midy+ra, width=1)
# rb 則為齒輪的基圓半徑
# 基圓為漸開線長齒之基準圓
rb=rp*cos(20*deg)
print("rp:", rp)
print("rb:", rb)
# 畫出 rb 圓 (基圓), 畫圓函式尚未定義
#create_oval(midx-rb, midy-rb, midx+rb, midy+rb, width=1)
# rd 為齒根圓半徑
rd=rp-d
# 當 rd 大於 rb 時
print("rd:", rd)
# 畫出 rd 圓 (齒根圓), 畫圓函式尚未定義
#create_oval(midx-rd, midy-rd, midx+rd, midy+rd, width=1)
# dr 則為基圓到齒頂圓半徑分成 imax 段後的每段半徑增量大小
# 將圓弧分成 imax 段來繪製漸開線
dr=(ra-rb)/imax
# tan(20*deg)-20*deg 為漸開線函數
sigma=pi/(2*n)+tan(20*deg)-20*deg
for j in range(n):
ang=-2.*j*pi/n+sigma
ang2=2.*j*pi/n+sigma
lxd=midx+rd*sin(ang2-2.*pi/n)
lyd=midy-rd*cos(ang2-2.*pi/n)
#for(i=0;i<=imax;i++):
for i in range(imax+1):
r=rb+i*dr
theta=sqrt((r*r)/(rb*rb)-1.)
alpha=theta-atan(theta)
xpt=r*sin(alpha-ang)
ypt=r*cos(alpha-ang)
xd=rd*sin(-ang)
yd=rd*cos(-ang)
# i=0 時, 繪線起點由齒根圓上的點, 作為起點
if(i==0):
last_x = midx+xd
last_y = midy-yd
# 由左側齒根圓作為起點, 除第一點 (xd,yd) 齒根圓上的起點外, 其餘的 (xpt,ypt)則為漸開線上的分段點
create_line((midx+xpt),(midy-ypt),(last_x),(last_y),fill=顏色)
# 最後一點, 則為齒頂圓
if(i==imax):
lfx=midx+xpt
lfy=midy-ypt
last_x = midx+xpt
last_y = midy-ypt
# the line from last end of dedendum point to the recent
# end of dedendum point
# lxd 為齒根圓上的左側 x 座標, lyd 則為 y 座標
# 下列為齒根圓上用來近似圓弧的直線
create_line((lxd),(lyd),(midx+xd),(midy-yd),fill=顏色)
#for(i=0;i<=imax;i++):
for i in range(imax+1):
r=rb+i*dr
theta=sqrt((r*r)/(rb*rb)-1.)
alpha=theta-atan(theta)
xpt=r*sin(ang2-alpha)
ypt=r*cos(ang2-alpha)
xd=rd*sin(ang2)
yd=rd*cos(ang2)
# i=0 時, 繪線起點由齒根圓上的點, 作為起點
if(i==0):
last_x = midx+xd
last_y = midy-yd
# 由右側齒根圓作為起點, 除第一點 (xd,yd) 齒根圓上的起點外, 其餘的 (xpt,ypt)則為漸開線上的分段點
create_line((midx+xpt),(midy-ypt),(last_x),(last_y),fill=顏色)
# 最後一點, 則為齒頂圓
if(i==imax):
rfx=midx+xpt
rfy=midy-ypt
last_x = midx+xpt
last_y = midy-ypt
# lfx 為齒頂圓上的左側 x 座標, lfy 則為 y 座標
# 下列為齒頂圓上用來近似圓弧的直線
create_line(lfx,lfy,rfx,rfy,fill=顏色)
gear(400,400,300,41,"blue")
</script>
<canvas id="plotarea" width="800" height="800"></canvas>
</body>
</html>
'''
return outstring
#@+node:.20150428191028.1815: *3* mygeartest2
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def mygeartest2(self , M=15, P=15,N1=7, N2=9,N3=11,N4=13,N5=15 ,N6=17):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.1-20150328-091302/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<form method=POST action=mygeartest2>
模數:<input type=text name=M><br />
壓力角:<input type=text name=P><br />
齒輪1齒數:<input type=text name=N1><br />
齒輪2齒數:<input type=text name=N2><br />
齒輪3齒數:<input type=text name=N3><br />
齒輪4齒數:<input type=text name=N4><br />
齒輪5齒數:<input type=text name=N5><br />
齒輪6齒數:<input type=text name=N6><br />
<input type=submit value=send>
</form>
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
from math import *
# 請注意, 這裡導入位於 Lib/site-packages 目錄下的 spur.py 檔案
import spur
# 準備在 id="plotarea" 的 canvas 中繪圖
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
# 以下利用 spur.py 程式進行繪圖, 接下來的協同設計運算必須要配合使用者的需求進行設計運算與繪圖
# 其中並將工作分配給其他組員建立類似 spur.py 的相關零件繪圖模組
# midx, midy 為齒輪圓心座標, rp 為節圓半徑, n 為齒數, pa 為壓力角, color 為線的顏色
# Gear(midx, midy, rp, n=20, pa=20, color="black"):
# 模數決定齒的尺寸大小, 囓合齒輪組必須有相同的模數與壓力角
# 壓力角 pa 單位為角度
pa ='''+str(P)+'''
# m 為模數
m = '''+str(M)+'''
# 第1齒輪齒數
n_g1 = '''+str(N1)+'''
# 第2齒輪齒數
n_g2 = '''+str(N2)+'''
# 第3齒輪齒數
n_g3 = '''+str(N3)+'''
# 第4齒輪齒數
n_g4 = '''+str(N4)+'''
# 第5齒輪齒數
n_g5 = '''+str(N5)+'''
# 第5齒輪齒數
n_g6 = '''+str(N6)+'''
# 計算兩齒輪的節圓半徑
rp_g1 = m*n_g1/2
rp_g2 = m*n_g2/2
rp_g3 = m*n_g3/2
rp_g4 = m*n_g4/2
rp_g5 = m*n_g5/2
rp_g6 = m*n_g6/2
# 繪圖第1齒輪的圓心座標
x_g1 = 200
y_g1 = 200
# 第2齒輪的圓心座標, 假設排列成水平, 表示各齒輪圓心 y 座標相同
x_g2 = x_g1 + rp_g1 + rp_g2
y_g2 = y_g1
# 第3齒輪的圓心座標
x_g3 = x_g1 + rp_g1 + 2*rp_g2 + rp_g3
y_g3 = y_g1
# 第4齒輪的圓心座標
x_g4 = x_g1 + rp_g1 + 2*rp_g2 +2* rp_g3+rp_g4
y_g4= y_g1
# 第5齒輪的圓心座標
x_g5 = x_g1+ rp_g1 + 2*rp_g2 +2* rp_g3+2*rp_g4+rp_g5
y_g5= y_g1
# 第6齒輪的圓心座標
x_g6 = x_g1+ rp_g1 + 2*rp_g2 +2* rp_g3+2*rp_g4+2*rp_g5+rp_g6
y_g6= y_g1
# 將第1齒輪順時鐘轉 90 度
# 使用 ctx.save() 與 ctx.restore() 以確保各齒輪以相對座標進行旋轉繪圖
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g1, y_g1)
# rotate to engage
ctx.rotate(pi/2)
# put it back
ctx.translate(-x_g1, -y_g1)
spur.Spur(ctx).Gear(x_g1, y_g1, rp_g1, n_g1, pa, "blue")
ctx.restore()
# 將第2齒輪逆時鐘轉 90 度之後, 再多轉一齒, 以便與第1齒輪進行囓合
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g2, y_g2)
# rotate to engage
ctx.rotate(-pi/2-pi/n_g2)
# put it back
ctx.translate(-x_g2, -y_g2)
spur.Spur(ctx).Gear(x_g2, y_g2, rp_g2, n_g2, pa, "black")
ctx.restore()
# 將第3齒輪逆時鐘轉 90 度之後, 再往回轉第2齒輪定位帶動轉角, 然後再逆時鐘多轉一齒, 以便與第2齒輪進行囓合
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g3, y_g3)
# rotate to engage
# pi+pi/n_g2 為第2齒輪從順時鐘轉 90 度之後, 必須配合目前的標記線所作的齒輪 2 轉動角度, 要轉換到齒輪3 的轉動角度
# 必須乘上兩齒輪齒數的比例, 若齒輪2 大, 則齒輪3 會轉動較快
# 第1個 -pi/2 為將原先垂直的第3齒輪定位線逆時鐘旋轉 90 度
# -pi/n_g3 則是第3齒與第2齒定位線重合後, 必須再逆時鐘多轉一齒的轉角, 以便進行囓合
# (pi+pi/n_g2)*n_g2/n_g3 則是第2齒原定位線為順時鐘轉動 90 度,
# 但是第2齒輪為了與第1齒輪囓合, 已經距離定位線, 多轉了 180 度, 再加上第2齒輪的一齒角度, 因為要帶動第3齒輪定位,
# 這個修正角度必須要再配合第2齒與第3齒的轉速比加以轉換成第3齒輪的轉角, 因此乘上 n_g2/n_g3
ctx.rotate(-pi/2-pi/n_g3+(pi+pi/n_g2)*n_g2/n_g3)
# put it back
ctx.translate(-x_g3, -y_g3)
spur.Spur(ctx).Gear(x_g3, y_g3, rp_g3, n_g3, pa, "red")
ctx.restore()
#齒輪4
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g4, y_g4)
# rotate to engage
ctx.rotate(-pi/2-pi/n_g4+(pi+pi/n_g3)*n_g3/n_g4)
# put it back
ctx.translate(-x_g4, -y_g4)
spur.Spur(ctx).Gear(x_g4, y_g4, rp_g4, n_g4, pa, "pink")
ctx.restore()
#齒輪5
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g5, y_g5)
# rotate to engage
ctx.rotate(-pi/2-pi/n_g5+(pi+pi/n_g4)*n_g4/n_g5)
# put it back
ctx.translate(-x_g5, -y_g5)
spur.Spur(ctx).Gear(x_g5, y_g5, rp_g5, n_g5, pa, "yellow")
ctx.restore()
#齒輪6
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g6, y_g6)
# rotate to engage
ctx.rotate(-pi/2-pi/n_g6+(pi+pi/n_g5)*n_g5/n_g6)
# put it back
ctx.translate(-x_g6, -y_g6)
spur.Spur(ctx).Gear(x_g6, y_g6, rp_g6, n_g6, pa, "pruple")
ctx.restore()
# 按照上面三個正齒輪的囓合轉角運算, 隨後的傳動齒輪轉角便可依此類推, 完成6個齒輪的囓合繪圖
</script>
<canvas id="plotarea" width="1600" height="1200"></canvas>
</body>
</html>
'''
return outstring
#@+node:2015.20150331094055.1737: *3* my3Dgeartest
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def mygeartest3(self , M=5, P=15,N1=15, N2=24 ):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.1-20150328-091302/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<form method=POST action=mygeartest3>
模數:<input type=text name=M><br />
壓力角:<input type=text name=P><br />
齒輪1齒數:<select name=N1>
<option selected="true">15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
<option>33</option>
<option>34</option>
<option>35</option>
<option>36</option>
<option>37</option>
<option>38</option>
<option>39</option>
<option>40</option>
<option>41</option>
<option>42</option>
<option>43</option>
<option>44</option>
<option>45</option>
<option>46</option>
<option>47</option>
<option>48</option>
<option>49</option>
<option>50</option>
<option>51</option>
<option>52</option>
<option>53</option>
<option>54</option>
<option>55</option>
<option>56</option>
<option>57</option>
<option>58</option>
<option>59</option>
<option>60</option>
<option>61</option>
<option>62</option>
<option>63</option>
<option>64</option>
<option>65</option>
<option>66</option>
<option>67</option>
<option>68</option>
<option>69</option>
<option>70</option>
<option>71</option>
<option>72</option>
<option>73</option>
<option>74</option>
<option>75</option>
<option>76</option>
<option>77</option>
<option>78</option>
<option>79</option>
<option>80</option>
</select>
齒輪2齒數:<select name=N2>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option selected="true">24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
<option>33</option>
<option>34</option>
<option>35</option>
<option>36</option>
<option>37</option>
<option>38</option>
<option>39</option>
<option>40</option>
<option>41</option>
<option>42</option>
<option>43</option>
<option>44</option>
<option>45</option>
<option>46</option>
<option>47</option>
<option>48</option>
<option>49</option>
<option>50</option>
<option>51</option>
<option>52</option>
<option>53</option>
<option>54</option>
<option>55</option>
<option>56</option>
<option>57</option>
<option>58</option>
<option>59</option>
<option>60</option>
<option>61</option>
<option>62</option>
<option>63</option>
<option>64</option>
<option>65</option>
<option>66</option>
<option>67</option>
<option>68</option>
<option>69</option>
<option>70</option>
<option>71</option>
<option>72</option>
<option>73</option>
<option>74</option>
<option>75</option>
<option>76</option>
<option>77</option>
<option>78</option>
<option>79</option>
<option>80</option>
</select>
<input type=submit value=send>
</form>
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
from math import *
# 請注意, 這裡導入位於 Lib/site-packages 目錄下的 spur.py 檔案
import spur
# 準備在 id="plotarea" 的 canvas 中繪圖
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
# 以下利用 spur.py 程式進行繪圖, 接下來的協同設計運算必須要配合使用者的需求進行設計運算與繪圖
# 其中並將工作分配給其他組員建立類似 spur.py 的相關零件繪圖模組
# midx, midy 為齒輪圓心座標, rp 為節圓半徑, n 為齒數, pa 為壓力角, color 為線的顏色
# Gear(midx, midy, rp, n=20, pa=20, color="black"):
# 模數決定齒的尺寸大小, 囓合齒輪組必須有相同的模數與壓力角
# 壓力角 pa 單位為角度
pa ='''+str(P)+'''
# m 為模數
m = '''+str(M)+'''
# 第1齒輪齒數
n_g1 = '''+str(N1)+'''
# 第2齒輪齒數
n_g2 = '''+str(N2)+'''
# 計算兩齒輪的節圓半徑
rp_g1 = m*n_g1/2
rp_g2 = m*n_g2/2
# 繪圖第1齒輪的圓心座標
x_g1 = 400
y_g1 = 400
# 第2齒輪的圓心座標, 假設排列成水平, 表示各齒輪圓心 y 座標相同
x_g2 = x_g1
y_g2 = y_g1 + rp_g1 + rp_g2
# 將第1齒輪順時鐘轉 90 度
# 使用 ctx.save() 與 ctx.restore() 以確保各齒輪以相對座標進行旋轉繪圖
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g1, y_g1)
# rotate to engage
ctx.rotate(pi)
# put it back
ctx.translate(-x_g1, -y_g1)
spur.Spur(ctx).Gear(x_g1, y_g1, rp_g1, n_g1, pa, "blue")
ctx.restore()
# 將第2齒輪逆時鐘轉 90 度之後, 再多轉一齒, 以便與第1齒輪進行囓合
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g2, y_g2)
# rotate to engage
ctx.rotate(-pi/n_g2)
# put it back
ctx.translate(-x_g2, -y_g2)
spur.Spur(ctx).Gear(x_g2, y_g2, rp_g2, n_g2, pa, "black")
ctx.restore()
# 按照上面三個正齒輪的囓合轉角運算, 隨後的傳動齒輪轉角便可依此類推, 完成6個齒輪的囓合繪圖
</script>
<canvas id="plotarea" width="1200" height="1200"></canvas>
</body>
</html>
'''
return outstring
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def mygeartest4(self , M=10, P=15,N1=15, N2=24,N3=15,N4=24 ):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.1-20150328-091302/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<form method=POST action=mygeartest4>
模數:<input type=text name=M><br />
壓力角:<input type=text name=P><br />
齒輪1齒數:<select name=N1>
<option selected="true">15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
<option>33</option>
<option>34</option>
<option>35</option>
<option>36</option>
<option>37</option>
<option>38</option>
<option>39</option>
<option>40</option>
<option>41</option>
<option>42</option>
<option>43</option>
<option>44</option>
<option>45</option>
<option>46</option>
<option>47</option>
<option>48</option>
<option>49</option>
<option>50</option>
<option>51</option>
<option>52</option>
<option>53</option>
<option>54</option>
<option>55</option>
<option>56</option>
<option>57</option>
<option>58</option>
<option>59</option>
<option>60</option>
<option>61</option>
<option>62</option>
<option>63</option>
<option>64</option>
<option>65</option>
<option>66</option>
<option>67</option>
<option>68</option>
<option>69</option>
<option>70</option>
<option>71</option>
<option>72</option>
<option>73</option>
<option>74</option>
<option>75</option>
<option>76</option>
<option>77</option>
<option>78</option>
<option>79</option>
<option>80</option>
</select>
齒輪2齒數:<select name=N2>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option selected="true">24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
<option>33</option>
<option>34</option>
<option>35</option>
<option>36</option>
<option>37</option>
<option>38</option>
<option>39</option>
<option>40</option>
<option>41</option>
<option>42</option>
<option>43</option>
<option>44</option>
<option>45</option>
<option>46</option>
<option>47</option>
<option>48</option>
<option>49</option>
<option>50</option>
<option>51</option>
<option>52</option>
<option>53</option>
<option>54</option>
<option>55</option>
<option>56</option>
<option>57</option>
<option>58</option>
<option>59</option>
<option>60</option>
<option>61</option>
<option>62</option>
<option>63</option>
<option>64</option>
<option>65</option>
<option>66</option>
<option>67</option>
<option>68</option>
<option>69</option>
<option>70</option>
<option>71</option>
<option>72</option>
<option>73</option>
<option>74</option>
<option>75</option>
<option>76</option>
<option>77</option>
<option>78</option>
<option>79</option>
<option>80</option>
</select>
齒輪3齒數:<select name=N3>
<option selected="true">15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
<option>33</option>
<option>34</option>
<option>35</option>
<option>36</option>
<option>37</option>
<option>38</option>
<option>39</option>
<option>40</option>
<option>41</option>
<option>42</option>
<option>43</option>
<option>44</option>
<option>45</option>
<option>46</option>
<option>47</option>
<option>48</option>
<option>49</option>
<option>50</option>
<option>51</option>
<option>52</option>
<option>53</option>
<option>54</option>
<option>55</option>
<option>56</option>
<option>57</option>
<option>58</option>
<option>59</option>
<option>60</option>
<option>61</option>
<option>62</option>
<option>63</option>
<option>64</option>
<option>65</option>
<option>66</option>
<option>67</option>
<option>68</option>
<option>69</option>
<option>70</option>
<option>71</option>
<option>72</option>
<option>73</option>
<option>74</option>
<option>75</option>
<option>76</option>
<option>77</option>
<option>78</option>
<option>79</option>
<option>80</option>
</select>
齒輪4齒數:<select name=N4>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>
<option>22</option>
<option>23</option>
<option selected="true">24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
<option>32</option>
<option>33</option>
<option>34</option>
<option>35</option>
<option>36</option>
<option>37</option>
<option>38</option>
<option>39</option>
<option>40</option>
<option>41</option>
<option>42</option>
<option>43</option>
<option>44</option>
<option>45</option>
<option>46</option>
<option>47</option>
<option>48</option>
<option>49</option>
<option>50</option>
<option>51</option>
<option>52</option>
<option>53</option>
<option>54</option>
<option>55</option>
<option>56</option>
<option>57</option>
<option>58</option>
<option>59</option>
<option>60</option>
<option>61</option>
<option>62</option>
<option>63</option>
<option>64</option>
<option>65</option>
<option>66</option>
<option>67</option>
<option>68</option>
<option>69</option>
<option>70</option>
<option>71</option>
<option>72</option>
<option>73</option>
<option>74</option>
<option>75</option>
<option>76</option>
<option>77</option>
<option>78</option>
<option>79</option>
<option>80</option>
</select>
<input type=submit value=send>
</form>
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
from math import *
# 請注意, 這裡導入位於 Lib/site-packages 目錄下的 spur.py 檔案
import spur
# 準備在 id="plotarea" 的 canvas 中繪圖
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
# 以下利用 spur.py 程式進行繪圖, 接下來的協同設計運算必須要配合使用者的需求進行設計運算與繪圖
# 其中並將工作分配給其他組員建立類似 spur.py 的相關零件繪圖模組
# midx, midy 為齒輪圓心座標, rp 為節圓半徑, n 為齒數, pa 為壓力角, color 為線的顏色
# Gear(midx, midy, rp, n=20, pa=20, color="black"):
# 模數決定齒的尺寸大小, 囓合齒輪組必須有相同的模數與壓力角
# 壓力角 pa 單位為角度
pa ='''+str(P)+'''
# m 為模數
m = '''+str(M)+'''
# 第1齒輪齒數
n_g1 = '''+str(N1)+'''
# 第2齒輪齒數
n_g2 = '''+str(N2)+'''
# 第3齒輪齒數
n_g3 = '''+str(N3)+'''
# 第4齒輪齒數
n_g4 = '''+str(N4)+'''
# 計算兩齒輪的節圓半徑
rp_g1 = m*n_g1/2
rp_g2 = m*n_g2/2
rp_g3 = m*n_g3/2
rp_g4 = m*n_g4/2
# 繪圖第1齒輪的圓心座標
x_g1 = 300
y_g1 = 300
# 第2齒輪的圓心座標, 假設排列成水平, 表示各齒輪圓心 y 座標相同
x_g2 = x_g1
y_g2 = y_g1 + rp_g1 + rp_g2
# 第3齒輪的圓心座標
x_g3 = x_g2 + rp_g2+rp_g3
y_g3 = y_g1 + rp_g1 + rp_g2
# 第4齒輪的圓心座標
x_g4 = x_g1 + rp_g2+rp_g3
y_g4= y_g1 + rp_g1 + rp_g2+rp_g3+rp_g4
# 將第1齒輪順時鐘轉 90 度
# 使用 ctx.save() 與 ctx.restore() 以確保各齒輪以相對座標進行旋轉繪圖
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g1, y_g1)
# rotate to engage
ctx.rotate(pi)
# put it back
ctx.translate(-x_g1, -y_g1)
spur.Spur(ctx).Gear(x_g1, y_g1, rp_g1, n_g1, pa, "blue")
ctx.restore()
# 將第2齒輪逆時鐘轉 90 度之後, 再多轉一齒, 以便與第1齒輪進行囓合
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g2, y_g2)
# rotate to engage
ctx.rotate(-pi/n_g2)
# put it back
ctx.translate(-x_g2, -y_g2)
spur.Spur(ctx).Gear(x_g2, y_g2, rp_g2, n_g2, pa, "black")
ctx.restore()
# 將第3齒輪逆時鐘轉 90 度之後, 再往回轉第2齒輪定位帶動轉角, 然後再逆時鐘多轉一齒, 以便與第2齒輪進行囓合
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g3, y_g3)
ctx.rotate(-pi/2-pi/n_g3+(pi/2+pi/n_g2)*n_g2/n_g3)
# put it back
ctx.translate(-x_g3, -y_g3)
spur.Spur(ctx).Gear(x_g3, y_g3, rp_g3, n_g3, pa, "red")
ctx.restore()
#齒輪4
ctx.save()
# translate to the origin of second gear
ctx.translate(x_g4, y_g4)
# rotate to engage
ctx.rotate(-pi/n_g4+(-pi/2+pi/n_g3)*n_g3/n_g4-(pi/2+pi/n_g2)*n_g2/n_g4)
# put it back
ctx.translate(-x_g4, -y_g4)
spur.Spur(ctx).Gear(x_g4, y_g4, rp_g4, n_g4, pa, "pink")
ctx.restore()
# 按照上面三個正齒輪的囓合轉角運算, 隨後的傳動齒輪轉角便可依此類推, 完成6個齒輪的囓合繪圖
</script>
<canvas id="plotarea" width="1200" height="1200"></canvas>
</body>
</html>
'''
return outstring
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def my3Dgeartest(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.0-20150301-090019/brython.js"></script>
<script src="/static/Cango2D.js" type="text/javascript"></script>
<script src="/static/gearUtils-04.js" type="text/javascript"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
from math import *
# 準備在 id="plotarea" 的 canvas 中繪圖
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
def create_line(x1, y1, x2, y2, width=3, fill="red"):
ctx.beginPath()
ctx.lineWidth = width
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = fill
ctx.stroke()
# 導入數學函式後, 圓周率為 pi
# deg 為角度轉為徑度的轉換因子
deg = pi/180.
#
# 以下分別為正齒輪繪圖與主 tkinter 畫布繪圖
#
# 定義一個繪正齒輪的繪圖函式
# midx 為齒輪圓心 x 座標
# midy 為齒輪圓心 y 座標
# rp 為節圓半徑, n 為齒數
def gear(midx, midy, rp, n, 顏色):
# 將角度轉換因子設為全域變數
global deg
# 齒輪漸開線分成 15 線段繪製
imax = 15
# 在輸入的畫布上繪製直線, 由圓心到節圓 y 軸頂點畫一直線
create_line(midx, midy, midx, midy-rp)
# 畫出 rp 圓, 畫圓函式尚未定義
#create_oval(midx-rp, midy-rp, midx+rp, midy+rp, width=2)
# a 為模數 (代表公制中齒的大小), 模數為節圓直徑(稱為節徑)除以齒數
# 模數也就是齒冠大小
a=2*rp/n
# d 為齒根大小, 為模數的 1.157 或 1.25倍, 這裡採 1.25 倍
d=2.5*rp/n
# ra 為齒輪的外圍半徑
ra=rp+a
print("ra:", ra)
# 畫出 ra 圓, 畫圓函式尚未定義
#create_oval(midx-ra, midy-ra, midx+ra, midy+ra, width=1)
# rb 則為齒輪的基圓半徑
# 基圓為漸開線長齒之基準圓
rb=rp*cos(20*deg)
print("rp:", rp)
print("rb:", rb)
# 畫出 rb 圓 (基圓), 畫圓函式尚未定義
#create_oval(midx-rb, midy-rb, midx+rb, midy+rb, width=1)
# rd 為齒根圓半徑
rd=rp-d
# 當 rd 大於 rb 時
print("rd:", rd)
# 畫出 rd 圓 (齒根圓), 畫圓函式尚未定義
#create_oval(midx-rd, midy-rd, midx+rd, midy+rd, width=1)
# dr 則為基圓到齒頂圓半徑分成 imax 段後的每段半徑增量大小
# 將圓弧分成 imax 段來繪製漸開線
dr=(ra-rb)/imax
# tan(20*deg)-20*deg 為漸開線函數
sigma=pi/(2*n)+tan(20*deg)-20*deg
for j in range(n):
ang=-2.*j*pi/n+sigma
ang2=2.*j*pi/n+sigma
lxd=midx+rd*sin(ang2-2.*pi/n)
lyd=midy-rd*cos(ang2-2.*pi/n)
#for(i=0;i<=imax;i++):
for i in range(imax+1):
r=rb+i*dr
theta=sqrt((r*r)/(rb*rb)-1.)
alpha=theta-atan(theta)
xpt=r*sin(alpha-ang)
ypt=r*cos(alpha-ang)
xd=rd*sin(-ang)
yd=rd*cos(-ang)
# i=0 時, 繪線起點由齒根圓上的點, 作為起點
if(i==0):
last_x = midx+xd
last_y = midy-yd
# 由左側齒根圓作為起點, 除第一點 (xd,yd) 齒根圓上的起點外, 其餘的 (xpt,ypt)則為漸開線上的分段點
create_line((midx+xpt),(midy-ypt),(last_x),(last_y),fill=顏色)
# 最後一點, 則為齒頂圓
if(i==imax):
lfx=midx+xpt
lfy=midy-ypt
last_x = midx+xpt
last_y = midy-ypt
# the line from last end of dedendum point to the recent
# end of dedendum point
# lxd 為齒根圓上的左側 x 座標, lyd 則為 y 座標
# 下列為齒根圓上用來近似圓弧的直線
create_line((lxd),(lyd),(midx+xd),(midy-yd),fill=顏色)
#for(i=0;i<=imax;i++):
for i in range(imax+1):
r=rb+i*dr
theta=sqrt((r*r)/(rb*rb)-1.)
alpha=theta-atan(theta)
xpt=r*sin(ang2-alpha)
ypt=r*cos(ang2-alpha)
xd=rd*sin(ang2)
yd=rd*cos(ang2)
# i=0 時, 繪線起點由齒根圓上的點, 作為起點
if(i==0):
last_x = midx+xd
last_y = midy-yd
# 由右側齒根圓作為起點, 除第一點 (xd,yd) 齒根圓上的起點外, 其餘的 (xpt,ypt)則為漸開線上的分段點
create_line((midx+xpt),(midy-ypt),(last_x),(last_y),fill=顏色)
# 最後一點, 則為齒頂圓
if(i==imax):
rfx=midx+xpt
rfy=midy-ypt
last_x = midx+xpt
last_y = midy-ypt
# lfx 為齒頂圓上的左側 x 座標, lfy 則為 y 座標
# 下列為齒頂圓上用來近似圓弧的直線
create_line(lfx,lfy,rfx,rfy,fill=顏色)
gear(400,400,300,41,"blue")
</script>
<canvas id="plotarea" width="800" height="800"></canvas>
</body>
</html>
'''
return outstring
#@+node:2014fall.20141215194146.1793: *3* doCheck
@cherrypy.expose
def doCheck(self, guess=None):
# 假如使用者直接執行 doCheck, 則設法轉回根方法
if guess is None:
raise cherrypy.HTTPRedirect("/")
# 從 session 取出 answer 對應資料, 且處理直接執行 doCheck 時無法取 session 值情況
try:
theanswer = int(cherrypy.session.get('answer'))
except:
raise cherrypy.HTTPRedirect("/")
# 經由表單所取得的 guess 資料型別為 string
try:
theguess = int(guess)
except:
return "error " + self.guessform()
# 每執行 doCheck 一次,次數增量一次
cherrypy.session['count'] += 1
# 答案與所猜數字進行比對
if theanswer < theguess:
return "big " + self.guessform()
elif theanswer > theguess:
return "small " + self.guessform()
else:
# 已經猜對, 從 session 取出累計猜測次數
thecount = cherrypy.session.get('count')
return "exact: <a href=''>再猜</a>"
#@+node:2014fall.20141215194146.1789: *3* guessform
def guessform(self):
# 印出讓使用者輸入的超文件表單
outstring = str(cherrypy.session.get('answer')) + "/" + str(cherrypy.session.get('count')) + '''<form method=POST action=doCheck>
請輸入您所猜的整數:<input type=text name=guess><br />
<input type=submit value=send>
</form>'''
return outstring
#@-others
#@-others
################# (4) 程式啟動區
# 配合程式檔案所在目錄設定靜態目錄或靜態檔案
application_conf = {'/static':{
'tools.staticdir.on': True,
# 程式執行目錄下, 必須自行建立 static 目錄
'tools.staticdir.dir': _curdir+"/static"},
'/downloads':{
'tools.staticdir.on': True,
'tools.staticdir.dir': data_dir+"/downloads"},
'/images':{
'tools.staticdir.on': True,
'tools.staticdir.dir': data_dir+"/images"}
}
root = Hello()
root.man = man.MAN()
root.man2 = man2.MAN()
root.man3 = man3.MAN()
if 'OPENSHIFT_REPO_DIR' in os.environ.keys():
# 表示在 OpenSfhit 執行
application = cherrypy.Application(root, config=application_conf)
else:
# 表示在近端執行
cherrypy.quickstart(root, config=application_conf)
| gpl-3.0 |
kzoacn/Grimoire | Training/10.07/C.cpp | 1292 | #include <bits/stdc++.h>
#define __advance __attribute__((optimize("O3")))
typedef long long ll;
int sgn(ll x) { return x < 0 ? -1 : x > 0; }
struct vec {
ll x, y;
vec() {}
vec(ll x, ll y): x(x), y(y) {}
__advance __inline vec operator - (const vec &rhs) const { return vec(x - rhs.x, y - rhs.y); }
};
__advance __inline ll XX(vec a, vec b) { return a.x * b.y - a.y * b.x; }
__advance __inline bool inter(vec a, vec b, vec p, vec q) {
return sgn(XX(p - a, b - a)) * sgn(XX(q - a, b - a)) <= 0 &&
sgn(XX(a - p, q - p)) * sgn(XX(b - p, q - p)) <= 0;
}
int n, m, q;
vec enemy[10005], wall[10005][2], now;
__advance int main() {
for (register int kase = 1; ~scanf("%d%d%d", &n, &m, &q); ++kase) {
for (register int i = 1; i <= n; ++i)
scanf("%lld%lld", &enemy[i].x, &enemy[i].y);
for (register int i = 1, j; i <= m; ++i)
for (j = 0; j < 2; ++j)
scanf("%lld%lld", &wall[i][j].x, &wall[i][j].y);
printf("Case #%d:\n", kase);
while (q--) {
scanf("%lld%lld", &now.x, &now.y);
int ans = 0;
for (register int i = 1; i <= n; ++i) {
bool flag = 1;
for (register int j = 1; j <= m; ++j)
if (inter(now, enemy[i], wall[j][0], wall[j][1])) {
flag = 0; break;
}
ans += flag;
}
printf("%d\n", ans);
}
}
return 0;
}
| gpl-3.0 |
hgonzalezgaviria/diheke | resources/views/errors/error.blade.php | 521 | @extends('layout')
@section('title', '/ Error')
@section('head')
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<style>
.title {
margin: 0;
padding: 0;
width: 100%;
color: #000000;
display: table;
height: 100%;
text-align: center;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
font-size: 72px;
margin-bottom: 40px;
font-weight: 100;
font-family: 'Lato';
}
</style>
@endsection
| gpl-3.0 |
AtmosFOAM/AtmosFOAM | src/TurbulenceModels/thetaBuoyantKEpsilon/thetaBuoyantKEpsilon.C | 5165 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2014-2018 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "thetaBuoyantKEpsilon.H"
#include "uniformDimensionedFields.H"
#include "fvcGrad.H"
#include "addToRunTimeSelectionTable.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace RASModels
{
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class BasicTurbulenceModel>
thetaBuoyantKEpsilon<BasicTurbulenceModel>::thetaBuoyantKEpsilon
(
const alphaField& alpha,
const rhoField& rho,
const volVectorField& U,
const surfaceScalarField& alphaRhoPhi,
const surfaceScalarField& phi,
const transportModel& transport,
const word& propertiesName,
const word& type
)
:
kEpsilon<BasicTurbulenceModel>
(
alpha,
rho,
U,
alphaRhoPhi,
phi,
transport,
propertiesName,
type
),
Cg_
(
dimensioned<scalar>::lookupOrAddToDict
(
"Cg",
this->coeffDict_,
1.0
)
)
{
if (type == typeName)
{
this->printCoeffs(type);
}
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class BasicTurbulenceModel>
bool thetaBuoyantKEpsilon<BasicTurbulenceModel>::read()
{
if (kEpsilon<BasicTurbulenceModel>::read())
{
Cg_.readIfPresent(this->coeffDict());
return true;
}
else
{
return false;
}
}
template<class BasicTurbulenceModel>
tmp<volScalarField>
thetaBuoyantKEpsilon<BasicTurbulenceModel>::Gcoef() const
{
const uniformDimensionedVectorField& g =
this->mesh_.objectRegistry::template
lookupObject<uniformDimensionedVectorField>("g");
const volScalarField& T = this->transport_.T();
const volScalarField& p = this->transport_.p();
const volScalarField& rho = this->rho_;
const volScalarField kappa
(
"kappa",
1-1/this->transport_.gamma()
);
const dimensionedScalar pRef("pRef", dimPressure, 1e5);
volScalarField theta = T*pow(pRef/p, kappa);
surfaceScalarField thetaf = linearInterpolate(theta);
theta = fvc::average(thetaf);
tmp<volScalarField> Gcoefp
(
new volScalarField
(
"Gcoef",
-(Cg_*this->Cmu_)*this->alpha_*rho*this->k_/kappa*
(
g &
(
fvc::grad(theta)/theta
)
)
/(this->epsilon_ + this->epsilonMin_)
)
);
return Gcoefp;
}
template<class BasicTurbulenceModel>
tmp<fvScalarMatrix>
thetaBuoyantKEpsilon<BasicTurbulenceModel>::kSource() const
{
const uniformDimensionedVectorField& g =
this->mesh_.objectRegistry::template
lookupObject<uniformDimensionedVectorField>("g");
if (mag(g.value()) > small)
{
return -fvm::SuSp(Gcoef(), this->k_);
}
else
{
return kEpsilon<BasicTurbulenceModel>::kSource();
}
}
template<class BasicTurbulenceModel>
tmp<fvScalarMatrix>
thetaBuoyantKEpsilon<BasicTurbulenceModel>::epsilonSource() const
{
const uniformDimensionedVectorField& g =
this->mesh_.objectRegistry::template
lookupObject<uniformDimensionedVectorField>("g");
if (mag(g.value()) > small)
{
vector gHat(g.value()/mag(g.value()));
volScalarField w(gHat & this->U_);
volScalarField u
(
mag(this->U_ - gHat*w)
+ dimensionedScalar(dimVelocity, small)
);
return -fvm::SuSp(this->C1_*tanh(mag(w)/u)*Gcoef(), this->epsilon_);
// return -fvm::SuSp(this->C1_*Gcoef(), this->epsilon_);
}
else
{
return kEpsilon<BasicTurbulenceModel>::epsilonSource();
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace RASModels
} // End namespace Foam
// ************************************************************************* //
| gpl-3.0 |
biancama/data-structures-java | src/main/java/org/biancama/algorithms/sort/MergeSort.java | 1390 | package org.biancama.algorithms.sort;
import java.util.ArrayList;
import java.util.List;
/**
* Created by massimo on 23/04/16.
*/
public class MergeSort {
private MergeSort() {}
/**
* Algorithm InsertionSort(A):
* Input: An array A of n comparable elements
* Output: The array A with elements rearranged in nondecreasing order
* for k from 1 to n−1 do
* compare A[k+1], A[k] if A[k+1] < A[k] then swap
* Continue until a complete cycle without sort
* @param unsorted
* @return
*/
public static <T extends Comparable<? super T>> List<T> sort(final List<T> unsorted) {
if (unsorted == null || unsorted.size() < 2) {
return unsorted;
} else {
int middleIndex = unsorted.size() / 2;
List<T> left = unsorted.subList(0, middleIndex);
List<T> right = unsorted.subList(middleIndex, unsorted.size());
left = sort(left);
right = sort(right);
return merge(left, right);
}
}
private static <T extends Comparable<? super T>> List<T> merge(final List<T> left, final List<T> right ) {
final List<T> result = new ArrayList<>(left.size() + right.size()) ;
int i = 0, j = 0;
for (int k = 0; k < left.size() + right.size(); k++) {
if (i == left.size() || j < right.size() && left.get(i).compareTo(right.get(j)) > 0) {
result.add(right.get(j));
j++;
} else {
result.add(left.get(i));
i++;
}
}
return result;
}
}
| gpl-3.0 |
liruixpc11/crucian | alevin/src/main/java/vnreal/resources/IdResource.java | 5131 | /* ***** BEGIN LICENSE BLOCK *****
* Copyright (C) 2010-2011, The VNREAL Project Team.
*
* This work has been funded by the European FP7
* Network of Excellence "Euro-NF" (grant agreement no. 216366)
* through the Specific Joint Developments and Experiments Project
* "Virtual Network Resource Embedding Algorithms" (VNREAL).
*
* The VNREAL Project Team consists of members from:
* - University of Wuerzburg, Germany
* - Universitat Politecnica de Catalunya, Spain
* - University of Passau, Germany
* See the file AUTHORS for details and contact information.
*
* This file is part of ALEVIN (ALgorithms for Embedding VIrtual Networks).
*
* ALEVIN is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License Version 3 or later
* (the "GPL"), or the GNU Lesser General Public License Version 3 or later
* (the "LGPL") as published by the Free Software Foundation.
*
* ALEVIN 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
* or the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License and
* GNU Lesser General Public License along with ALEVIN; see the file
* COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* ***** END LICENSE BLOCK ***** */
package vnreal.resources;
import vnreal.ExchangeParameter;
import vnreal.ToolKit;
import vnreal.constraints.AbstractConstraint;
import vnreal.constraints.INodeConstraint;
import vnreal.demands.AbstractDemand;
import vnreal.demands.DemandVisitorAdapter;
import vnreal.demands.IdDemand;
import vnreal.gui.GUI;
import vnreal.mapping.Mapping;
import vnreal.network.NetworkEntity;
import vnreal.network.Node;
import vnreal.network.substrate.SubstrateNode;
import javax.swing.*;
/**
* A resource for an identifier.
* <p/>
* N.b.: This resource is applicable for links and nodes.
*
* @author Michael Duelli
* @author Vlad Singeorzan
* @since 2010-09-10
*/
public final class IdResource extends AbstractResource implements
INodeConstraint {
private String id;
public IdResource(Node<? extends AbstractConstraint> owner) {
super(owner);
}
@ExchangeParameter
public void setId(String id) {
if (checkUniquness(id)) {
this.id = id;
} else {
if (GUI.isInitialized())
JOptionPane.showMessageDialog(GUI.getInstance(),
"IdResource is not unique.", "Error",
JOptionPane.ERROR_MESSAGE);
System.err.println("IdResource: id is not unique.");
}
}
@ExchangeParameter
public String getId() {
return id;
}
@Override
public boolean accepts(AbstractDemand dem) {
return dem.getAcceptsVisitor().visit(this);
}
@Override
public boolean fulfills(AbstractDemand dem) {
return dem.getFulfillsVisitor().visit(this);
}
@Override
protected DemandVisitorAdapter createOccupyVisitor() {
return new DemandVisitorAdapter() {
@Override
public boolean visit(IdDemand dem) {
if (fulfills(dem)) {
new Mapping(dem, getThis());
return true;
} else
return false;
}
};
}
@Override
protected DemandVisitorAdapter createFreeVisitor() {
return new DemandVisitorAdapter() {
@Override
public boolean visit(IdDemand dem) {
if (getMapping(dem) != null) {
return getMapping(dem).unregister();
} else
return false;
}
};
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("IdResource: id=");
sb.append(getId());
if (getMappings().size() > 0) {
sb.append(" occupied by ");
sb.append(getMappingsString());
}
return sb.toString();
}
private boolean checkUniquness(String id) {
if (ToolKit.getScenario().getNetworkStack() != null
&& ToolKit.getScenario().getNetworkStack().getSubstrate() != null)
for (SubstrateNode sn : ToolKit.getScenario().getNetworkStack()
.getSubstrate().getVertices()) {
for (AbstractResource res : sn.get()) {
if (res instanceof IdResource) {
if (((IdResource) res).getId().equals(id)
&& res != this) {
return false;
}
}
}
}
return true;
}
@Override
public AbstractResource getCopy(NetworkEntity<? extends AbstractConstraint> owner) {
IdResource clone = new IdResource((Node<? extends AbstractConstraint>) owner);
clone.id = id;
return clone;
}
}
| gpl-3.0 |
digitalshow/pcd-ddf-in-wpf | pcd-ddf-in-wpf/ChangesTracker.cs | 6850 | /*
pcd-ddf-in-wpf: A DDF editor for PC_DIMMER, an open source light
control software.
Copyright (C) 2016 Ingo Koinzer
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/>.
*/
using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
namespace Koinzer.pcdddfinwpf
{
/// <summary>
/// Tracks changes of objects and referenced objects.
/// Keeps track of changes with INotifyPropertyChanged
/// and INotifyCollectionChanged interfaces. Keeps track
/// of references. It might not always be accurate keeping
/// track of referencing because of the events the
/// interfaces provide.
/// </summary>
public class ChangesTracker: Prism.Mvvm.BindableBase
{
public ChangesTracker()
{
Changed = false;
References = new Dictionary<object, int>();
PropertyValues = new Dictionary<Tuple<object, string>, object>();
Parents = new Dictionary<object, object[]>();
}
public bool Attach(Object child)
{
return Attach(child, new Object[0]);
}
public bool Attach(Object child, Object[] parents)
{
if ((child == null) || (child is String) || (child is int))
return false;
if ((parents.Length > 0) && (child == _observed))
return false;
if (References.ContainsKey(child)) {
References[child]++;
return true;
}
Object[] newParents = parents.Concat(new Object[] {child}).ToArray();
bool isAttached = false;
if (child is INotifyPropertyChanged) {
AttachPropertyChanged((INotifyPropertyChanged)child);
isAttached = true;
}
if (child is INotifyCollectionChanged) {
AttachCollectionChanged((INotifyCollectionChanged)child);
isAttached = true;
}
if (child is IEnumerable) {
foreach (Object item in (IEnumerable)child)
Attach(item, newParents);
}
foreach (PropertyInfo pi in child.GetType().GetProperties()) {
if (pi.GetIndexParameters().Any())
continue;
Object value = pi.GetValue(child);
if (value == null) continue;
if (newParents.Contains(value)) continue;
if (Attach(value, newParents)) {
isAttached = true;
PropertyValues[Tuple.Create(child, pi.Name)] = value;
}
}
if (isAttached) {
References[child] = 1;
Parents[child] = newParents;
}
return isAttached;
}
public void AttachPropertyChanged(INotifyPropertyChanged child)
{
child.PropertyChanged += Observed_PropertyChanged;
}
public void AttachCollectionChanged(INotifyCollectionChanged child)
{
child.CollectionChanged += Observed_CollectionChanged;
}
void Observed_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Changed = true;
var key = Tuple.Create(sender, e.PropertyName);
if (PropertyValues.ContainsKey(key)) {
Object oldValue = PropertyValues[key];
Detach(oldValue, Parents[sender]);
}
PropertyInfo pi = sender.GetType().GetProperty(e.PropertyName);
if ((pi != null) && (pi.GetIndexParameters().Length == 0))
Attach(pi.GetValue(sender), Parents[sender]);
}
void Observed_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Changed = true;
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
foreach (Object item in e.NewItems)
Attach(item, Parents[sender]);
break;
case NotifyCollectionChangedAction.Replace:
foreach (Object item in e.NewItems)
Attach(item, Parents[sender]);
foreach (Object item in e.OldItems)
Detach(item, Parents[sender]);
break;
case NotifyCollectionChangedAction.Remove:
foreach (Object item in e.OldItems)
Detach(item, Parents[sender]);
break;
}
}
public void Detach(Object child)
{
Detach(child, new Object[0]);
}
public void Detach(Object child, Object[] parents)
{
if (child == null)
return;
if (!References.ContainsKey(child))
return;
References[child]--;
if (References[child] < 0)
throw new ApplicationException("Reference counter for object " + child.ToString() + " dropped below 0!");
if (References[child] > 0)
return;
References.Remove(child);
Parents.Remove(child);
Object[] newParents = parents.Concat(new Object[] {child}).ToArray();
if (child is INotifyPropertyChanged)
DetachPropertyChanged((INotifyPropertyChanged)child);
if (child is INotifyCollectionChanged)
DetachCollectionChanged((INotifyCollectionChanged)child);
if (child is IEnumerable) {
foreach (Object item in (IEnumerable)child)
Detach(item, newParents);
}
foreach (PropertyInfo pi in child.GetType().GetProperties()) {
if (pi.GetIndexParameters().Any())
continue;
Object value = pi.GetValue(child);
if (PropertyValues.ContainsKey(Tuple.Create(child, pi.Name)))
PropertyValues.Remove(Tuple.Create(child, pi.Name));
if (value == null) continue;
if (newParents.Contains(value)) continue;
Detach(value, newParents);
}
}
public void DetachPropertyChanged(INotifyPropertyChanged child)
{
child.PropertyChanged -= Observed_PropertyChanged;
}
public void DetachCollectionChanged(INotifyCollectionChanged child)
{
child.CollectionChanged -= Observed_CollectionChanged;
}
public void Unchanged()
{
Changed = false;
}
private void Reset()
{
while (References.Count > 0) {
Object key = References.First().Key;
References[key] = 1;
Detach(key);
}
Unchanged();
}
private Dictionary<Object, int> References { get; set; }
private Dictionary<Tuple<Object, String>, Object> PropertyValues { get; set; }
private Dictionary<Object, Object[]> Parents { get; set; }
Object _observed;
public Object Observed {
get { return _observed; }
set {
Detach(_observed);
System.Diagnostics.Debug.WriteLine("ChangesTracker: {0} hanging references.", References.Count);
System.Diagnostics.Debug.WriteLine("ChangesTracker: {0} hanging property values.", PropertyValues.Count);
Reset();
_observed = value;
Attach(_observed);
}
}
bool changed;
public bool Changed {
get { return changed; }
private set { SetProperty(ref changed, value); }
}
}
}
| gpl-3.0 |
leandrolanzieri/ciaabot-ide | typings/modules/closure/goog/dom/pattern/callback/test.d.ts | 806 | declare module goog {
function require(name: 'goog.dom.pattern.callback.Test'): typeof goog.dom.pattern.callback.Test;
}
declare module goog.dom.pattern.callback {
/**
* Callback class for testing for at least one match.
* @constructor
* @final
*/
class Test {
constructor();
/**
* Whether or not the pattern matched.
*
* @type {boolean}
*/
matched: boolean;
/**
* Get a bound callback function that is suitable as a callback for
* {@link goog.dom.pattern.Matcher}.
*
* @return {!Function} A callback function.
*/
getCallback(): Function;
/**
* Reset the counter.
*/
reset(): void;
}
}
| gpl-3.0 |
cli/sonews | sonews-modules/core/src/main/java/org/sonews/daemon/Connections.java | 4653 | /*
* SONEWS News Server
* Copyright (C) 2009-2015 Christian Lins <christian@lins.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sonews.daemon;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.logging.Level;
import org.sonews.config.Config;
import org.sonews.util.Log;
/**
* Daemon thread collecting all NNTPConnection instances. The thread checks
* periodically if there are stale/timed out connections and removes and purges
* them properly.
*
* @author Christian Lins
* @since sonews/0.5.0
*/
public final class Connections extends DaemonRunner {
private static final Connections instance = new Connections();
/**
* @return Active Connections instance.
*/
public static Connections getInstance() {
return Connections.instance;
}
private final List<NNTPConnection> connections = new ArrayList<>();
private final Map<SocketChannelWrapper, NNTPConnection> connByChannel
= new HashMap<>();
private Connections() {
}
/**
* Adds the given NNTPConnection to the Connections management.
*
* @param conn
* @see org.sonews.daemon.SynchronousNNTPConnection
*/
public void add(final NNTPConnection conn) {
synchronized (this.connections) {
this.connections.add(conn);
this.connByChannel.put(conn.getSocketChannel(), conn);
}
}
/**
* @param channel
* @return NNTPConnection instance that is associated with the given
* SocketChannel.
*/
public NNTPConnection get(final SocketChannelWrapper channel) {
synchronized (this.connections) {
return this.connByChannel.get(channel);
}
}
/**
* Run loops. Checks periodically for timed out connections and purged them
* from the lists.
*/
@Override
public void run() {
this.daemon.setName("Connections");
while (daemon.isRunning()) {
int timeoutMillis = 1000 * Config.inst().get(Config.TIMEOUT, 180);
synchronized (this.connections) {
final ListIterator<NNTPConnection> iter = this.connections
.listIterator();
NNTPConnection conn;
while (iter.hasNext()) {
conn = iter.next();
if ((System.currentTimeMillis() - conn.getLastActivity()) > timeoutMillis
&& conn.getBuffers().isOutputBufferEmpty()) {
// A connection timeout has occurred so purge the
// connection
iter.remove();
// Close and remove the channel
SocketChannelWrapper channel = conn.getSocketChannel();
connByChannel.remove(channel);
try {
assert channel != null;
// Close the channel; implicitely cancels all
// selectionkeys
channel.close();
Log.get().log(
Level.INFO,
"Disconnected: {0} (timeout)",
channel.getRemoteAddress());
} catch (IOException ex) {
Log.get().log(Level.WARNING, "Connections.run(): {0}", ex);
}
// Recycle the used buffers
conn.getBuffers().recycleBuffers();
}
}
}
try {
Thread.sleep(10000); // Sleep ten seconds
} catch (InterruptedException ex) {
Log.get().log(Level.WARNING, "Connections Thread was interrupted: {0}", ex.getMessage());
}
}
}
}
| gpl-3.0 |
glotaran/glotaran | glotaran/builtin/models/doas/test/test_doas_model.py | 9452 | import pytest
import numpy as np
import xarray as xr
from glotaran import ParameterGroup
from glotaran.builtin.models.doas import DOASModel
from glotaran.builtin.models.doas.doas_matrix import calculate_doas_matrix
class OneOscillation():
sim_model = DOASModel.from_dict({
'oscillation': {
'osc1': {'frequency': 'osc.freq', 'rate': 'osc.rate'}
},
'megacomplex': {
'm1': {'oscillation': ['osc1']}
},
'shape': {
'sh1': {
'type': "gaussian",
'amplitude': "shape.amps.1",
'location': "shape.locs.1",
'width': "shape.width.1",
},
},
'dataset': {
'dataset1': {
'megacomplex': ['m1'],
'shape': {'osc1': 'sh1'}
}
}
})
model = DOASModel.from_dict({
'oscillation': {
'osc1': {'frequency': 'osc.freq', 'rate': 'osc.rate'}
},
'megacomplex': {
'm1': {'oscillation': ['osc1']}
},
'dataset': {
'dataset1': {
'megacomplex': ['m1']
}
}
})
wanted_parameter = ParameterGroup.from_dict({
'osc': [
['freq', 25.5],
['rate', 0.1],
],
'shape': {'amps': [7], 'locs': [5], 'width': [4]},
})
parameter = ParameterGroup.from_dict({
'osc': [
['freq', 20],
['rate', 0.3],
],
})
time = np.arange(0, 3, 0.01)
spectral = np.arange(0, 10)
axis = {'time': time, 'spectral': spectral}
wanted_clp = ['osc1_cos', 'osc1_sin']
wanted_shape = (300, 2)
class OneOscillationWithIrf():
sim_model = DOASModel.from_dict({
'oscillation': {
'osc1': {'frequency': 'osc.freq', 'rate': 'osc.rate'}
},
'megacomplex': {
'm1': {'oscillation': ['osc1']}
},
'shape': {
'sh1': {
'type': "gaussian",
'amplitude': "shape.amps.1",
'location': "shape.locs.1",
'width': "shape.width.1",
},
},
'irf': {
'irf1': {'type': 'gaussian', 'center': ['irf.center'], 'width': ['irf.width']},
},
'dataset': {
'dataset1': {
'megacomplex': ['m1'],
'shape': {'osc1': 'sh1'},
'irf': 'irf1',
}
}
})
model = DOASModel.from_dict({
'oscillation': {
'osc1': {'frequency': 'osc.freq', 'rate': 'osc.rate'}
},
'megacomplex': {
'm1': {'oscillation': ['osc1']}
},
'irf': {
'irf1': {'type': 'gaussian', 'center': ['irf.center'], 'width': ['irf.width']},
},
'dataset': {
'dataset1': {
'megacomplex': ['m1'],
'irf': 'irf1',
}
}
})
wanted_parameter = ParameterGroup.from_dict({
'osc': [
['freq', 25],
['rate', 0.1],
],
'shape': {'amps': [7], 'locs': [5], 'width': [4]},
'irf': [['center', 0.3], ['width', 0.1]],
})
parameter = ParameterGroup.from_dict({
'osc': [
['freq', 25],
['rate', 0.1],
],
'irf': [['center', 0.3], ['width', 0.1]],
})
time = np.arange(0, 3, 0.01)
spectral = np.arange(0, 10)
axis = {'time': time, 'spectral': spectral}
wanted_clp = ['osc1_cos', 'osc1_sin']
wanted_shape = (300, 2)
class OneOscillationWithSequentialModel():
sim_model = DOASModel.from_dict({
'initial_concentration': {
'j1': {
'compartments': ['s1', 's2'],
'parameters': ['j.1', 'j.0']
},
},
'k_matrix': {
"k1": {'matrix': {
("s2", "s1"): 'kinetic.1',
("s2", "s2"): 'kinetic.2',
}}
},
'oscillation': {
'osc1': {'frequency': 'osc.freq', 'rate': 'osc.rate'}
},
'megacomplex': {
'm1': {
'k_matrix': ['k1'],
'oscillation': ['osc1'],
}
},
'shape': {
'sh1': {
'type': "gaussian",
'amplitude': "shape.amps.1",
'location': "shape.locs.1",
'width': "shape.width.1",
},
'sh2': {
'type': "gaussian",
'amplitude': "shape.amps.2",
'location': "shape.locs.2",
'width': "shape.width.2",
},
'sh3': {
'type': "gaussian",
'amplitude': "shape.amps.3",
'location': "shape.locs.3",
'width': "shape.width.3",
},
},
'irf': {
'irf1': {'type': 'gaussian', 'center': ['irf.center'], 'width': ['irf.width']},
},
'dataset': {
'dataset1': {
'initial_concentration': 'j1',
'megacomplex': ['m1'],
'shape': {
'osc1': 'sh1',
's1': 'sh2',
's2': 'sh3',
},
'irf': 'irf1',
}
}
})
model = DOASModel.from_dict({
'initial_concentration': {
'j1': {
'compartments': ['s1', 's2'],
'parameters': ['j.1', 'j.0']
},
},
'k_matrix': {
"k1": {'matrix': {
("s2", "s1"): 'kinetic.1',
("s2", "s2"): 'kinetic.2',
}}
},
'oscillation': {
'osc1': {'frequency': 'osc.freq', 'rate': 'osc.rate'}
},
'megacomplex': {
'm1': {
'k_matrix': ['k1'],
'oscillation': ['osc1'],
}
},
'irf': {
'irf1': {'type': 'gaussian', 'center': ['irf.center'], 'width': ['irf.width']},
},
'dataset': {
'dataset1': {
'initial_concentration': 'j1',
'megacomplex': ['m1'],
'irf': 'irf1',
}
}
})
wanted_parameter = ParameterGroup.from_dict({
'j': [
['1', 1, {'vary': False, 'non-negative': False}],
['0', 0, {'vary': False, 'non-negative': False}],
],
'kinetic': [
["1", 0.2],
["2", 0.01],
],
'osc': [
['freq', 25],
['rate', 0.1],
],
'shape': {'amps': [0.07, 2, 4], 'locs': [5, 2, 8], 'width': [4, 2, 3]},
'irf': [['center', 0.3], ['width', 0.1]],
})
parameter = ParameterGroup.from_dict({
'j': [
['1', 1, {'vary': False, 'non-negative': False}],
['0', 0, {'vary': False, 'non-negative': False}],
],
'kinetic': [
["1", 0.2],
["2", 0.01],
],
'osc': [
['freq', 25],
['rate', 0.1],
],
'irf': [['center', 0.3], ['width', 0.1]],
})
time = np.arange(-1, 5, 0.01)
spectral = np.arange(0, 10)
axis = {'time': time, 'spectral': spectral}
wanted_clp = ['osc1_cos', 'osc1_sin', 's1', 's2']
wanted_shape = (600, 4)
@pytest.mark.parametrize("suite", [
OneOscillation,
OneOscillationWithIrf,
OneOscillationWithSequentialModel,
])
def test_doas_model(suite):
print(suite.sim_model.validate())
assert suite.sim_model.valid()
print(suite.model.validate())
assert suite.model.valid()
print(suite.sim_model.validate(suite.wanted_parameter))
assert suite.sim_model.valid(suite.wanted_parameter)
print(suite.model.validate(suite.parameter))
assert suite.model.valid(suite.parameter)
dataset = suite.sim_model.dataset['dataset1'].fill(suite.sim_model, suite.wanted_parameter)
data = xr.DataArray(suite.axis['time'], coords=[('time', suite.axis['time'])])
clp, matrix = calculate_doas_matrix(dataset, suite.axis['time'], 0)
print(matrix.shape)
assert matrix.shape == suite.wanted_shape
print(clp)
assert clp == suite.wanted_clp
dataset = suite.sim_model.simulate('dataset1', suite.wanted_parameter,
suite.axis)
print(dataset)
assert dataset.data.shape == \
(suite.axis['time'].size, suite.axis['spectral'].size)
print(suite.parameter)
print(suite.wanted_parameter)
data = {'dataset1': dataset}
result = suite.model.optimize(suite.parameter, data, max_nfev=50)
print(result.optimized_parameter)
for label, param in result.optimized_parameter.all():
assert np.allclose(param.value, suite.wanted_parameter.get(label).value,
rtol=1e-1)
resultdata = result.data["dataset1"]
assert np.array_equal(dataset['time'], resultdata['time'])
assert np.array_equal(dataset['spectral'], resultdata['spectral'])
assert dataset.data.shape == resultdata.fitted_data.shape
assert np.allclose(dataset.data, resultdata.fitted_data)
assert 'dampened_oscillation_cos' in resultdata
assert 'dampened_oscillation_sin' in resultdata
assert 'dampened_oscillation_associated_spectra' in resultdata
assert 'dampened_oscillation_phase' in resultdata
| gpl-3.0 |
lejubila/piGardenWeb | vendor/caouecs/laravel-lang/src/he/validation.php | 9372 | <?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages.
|
*/
'accepted' => 'שדה :attribute חייב להיות מסומן.',
'active_url' => 'שדה :attribute הוא לא כתובת אתר תקנית.',
'after' => 'שדה :attribute חייב להיות תאריך אחרי :date.',
'after_or_equal' => 'שדה :attribute חייב להיות תאריך מאוחר או שווה ל :date.',
'alpha' => 'שדה :attribute יכול להכיל אותיות בלבד.',
'alpha_dash' => 'שדה :attribute יכול להכיל אותיות, מספרים ומקפים בלבד.',
'alpha_num' => 'שדה :attribute יכול להכיל אותיות ומספרים בלבד.',
'array' => 'שדה :attribute חייב להיות מערך.',
'before' => 'שדה :attribute חייב להיות תאריך לפני :date.',
'before_or_equal' => 'שדה :attribute חייב להיות תאריך מוקדם או שווה ל :date.',
'between' => [
'numeric' => 'שדה :attribute חייב להיות בין :min ל-:max.',
'file' => 'שדה :attribute חייב להיות בין :min ל-:max קילובייטים.',
'string' => 'שדה :attribute חייב להיות בין :min ל-:max תווים.',
'array' => 'שדה :attribute חייב להיות בין :min ל-:max פריטים.',
],
'boolean' => 'שדה :attribute חייב להיות אמת או שקר.',
'confirmed' => 'שדה האישור של :attribute לא תואם.',
'date' => 'שדה :attribute אינו תאריך תקני.',
'date_equals' => 'The :attribute must be a date equal to :date.',
'date_format' => 'שדה :attribute לא תואם את הפורמט :format.',
'different' => 'שדה :attribute ושדה :other חייבים להיות שונים.',
'digits' => 'שדה :attribute חייב להיות בעל :digits ספרות.',
'digits_between' => 'שדה :attribute חייב להיות בין :min ו-:max ספרות.',
'dimensions' => 'שדה :attribute מימדי התמונה לא תקינים',
'distinct' => 'שדה :attribute קיים ערך כפול.',
'email' => 'שדה :attribute חייב להיות כתובת אימייל תקנית.',
'exists' => 'בחירת ה-:attribute אינה תקפה.',
'file' => 'שדה :attribute חייב להיות קובץ.',
'filled' => 'שדה :attribute הוא חובה.',
'gt' => [
'numeric' => 'The :attribute must be greater than :value.',
'file' => 'The :attribute must be greater than :value kilobytes.',
'string' => 'The :attribute must be greater than :value characters.',
'array' => 'The :attribute must have more than :value items.',
],
'gte' => [
'numeric' => 'The :attribute must be greater than or equal :value.',
'file' => 'The :attribute must be greater than or equal :value kilobytes.',
'string' => 'The :attribute must be greater than or equal :value characters.',
'array' => 'The :attribute must have :value items or more.',
],
'image' => 'שדה :attribute חייב להיות תמונה.',
'in' => 'בחירת ה-:attribute אינה תקפה.',
'in_array' => 'שדה :attribute לא קיים ב:other.',
'integer' => 'שדה :attribute חייב להיות מספר שלם.',
'ip' => 'שדה :attribute חייב להיות כתובת IP תקנית.',
'ipv4' => 'שדה :attribute חייב להיות כתובת IPv4 תקנית.',
'ipv6' => 'שדה :attribute חייב להיות כתובת IPv6 תקנית.',
'json' => 'שדה :attribute חייב להיות מחרוזת JSON תקנית.',
'lt' => [
'numeric' => 'The :attribute must be less than :value.',
'file' => 'The :attribute must be less than :value kilobytes.',
'string' => 'The :attribute must be less than :value characters.',
'array' => 'The :attribute must have less than :value items.',
],
'lte' => [
'numeric' => 'The :attribute must be less than or equal :value.',
'file' => 'The :attribute must be less than or equal :value kilobytes.',
'string' => 'The :attribute must be less than or equal :value characters.',
'array' => 'The :attribute must not have more than :value items.',
],
'max' => [
'numeric' => 'שדה :attribute אינו יכול להיות גדול מ-:max.',
'file' => 'שדה :attribute לא יכול להיות גדול מ-:max קילובייטים.',
'string' => 'שדה :attribute לא יכול להיות גדול מ-:max characters.',
'array' => 'שדה :attribute לא יכול להכיל יותר מ-:max פריטים.',
],
'mimes' => 'שדה :attribute צריך להיות קובץ מסוג: :values.',
'mimetypes' => 'שדה :attribute צריך להיות קובץ מסוג: :values.',
'min' => [
'numeric' => 'שדה :attribute חייב להיות לפחות :min.',
'file' => 'שדה :attribute חייב להיות לפחות :min קילובייטים.',
'string' => 'שדה :attribute חייב להיות לפחות :min תווים.',
'array' => 'שדה :attribute חייב להיות לפחות :min פריטים.',
],
'not_in' => 'בחירת ה-:attribute אינה תקפה.',
'not_regex' => 'The :attribute format is invalid.',
'numeric' => 'שדה :attribute חייב להיות מספר.',
'present' => 'שדה :attribute חייב להיות קיים.',
'regex' => 'שדה :attribute בעל פורמט שאינו תקין.',
'required' => 'שדה :attribute הוא חובה.',
'required_if' => 'שדה :attribute נחוץ כאשר :other הוא :value.',
'required_unless' => 'שדה :attribute נחוץ אלא אם כן :other הוא בין :values.',
'required_with' => 'שדה :attribute נחוץ כאשר :values נמצא.',
'required_with_all' => 'שדה :attribute נחוץ כאשר :values נמצא.',
'required_without' => 'שדה :attribute נחוץ כאשר :values לא בנמצא.',
'required_without_all' => 'שדה :attribute נחוץ כאשר אף אחד מ-:values נמצאים.',
'same' => 'שדה :attribute ו-:other חייבים להיות זהים.',
'size' => [
'numeric' => 'שדה :attribute חייב להיות :size.',
'file' => 'שדה :attribute חייב להיות :size קילובייטים.',
'string' => 'שדה :attribute חייב להיות :size תווים.',
'array' => 'שדה :attribute חייב להכיל :size פריטים.',
],
'starts_with' => 'The :attribute must start with one of the following: :values',
'string' => 'שדה :attribute חייב להיות מחרוזת.',
'timezone' => 'שדה :attribute חייב להיות איזור תקני.',
'unique' => 'שדה :attribute כבר תפוס.',
'uploaded' => 'שדה :attribute ארעה שגיאה בעת ההעלאה.',
'url' => 'שדה :attribute בעל פורמט שאינו תקין.',
'uuid' => 'The :attribute must be a valid UUID.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [
],
];
| gpl-3.0 |
lkdjiin/Personal-Bug-Tracker | src/desktopbugtracker/dialog/DialogChangePriority.java | 8955 | /*
* This file is part of Personal Bug Tracker.
* Copyright (C) 2009, Xavier Nayrac
*
* Personal Bug Tracker 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 desktopbugtracker.dialog;
import desktopbugtracker.data.ApplicationConfig;
import desktopbugtracker.component.Priority;
import desktopbugtracker.dao.PriorityDAO;
import desktopbugtracker.renderer.PriorityRenderer;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
/**
*
* @author xavier
*/
public class DialogChangePriority extends javax.swing.JDialog {
/** A return status code - returned if Cancel button has been pressed */
public static final int RET_CANCEL = 0;
/** A return status code - returned if OK button has been pressed */
public static final int RET_OK = 1;
/**
* Use this to set the dialog to change the priority of a bug.
*/
public static final int MODE_CHANGE = 0;
/**
* Use this to set the dialog to choose/select/pick a priority.
*/
public static final int MODE_CHOOSE = 1;
DefaultListModel dlm;
Priority newPriority;
/** Creates new form DialogChangePriority */
public DialogChangePriority(java.awt.Frame parent, boolean modal, int mode) {
super(parent, modal);
dlm = new DefaultListModel();
Vector<Priority> vPriority = new Vector<Priority>();
try {
vPriority = PriorityDAO.read();
} catch (SQLException ex) {
Logger.getLogger(DialogChangePriority.class.getName()).log(Level.SEVERE, null, ex);
}
for (Priority e : vPriority) {
// Zéro est une priorité spéciale, uniquement pour la consultation.
if (e.pri_number != 0) {
dlm.addElement(e);
}
}
initComponents();
this.getRootPane().setDefaultButton(okButton);
if (mode == MODE_CHOOSE) {
jLabel1.setText(java.util.ResourceBundle.getBundle("desktopbugtracker/Bundle", ApplicationConfig.getLocale()).getString("Pick_a_priority"));
}
setLocationRelativeTo(parent);
setVisible(true);
}
/** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
public int getReturnStatus() {
return returnStatus;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
closeDialog(evt);
}
});
okButton.setText("OK");
okButton.setEnabled(false);
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("desktopbugtracker/Bundle", ApplicationConfig.getLocale()); // NOI18N
cancelButton.setText(bundle.getString("Cancel")); // NOI18N
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("sansserif", 0, 18)); // NOI18N
jLabel1.setText(bundle.getString("Change_Priority")); // NOI18N
jList1.setModel(dlm);
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setCellRenderer(new PriorityRenderer());
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton))
.addComponent(jLabel1)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(okButton))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
newPriority = (Priority) jList1.getSelectedValue();
doClose(RET_OK);
}//GEN-LAST:event_okButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
doClose(RET_CANCEL);
}//GEN-LAST:event_cancelButtonActionPerformed
/** Closes the dialog */
private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
doClose(RET_CANCEL);
}//GEN-LAST:event_closeDialog
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
okButton.setEnabled(true);
}//GEN-LAST:event_jList1ValueChanged
private void doClose(int retStatus) {
returnStatus = retStatus;
setVisible(false);
dispose();
}
public Priority getNewPriority() {
return newPriority;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton okButton;
// End of variables declaration//GEN-END:variables
private int returnStatus = RET_CANCEL;
}
| gpl-3.0 |
NZMSA/2017-AdvTraining | Day 2/2.5 Integrating EasyTables with NodeJS(Post)/Project Files/controller/LuisDialog.js | 4665 | var builder = require('botbuilder');
var food = require("./FavouriteFoods");
// Some sections have been omitted
var isAttachment = false;
exports.startDialog = function (bot) {
// Replace {YOUR_APP_ID_HERE} and {YOUR_KEY_HERE} with your LUIS app ID and your LUIS key, respectively.
var recognizer = new builder.LuisRecognizer('https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/a60b1df0-f068-4d7d-8dd1-87b95d1bb02c?subscription-key=c2def163238d4646a900f56a275998bc&verbose=true&timezoneOffset=0&q=');
bot.recognizer(recognizer);
bot.dialog('GetCalories', function (session, args) {
session.send("Get Calories intent found");
}).triggerAction({
matches: 'GetCalories'
});
bot.dialog('GetFavouriteFood', [
function (session, args, next) {
session.dialogData.args = args || {};
if (!session.conversationData["username"]) {
builder.Prompts.text(session, "Enter a username to setup your account.");
} else {
next(); // Skip if we already have this info.
}
},
function (session, results, next) {
if (results.response) {
session.conversationData["username"] = results.response;
}
session.send("Retrieving your favourite foods");
food.displayFavouriteFood(session, session.conversationData["username"]); // <---- THIS LINE HERE IS WHAT WE NEED
}
]).triggerAction({
matches: 'GetFavouriteFood'
});
bot.dialog('DeleteFavourite', [
function (session, args, next) {
session.dialogData.args = args || {};
if (!session.conversationData["username"]) {
builder.Prompts.text(session, "Enter a username to setup your account.");
} else {
next(); // Skip if we already have this info.
}
},
function (session, results,next) {
//Add this code in otherwise your username will not work.
if (results.response) {
session.conversationData["username"] = results.response;
}
session.send("You want to delete one of your favourite foods.");
// Pulls out the food entity from the session if it exists
var foodEntity = builder.EntityRecognizer.findEntity(session.dialogData.args.intent.entities, 'food');
// Checks if the for entity was found
if (foodEntity) {
session.send('Deleting \'%s\'...', foodEntity.entity);
food.deleteFavouriteFood(session,session.conversationData['username'],foodEntity.entity); //<--- CALLL WE WANT
} else {
session.send("No food identified! Please try again");
}
}]).triggerAction({
matches: 'DeleteFavourite'
});
bot.dialog('WantFood', function (session, args) {
session.send("WantFood intent found");
}).triggerAction({
matches: 'WantFood'
});
bot.dialog('WelcomeIntent', function (session, args) {
session.send("WelcomeIntent intent found");
}).triggerAction({
matches: 'WelcomeIntent'
});
bot.dialog('LookForFavourite', [
function (session, args, next) {
session.dialogData.args = args || {};
if (!session.conversationData["username"]) {
builder.Prompts.text(session, "Enter a username to setup your account.");
} else {
next(); // Skip if we already have this info.
}
},
function (session, results, next) {
if (results.response) {
session.conversationData["username"] = results.response;
}
// Pulls out the food entity from the session if it exists
var foodEntity = builder.EntityRecognizer.findEntity(session.dialogData.args.intent.entities, 'food');
// Checks if the food entity was found
if (foodEntity) {
session.send('Thanks for telling me that \'%s\' is your favourite food', foodEntity.entity);
food.sendFavouriteFood(session, session.conversationData["username"], foodEntity.entity); // <-- LINE WE WANT
} else {
session.send("No food identified!!!");
}
}
]).triggerAction({
matches: 'LookForFavourite'
});
} | gpl-3.0 |
guardicore/monkey | monkey/monkey_island/cc/ui/src/components/report-components/AttackReport.js | 6550 | import React from 'react';
import {Col, Button} from 'react-bootstrap';
import '../../styles/components/Collapse.scss';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {faCircle} from '@fortawesome/free-solid-svg-icons/faCircle';
import {faRadiation} from '@fortawesome/free-solid-svg-icons/faRadiation';
import {faEye} from '@fortawesome/free-solid-svg-icons/faEye';
import {faEyeSlash} from '@fortawesome/free-solid-svg-icons/faEyeSlash';
import {faToggleOff} from '@fortawesome/free-solid-svg-icons/faToggleOff';
import marked from 'marked';
import ReportHeader, {ReportTypes} from './common/ReportHeader';
import {ScanStatus} from '../attack/techniques/Helpers';
import Matrix from './attack/ReportMatrixComponent';
import SelectedTechnique from './attack/SelectedTechnique';
import TechniqueDropdowns from './attack/TechniqueDropdowns';
import ReportLoader from './common/ReportLoader';
const techComponents = getAllAttackModules();
function getAllAttackModules() {
let context = require.context('../attack/techniques/', false, /\.js$/);
let obj = {};
context.keys().forEach(function (key) {
let techName = key.replace(/\.js/, '');
techName = String(techName.replace(/\.\//, ''));
obj[techName] = context(key).default;
});
return obj;
}
class AttackReport extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedTechnique: false,
collapseOpen: ''
};
if (typeof this.props.report.schema !== 'undefined' && typeof this.props.report.techniques !== 'undefined'){
this.state['schema'] = this.props.report['schema'];
this.state['techniques'] = AttackReport.modifyTechniqueData(this.props.report['schema'], this.props.report['techniques']);
}
}
componentDidUpdate(prevProps) {
if (this.props.report !== prevProps.report) {
this.setState({schema: this.props.report['schema'],
techniques: AttackReport.modifyTechniqueData(this.props.report['schema'], this.props.report['techniques'])})
}
}
onTechniqueSelect = (technique, _) => {
let selectedTechnique = this.getTechniqueByTitle(technique);
if (selectedTechnique === false){
return;
}
this.setState({selectedTechnique: selectedTechnique.tech_id})
};
static getComponentClass(tech_id, techniques) {
switch (techniques[tech_id].status) {
case ScanStatus.SCANNED:
return 'collapse-warning';
case ScanStatus.USED:
return 'collapse-danger';
case ScanStatus.DISABLED:
return 'collapse-disabled';
default:
return 'collapse-default';
}
}
static getStatusIcon(tech_id, techniques){
switch (techniques[tech_id].status){
case ScanStatus.SCANNED:
return <FontAwesomeIcon icon={faEye} className={'technique-status-icon'}/>;
case ScanStatus.USED:
return <FontAwesomeIcon icon={faRadiation} className={'technique-status-icon'}/>;
case ScanStatus.DISABLED:
return <FontAwesomeIcon icon={faToggleOff} className={'technique-status-icon'}/>;
default:
return <FontAwesomeIcon icon={faEyeSlash} className={'technique-status-icon'}/>;
}
}
renderLegend() {
return (<div id='header' className='row justify-content-between attack-legend'>
<Col xs={3}>
<FontAwesomeIcon icon={faCircle} className='technique-disabled'/>
<span> - Disabled</span>
</Col>
<Col xs={3}>
<FontAwesomeIcon icon={faCircle} className='technique-not-attempted'/>
<span> - Not attempted</span>
</Col>
<Col xs={3}>
<FontAwesomeIcon icon={faCircle} className='technique-attempted'/>
<span> - Tried (but failed)</span>
</Col>
<Col xs={3}>
<FontAwesomeIcon icon={faCircle} className='technique-used'/>
<span> - Successfully used</span>
</Col>
</div>)
}
generateReportContent() {
return (
<div>
<p>
This report shows information about
<Button variant={'link'}
href={'https://attack.mitre.org/'}
size={'lg'}
className={'attack-link'}
target={'_blank'}>
Mitre ATT&CK™
</Button>
techniques used by Infection Monkey.
</p>
{this.renderLegend()}
<Matrix techniques={this.state.techniques} schema={this.state.schema} onClick={this.onTechniqueSelect}/>
<SelectedTechnique techComponents={techComponents}
techniques={this.state.techniques}
selected={this.state.selectedTechnique}/>
<TechniqueDropdowns techniques={this.state.techniques}
techComponents={techComponents}
schema={this.state.schema}/>
<br/>
</div>
)
}
getTechniqueByTitle(title){
for (const tech_id in this.state.techniques){
if (! Object.prototype.hasOwnProperty.call(this.state.techniques, tech_id)) {return false;}
let technique = this.state.techniques[tech_id];
if (technique.title === title){
technique['tech_id'] = tech_id;
return technique
}
}
return false;
}
static modifyTechniqueData(schema, techniques){
// add links to techniques
schema = schema.properties;
for(const type in schema){
if (! Object.prototype.hasOwnProperty.call(schema, type)) {return false;}
let typeTechniques = schema[type].properties;
for(const tech_id in typeTechniques){
if (! Object.prototype.hasOwnProperty.call(typeTechniques, tech_id)) {return false;}
if (typeTechniques[tech_id] !== undefined){
techniques[tech_id]['link'] = typeTechniques[tech_id].link
}
}
}
// compiles techniques' message string from markdown to HTML
for (const tech_id in techniques){
techniques[tech_id]['message_html'] = <div dangerouslySetInnerHTML={{__html: marked(techniques[tech_id]['message'])}} />;
}
return techniques
}
render() {
let content = {};
if (typeof this.state.schema === 'undefined' || typeof this.state.techniques === 'undefined') {
content = <ReportLoader/>;
} else {
content = <div> {this.generateReportContent()}</div>;
}
return (
<div id='attack' className='attack-report report-page'>
<ReportHeader report_type={ReportTypes.attack}/>
<hr/>
{content}
</div>)
}
}
export default AttackReport;
| gpl-3.0 |
psci2195/espresso-ffans | src/utils/include/utils/make_function.hpp | 2317 | /*
* Copyright (C) 2010-2019 The ESPResSo project
*
* This file is part of ESPResSo.
*
* ESPResSo 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.
*
* ESPResSo 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 UTILS_MAKE_FUNCTION_HPP
#define UTILS_MAKE_FUNCTION_HPP
#include <functional>
#include "type_traits.hpp"
namespace Utils {
namespace detail {
template <class FPtr> struct function_traits;
/**
* @brief Determine the signature from a pointer to member function (C::*).
*/
template <class T, class C> struct function_traits<T(C::*)> { typedef T type; };
} // namespace detail
/* make_function deduces the signature of a class with not-overloaded operator()
member , a lambda or std::function,
and creates a corresponding std::function. This is needed to solve some
issues with
template parameter deduction if the type is not known beforehand. */
/**
* @brief Given a std::function, return a copy.
*
* For a std::function argument nothing has to be done, just a copy is returned.
*/
template <typename T, typename... Args>
std::function<T(Args...)> make_function(std::function<T(Args...)> const &f) {
return f;
}
/**
* @brief Given a Functor or a Closure, return a std::function with the same
* signature that contains a copy of the argument.
*
* This inspects the operator() on the given type, deduces the signature,
* if operator() is const, as in non-mutable lambdas, the const is removed,
* and a std::function with the correct type, containing a copy, is returned.
*/
template <
typename F,
typename Signature = typename Utils::function_remove_const<
typename detail::function_traits<decltype(&F::operator())>::type>::type>
std::function<Signature> make_function(F const &f) {
return f;
}
} /* namespace Utils */
#endif
| gpl-3.0 |
danielquinn/ripe-atlas-tools | ripe/atlas/tools/commands/configure.py | 4276 | # Copyright (c) 2015 RIPE NCC
#
# 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 functools
import os
from ..exceptions import RipeAtlasToolsException
from ..settings import Configuration, conf
from .base import Command as BaseCommand
class Command(BaseCommand):
NAME = "configure"
EDITOR = os.environ.get("EDITOR", "/usr/bin/vim")
DESCRIPTION = "An easy way to configure this tool. Alternatively, you " \
"can always just create/edit {}".format(Configuration.USER_RC)
def add_arguments(self):
self.parser.add_argument(
"--editor",
action="store_true",
help="Invoke {0} to edit the configuration directly".format(
self.EDITOR)
)
self.parser.add_argument(
"--set",
action="store",
help="Permanently set a configuration value so it can be used in "
"the future. Example: --set authorisation.create=MY_API_KEY"
)
self.parser.add_argument(
"--init",
action="store_true",
help="Create a configuration file and save it into your home "
"directory at: {}".format(Configuration.USER_RC)
)
def run(self):
if not self.arguments.init:
if not self.arguments.editor:
if not self.arguments.set:
raise RipeAtlasToolsException(
"Run this with --help for more information")
self._create_if_necessary()
if self.arguments.editor:
os.system("{0} {1}".format(self.EDITOR, Configuration.USER_RC))
if self.arguments.init or self.arguments.editor:
return self.ok(
"Configuration file writen to {}".format(Configuration.USER_RC))
if self.arguments.set:
if "=" not in self.arguments.set:
raise RipeAtlasToolsException(
"Invalid format. Execute with --help for more information.")
path, value = self.arguments.set.split("=")
self.set(path.split("."), value)
def set(self, path, value):
try:
required_type = type(self._get_from_dict(conf, path))
except KeyError:
raise RipeAtlasToolsException(
'Invalid configuration key: "{}"'.format(".".join(path)))
if value.isdigit():
value = int(value)
if not isinstance(value, required_type):
raise RipeAtlasToolsException(
'Invalid configuration value: "{}". You must supply a {} for '
'this key'.format(value, required_type.__name__)
)
self._set_in_dict(conf, path, value)
Configuration.write(conf)
@staticmethod
def _create_if_necessary():
if os.path.exists(Configuration.USER_RC):
return
if not os.path.exists(Configuration.USER_CONFIG_DIR):
os.makedirs(Configuration.USER_CONFIG_DIR)
Configuration.write(conf)
@staticmethod
def _get_from_dict(data, path):
return functools.reduce(lambda d, k: d[k], path, data)
@classmethod
def _set_in_dict(cls, data, path, value):
cls._get_from_dict(data, path[:-1])[path[-1]] = value
@staticmethod
def cast_value(value):
# Booleans are a pain in the ass to cast
if value.lower() == "true":
return True
if value.lower() == "false":
return False
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
return str(value)
| gpl-3.0 |
wlx65003/HZNUOJ | web/OJ/status-ajax.php | 2095 | <?php
/**
* This file is modified!
* by yybird
* @2015.07.02
**/
?>
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
////////////////////////////Common head
$cache_time=2;
$OJ_CACHE_SHARE=false;
require_once('./include/db_info.inc.php');
require_once('./include/setlang.php');
$view_title= "$MSG_STATUS";
require_once("./include/const.inc.php");
$solution_id=0;
// check the top arg
if (isset($_GET['solution_id'])){
$solution_id=intval($_GET['solution_id']);
}
$sql="select * from solution where solution_id=$solution_id LIMIT 1";
//echo $sql;
if($OJ_MEMCACHE){
require("./include/memcache.php");
$result = $mysqli->query_cache($sql);// or die("Error! ".$mysqli->error);
if($result) $rows_cnt=count($result);
else $rows_cnt=0;
} else {
$result = $mysqli->query($sql);// or die("Error! ".$mysqli->error);
if($result)
$rows_cnt=$result->num_rows;
else
$rows_cnt=0;
}
for ($i=0; $i<$rows_cnt; $i++){
if($OJ_MEMCACHE)
$row=$result[$i];
else
$row=$result->fetch_array();
if(isset($_GET['tr'])){
$res=$row['result'];
if ($res==11) {
$sql="SELECT `error` FROM `compileinfo` WHERE `solution_id`='".$solution_id."'";
} else {
$sql="SELECT `error` FROM `runtimeinfo` WHERE `solution_id`='".$solution_id."'";
}
$result=$mysqli->query($sql);
$row=$result->fetch_array();
if($row){
if(strpos($_SERVER['HTTP_USER_AGENT'], "MSIE"))
echo str_replace("\n","<br>",htmlspecialchars(str_replace("\n\r","\n",$row['error'])));
else
echo htmlspecialchars(str_replace("\n\r","\n",$row['error']));
$sql="delete from custominput where solution_id=".$solution_id;
$mysqli->query($sql);
}
//echo $sql.$res;
}else{
echo $row['result'].",".$row['memory'].",".$row['time'];
//echo "hhhh".",".$row['memory'].",".$row['time'];
}
}
if(!$OJ_MEMCACHE)$result->free();
?> | gpl-3.0 |
maratgaip/MusicApp | scripts/components/MobileSongListItem.js | 1065 | import React, { Component, PropTypes } from 'react';
import { getImageUrl } from '../utils/SongUtils';
const propTypes = {
isActive: PropTypes.bool.isRequired,
playSong: PropTypes.func.isRequired,
song: PropTypes.object.isRequired,
user: PropTypes.object.isRequired,
};
class MobileSongListItem extends Component {
render() {
const { isActive, playSong, song, user } = this.props;
return (
<a
className={`mobile-song-list-item ${(isActive ? ' active' : '')}`}
href="#"
onClick={playSong}
>
<img
alt="song artwork"
className="mobile-song-list-item-image"
src={getImageUrl(song.artwork_url)}
/>
<div className="mobile-song-list-item-info">
<div className="mobile-song-list-item-title">
{song.title}
</div>
<div className="mobile-song-list-item-user">
{user.username}
</div>
</div>
</a>
);
}
}
MobileSongListItem.propTypes = propTypes;
export default MobileSongListItem;
| gpl-3.0 |
domainmod/domainmod | cron.php | 6784 | <?php
/**
* /cron.php
*
* This file is part of DomainMOD, an open source domain and internet asset manager.
* Copyright (c) 2010-2021 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
require_once __DIR__ . '/_includes/init.inc.php';
require_once DIR_INC . '/config.inc.php';
require_once DIR_INC . '/software.inc.php';
require_once DIR_ROOT . '/vendor/autoload.php';
$conversion = new DomainMOD\Conversion();
$deeb = DomainMOD\Database::getInstance();
$log = new DomainMOD\Log('/cron.php');
$maint = new DomainMOD\Maintenance();
$schedule = new DomainMOD\Scheduler();
$system = new DomainMOD\System();
$time = new DomainMOD\Time();
require_once DIR_INC . '/head.inc.php';
require_once DIR_INC . '/config-demo.inc.php';
require_once DIR_INC . '/debug.inc.php';
$pdo = $deeb->cnxx;
if (DEMO_INSTALLATION == false) {
$pdo->query("UPDATE scheduler SET is_running = '0'");
$stmt = $pdo->prepare("
SELECT id, `name`, slug, expression, active
FROM scheduler
WHERE active = '1'
AND is_running = '0'
AND next_run <= :next_run");
$bind_timestamp = $time->stamp();
$stmt->bindValue('next_run', $bind_timestamp, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
if (!$result) {
$log_message = 'No scheduled tasks to run';
$log->info($log_message);
} else {
foreach ($result as $row) {
$cron = \Cron\CronExpression::factory($row->expression);
$next_run = $cron->getNextRunDate()->format('Y-m-d H:i:s');
$log_extra = array('Task ID' => $row->id, 'Name' => $row->name, 'Slug' => $row->slug, 'Expression' => $row->expression, 'Active' => $row->active, 'Next Run' => $next_run);
if ($row->slug == 'cleanup') {
$log_message = sprintf('[%s]' . _('Cleanup Tasks'), strtoupper(_('Start')));
$log->notice($log_message, $log_extra);
$schedule->isRunning($row->id);
$maint->performCleanup();
$schedule->updateTime($row->id, $time->stamp(), $next_run);
$schedule->isFinished($row->id);
$log_message = sprintf('[%s]' . _('Cleanup Tasks'), strtoupper(_('End')));
$log->notice($log_message);
} elseif ($row->slug == 'expiration-email') {
$log_message = sprintf('[%s]' . _('Send Expiration Email'), strtoupper(_('Start')));
$log->notice($log_message, $log_extra);
$email = new DomainMOD\Email();
$schedule->isRunning($row->id);
$email->sendExpirations(true);
$schedule->updateTime($row->id, $time->stamp(), $next_run);
$schedule->isFinished($row->id);
$log_message = sprintf('[%s]' . _('Send Expiration Email'), strtoupper(_('End')));
$log->notice($log_message);
} elseif ($row->slug == 'update-conversion-rates') {
$log_message = sprintf('[%s]' . _('Update Conversion Rates'), strtoupper(_('Start')));
$log->notice($log_message, $log_extra);
$schedule->isRunning($row->id);
$result_conversion = $pdo->query("
SELECT user_id, default_currency
FROM user_settings")->fetchAll();
if (!$result_conversion) {
$log_message = 'No user currencies found';
$log->critical($log_message);
} else {
foreach ($result_conversion as $row_conversion) {
$conversion->updateRates($row_conversion->default_currency, $row_conversion->user_id, true);
}
}
$schedule->updateTime($row->id, $time->stamp(), $next_run);
$schedule->isFinished($row->id);
$log_message = sprintf('[%s]' . _('Update Conversion Rates'), strtoupper(_('End')));
$log->notice($log_message);
} elseif ($row->slug == 'check-new-version') {
$log_message = sprintf('[%s]' . _('New Version Check'), strtoupper(_('Start')));
$log->notice($log_message, $log_extra);
$schedule->isRunning($row->id);
$system->checkVersion(SOFTWARE_VERSION);
$schedule->updateTime($row->id, $time->stamp(), $next_run);
$schedule->isFinished($row->id);
$log_message = sprintf('[%s]' . _('New Version Check'), strtoupper(_('End')));
$log->notice($log_message);
} elseif ($row->slug == 'data-warehouse-build') {
$log_message = sprintf('[%s]' . _('Build Data Warehouse'), strtoupper(_('Start')));
$log->notice($log_message, $log_extra);
$dw = new DomainMOD\DwBuild();
$schedule->isRunning($row->id);
$dw->build();
$schedule->updateTime($row->id, $time->stamp(), $next_run);
$schedule->isFinished($row->id);
$log_message = sprintf('[%s]' . _('Build Data Warehouse'), strtoupper(_('End')));
$log->notice($log_message);
} elseif ($row->slug == 'domain-queue') {
$log_message = sprintf('[%s]' . _('Process Domain Queue'), strtoupper(_('Start')));
$log->notice($log_message, $log_extra);
$queue = new DomainMOD\DomainQueue();
$schedule->isRunning($row->id);
$queue->processQueueList();
$queue->processQueueDomain();
$schedule->updateTime($row->id, $time->stamp(), $next_run);
$schedule->isFinished($row->id);
$log_message = sprintf('[%s]' . _('Process Domain Queue'), strtoupper(_('End')));
$log->notice($log_message);
} else {
$log_message = 'There are results, but no matching slugs';
$log->critical($log_message, $log_extra);
}
}
}
}
| gpl-3.0 |
domcleal/smart-proxy | lib/bmc_api.rb | 8026 | require 'proxy/bmc'
class SmartProxy < Sinatra::Base
# All GET requests will only read ipmi data, no changes
# All PUT requests will update information on the bmc device
get "/bmc" do
# return list of available options
end
# Returns a list of bmc providers
get "/bmc/providers" do
{ :providers => Proxy::BMC.providers }.to_json
end
# Returns a list of installed providers
get "/bmc/providers/installed" do
{ :installed_providers => Proxy::BMC.installed_providers? }.to_json
end
# returns host operations
get "/bmc/:host" do
{ :actions => %w[chassis lan] }.to_json
end
# returns chassis operations
get "/bmc/:host/chassis" do
{ :actions => %w[power identify config] }.to_json
end
# Gets the power status, does not change power
get "/bmc/:host/chassis/power/?:action?" do
# return hint on valid options
if params[:action].nil?
return { :actions => ["on", "off", "status"] }.to_json
end
bmc_setup
begin
case params[:action]
when "status"
{ :action => params[:action], :result => @bmc.powerstatus }.to_json
when "off"
{ :action => params[:action], :result => @bmc.poweroff? }.to_json
when "on"
{ :action => params[:action], :result => @bmc.poweron? }.to_json
else
{ :error => "The action: #{params[:action]} is not a valid action" }.to_json
end
rescue => e
log_halt 400, e
end
end
get "/bmc/:host/lan/?:action?" do
if params[:action].nil?
return { :actions => ["ip", "netmask", "mac", "gateway"] }.to_json
end
bmc_setup
begin
case params[:action]
when "ip"
{ :action => params[:action], :result => @bmc.ip }.to_json
when "netmask"
{ :action => params[:action], :result => @bmc.netmask }.to_json
when "mac"
{ :action => params[:action], :result => @bmc.mac }.to_json
when "gateway"
{ :action => params[:action], :result => @bmc.gateway }.to_json
else
{ :error => "The action: #{params[:action]} is not a valid action" }.to_json
end
rescue => e
log_halt 400, e
end
end
get "/bmc/:host/chassis/identify/?:action?" do
# return hint on valid options
if params[:action].nil?
return { :actions => ["status"] }.to_json
end
bmc_setup
# determine which function should be executed
begin
case params[:action]
when "status"
{ :action => params[:action], :result => @bmc.identifystatus }.to_json
else
{ :error => "The action: #{params[:action]} is not a valid action" }.to_json
end
rescue => e
log_halt 400, e
end
end
get "/bmc/:host/chassis/config/?:function?" do
# return hint on valid options
# removing bootdevice until its supported in rubyipmi
if params[:function].nil?
#return {:actions => ["bootdevice", "bootdevices"]}.to_json
return { :functions => ["bootdevices"] }.to_json
end
bmc_setup
begin
case params[:function]
#when "bootdevice"
# @bmc.chassis.config.bootdevice.to_json
when "bootdevices"
{ :devices => @bmc.bootdevices }.to_json
else
{ :error => "The action: #{params[:function]} is not a valid function" }.to_json
end
rescue => e
log_halt 400, e
end
end
put "/bmc/:host/chassis/power/?:action?" do
# return hint on valid options
if params[:action].nil?
return { :actions => ["on", "off", "cycle", "soft"] }.to_json
end
bmc_setup
begin
case params[:action]
when "on"
{ :action => params[:action], :result => @bmc.poweron }.to_json
when "off"
{ :action => params[:action], :result => @bmc.poweroff }.to_json
when "cycle"
{ :action => params[:action], :result => @bmc.powercycle }.to_json
when "soft"
{ :action => params[:action], :result => @bmc.poweroff(true) }.to_json
else
{ :error => "The action: #{params[:action]} is not a valid action" }.to_json
end
rescue => e
log_halt 400, e
end
end
put "/bmc/:host/chassis/config/?:function?/?:action?" do
if params[:function].nil?
return { :functions => ["bootdevice"] }.to_json
end
bmc_setup
begin
case params[:function]
when "bootdevice"
if params[:action].nil?
return { :actions => @bmc.bootdevices, :options => ["reboot", "persistent"] }.to_json
end
case params[:action]
when /pxe/
{ :action => params[:action], :result => @bmc.bootpxe(params[:reboot], params[:persistent]) }.to_json
when /cdrom/
{ :action => params[:action], :result => @bmc.bootcdrom(params[:reboot], params[:persistent]) }.to_json
when /bios/
{ :action => params[:action], :result => @bmc.bootbios(params[:reboot], params[:persistent]) }.to_json
when /disk/
{ :action => params[:action], :result => @bmc.bootdisk(params[:reboot], params[:persistent]) }.to_json
else
if @bmc.bootdevices.include?(params[:action])
{ :action => params[:action], :result => @bmc.bootdevice({ :device => params[:action],
:reboot => params[:reboot],
:persistent => params[:persistent] }) }.to_json
else
{ :error => "#{params[:action]} is not a valid boot device" }.to_json
end
end
else
{ :error => "The action: #{params[:function]} is not a valid function" }.to_json
end
rescue => e
log_halt 400, e
end
end
put "/bmc/:host/chassis/identify/?:action?" do
if params[:action].nil?
return { :actions => ["on", "off"] }.to_json
end
bmc_setup
begin
case params[:action]
when "on"
{ :action => params[:action], :result => @bmc.identifyon }.to_json
when "off"
{ :action => params[:action], :result => @bmc.identifyoff }.to_json
else
{ :error => "The action: #{params[:function]} is not a valid function" }.to_json
end
rescue => e
log_halt 400, e
end
end
private
def bmc_setup
raise "Smart Proxy is not configured to support BMC control" unless SETTINGS.bmc
# Either use the default provider or allow user to specify provider in request
provider_type ||= params[:bmc_provider] || SETTINGS.bmc_default_provider
provider_type.downcase! if provider_type
case provider_type
when /ipmi/
require 'proxy/bmc/ipmi'
raise "unauthorized" unless auth.provided?
raise "bad_authentication_request" unless auth.basic?
username, password = auth.credentials
# check to see if provider is given and no default provider is set, search for installed providers
unless Proxy::BMC::IPMI.installed?(provider_type)
# check if provider_type is a valid type
if Proxy::BMC::IPMI.providers.include?(provider_type)
log_halt 400, "#{provider_type} is not installed, please install a ipmi provider"
else
log_halt 400, "Unrecognized or missing bmc provider type: #{provider_type}"
end
end
# all the use of the http auth basic header to pass credentials
args = { :host => params[:host], :username => username,
:password => password, :bmc_provider => provider_type }
@bmc = Proxy::BMC::IPMI.new(args)
when "shell"
require 'proxy/bmc/shell'
@bmc = Proxy::BMC::Shell.new
else
log_halt 400, "Unrecognized or missing BMC type: #{provider_type}"
end
rescue => e
log_halt 400, e
end
def auth
@auth ||= Rack::Auth::Basic::Request.new(request.env)
end
end
| gpl-3.0 |
adixcompany/self | plugins/tools.lua | 18274 | --Tools.lua :D
local function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
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 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 action_by_reply(arg, data)
local cmd = arg.cmd
if data.sender_user_id_ then
if cmd == "block" then
tdcli.blockUser(data.sender_user_id_, dl_cb, nil)
tdcli.sendMessage(data.chat_id_, data.id_, 0, "_User_ *"..data.sender_user_id_.."* _Has Been_ *Blocked*", 0, "md")
end
if cmd == "unblock" then
tdcli.unblockUser(data.sender_user_id_, dl_cb, nil)
tdcli.sendMessage(data.chat_id_, data.id_, 0, "_User_ *"..data.sender_user_id_.."* _Has Been_ *Unblocked*", 0, "md")
end
else
return tdcli.sendMessage(data.chat_id_, "", 0, "*User not founded*", 0, "md")
end
end
local function action_by_username(arg, data)
local cmd = arg.cmd
if data.id_ then
if cmd == "block" then
tdcli.blockUser(data.id_, dl_cb, nil)
tdcli.sendMessage(arg.chat_id, "", 0, "_User_ *"..data.id_.."* _Has Been_ *Blocked*", 0, "md")
end
if cmd == "unblock" then
tdcli.unblockUser(data.id_, dl_cb, nil)
tdcli.sendMessage(arg.chat_id, "", 0, "_User_ *"..data.id_.."* _Has Been_ *Unblocked*", 0, "md")
end
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User not founded*", 0, "md")
end
end
local function get_variables_hash(msg)
if msg.to.type == 'chat' or msg.to.type == 'channel' then
return 'chat:bot:variables'
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
local function list_chats(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'bot replyes :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
local function save_value(msg, name, value)
if (not name or not value) then
return "Usage: !set var_name value"
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hset(hash, name, value)
return "_Saved_ *"..name.."*"
end
end
local function del_value(msg, name)
if not name then
return
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hdel(hash, name)
return "_Removed_ *"..name.."*"
end
end
local function delallchats(msg)
local hash = 'chat:bot:variables'
if hash then
local names = redis:hkeys(hash)
for i=1, #names do
redis:hdel(hash,names[i])
end
return "*Done!*"
else
return
end
end
local function run(msg, matches)
local chat = msg.to.id
local user = msg.from.id
if matches[1] == "clear cache" and tonumber(msg.from.id) == our_id 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] == "block" 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="block"})
end
if matches[2] and string.match(matches[2], '^%d+$') and not msg.reply_id then
tdcli.blockUser(matches[2], dl_cb, nil)
return "_User_ *"..matches[2].."* _Has Been_ *Blocked*"
end
if matches[2] and not string.match(matches[2], '^%d+$') and not msg.reply_id then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="block"})
end
end
if matches[1] == "unblock" 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="unblock"})
end
if matches[2] and string.match(matches[2], '^%d+$') and not msg.reply_id then
tdcli.unblockUser(matches[2], dl_cb, nil)
return "_User_ *"..matches[2].."* _Has Been_ *Unblocked*"
end
if matches[2] and not string.match(matches[2], '^%d+$') and not msg.reply_id then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="unblock"})
end
end
if matches[1] == 'addplugin' and is_sudo(msg) then
if not is_sudo(msg) then
return '_You Are Not Allowed To Add Plugin_'
end
text = matches[2]
name = matches[3]
file = io.open('./plugins/'..name, 'w')
file:write(text)
file:flush()
file:close()
return '_Plugin_ *['..matches[3]..']* _Has Been Added_'
end
if matches[1] == "delplugin" and is_sudo(msg) then
if not is_sudo(msg) then
return "_You Are Not Allow To Delete Plugins!_"
end
io.popen("cd plugins && rm "..matches[2]..".lua")
return "*Done!*"
end
if is_sudo(msg) then
if matches[1]:lower() == "sendfile" 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, '@adixco', dl_cb, nil)
end
if matches[1]:lower() == "sendplug" and matches[2] then
local plug = "./plugins/"..matches[2]..".lua"
tdcli.sendDocument(msg.chat_id_, msg.id_,0,
1, nil, plug, '@adixco', dl_cb, nil)
end
end
if matches[1]:lower() == 'save' 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]:lower() == 'savefile' 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)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>File</b> <code>'..folder..'</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
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)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Photo</b> <code>'..folder..'</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
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)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Sticker</b> <code>'..folder..'</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
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)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Audio</b> <code>'..folder..'</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
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)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Voice</b> <code>'..folder..'</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
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)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Video</b> <code>'..folder..'</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
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)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Gif</b> <code>'..folder..'</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
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] == 'markread' and is_sudo(msg) then
if matches[2] == 'on' then
redis:set('markread','on')
return '_Markread >_ *ON*'
end
if matches[2] == 'off' then
redis:set('markread','off')
return '_Markread >_ *OFF*'
end
end
if matches[1] == 'setmyusername' and is_sudo(msg) then
tdcli.changeUsername(matches[2], dl_cb, nil)
return '_Username Changed To:_ @'..matches[2]
end
if matches[1] == 'delmyusername' and is_sudo(msg) then
tdcli.changeUsername('', dl_cb, nil)
return '*Done!*'
end
if matches[1] == 'setmyname' and is_sudo(msg) then
tdcli.changeName(matches[2], dl_cb, nil)
return '_Name Changed To:_ *'..matches[2]..'*'
end
if matches[1] == 'delmyname' and is_sudo(msg) then
tdcli.changeName(' ', dl_cb, nil)
return '_Name Has Been Deleted_'
end
if matches[1] == 'addcontact' and is_sudo(msg) then
local phone_number = matches[2]
local first_name = matches[3]
local last_name = matches[4]
tdcli.importContacts(phone_number, first_name, last_name, 0)
return '_User_ *[+'.. matches[2] ..']* _Has Been Added_'
end
if matches[1] == 'delcontact' and is_sudo(msg) then
tdcli.deleteContacts({
[0] = tonumber(matches[2])
})
return '_User_ *['.. matches[2] ..']* _Removed From Contact List_'
end
if matches[1] == 'left' and is_sudo(msg) then
tdcli.sendMessage(msg.to.id, "", 0, "*Bye All :D*", 0, "md")
tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil)
end
if matches[1] == 'selfbot' then
return tdcli.sendMessage(msg.to.id, msg.id, 1, _config.info_text, 1, 'html')
end
if matches[1] == 'chatlist' and is_sudo(msg) then
local output = list_chats(msg)
return output
end
if matches[1] == 'chat' and is_sudo(msg) then
local name = matches[3]
local value = matches[4]
if matches[2] == 'clean' then
local output = delallchats(msg)
return output
elseif matches[2] == '+' then
local text = save_value(msg, name, value)
return text
elseif matches[2] == '-' then
local text = del_value(msg,name)
return text
end
end
if matches[1] then
return get_value(msg, matches[1])
end
end
return {
patterns = {
"^[!/#](addplugin) (.*) (.+)$",
"^[!/#](delplugin) (.*)$",
"^[!/#](chatlist)$",
"^[#!/](chat) (+) ([^%s]+) (.+)$",
"^[#!/](chat) (clean)$",
"^[#!/](chat) (-) (.*)$",
"^[!/#](markread) (.*)$",
"^[!/#](setmyusername) (.*)$",
"^[!/#](delmyusername)$",
"^[!/#](setmyname) (.*)$",
"^[!/#](delmyname) (.*)$",
"^[!/#](addcontact) (%d+) (.*) (.*)$",
"^[!/#](delcontact) (%d+)$",
"^[!/#](selfbot)$",
"^[!/#](clear cache)$",
"^[!/#](left)$",
"^[!/#](block)$",
"^[!/#](block)$",
"^[!/#](unblock)$",
"^[!/#](block) (.*)$",
"^[!/#](unblock) (.*)$",
"^[!/#](sendfile) (.*) (.*)$",
"^[!/#](save) (.*)$",
"^[!/#](sendplug) (.*)$",
"^[!/#](savefile) (.*)$",
"^(.+)$",
},
run = run
}
| gpl-3.0 |
psychowood/ng-torrent-ui | app/scripts/directives/torrent-row.js | 3822 | 'use strict';
/**
* @ngdoc directive
* @name ngTorrentUiApp.directive:torrentStatus
* @description
* # torrentStatus
*/
angular.module('ngTorrentUiApp')
.directive('torrentRow', function() {
return {
priority: 1000,
templateUrl: 'views/torrent-row.html',
restrict: 'E',
replace: true,
link: function postLink(scope /*, element, attrs */ ) {
var item = scope.item;
//Preserve order of execution
var statusClass, statusTitle, statusColor;
var btnClass, btnIcon, btnAction;
item.getStatuses();
if (item.isStatusError() && !item.isStatusCompleted()) {
statusClass = 'exclamation-sign';
statusTitle = 'Error';
statusColor = 'text-danger';
} else if (!item.isStatusLoaded()) {
statusClass = 'warning-sign';
statusTitle = 'Torrent not loaded';
statusColor = 'text-danger';
} else if (item.isStatusChecking()) {
statusClass = 'repeat';
statusTitle = 'Checking';
statusColor = 'text-info';
} else if (!item.isStatusChecked()) {
statusClass = 'warning-sign';
statusTitle = 'Torrent needs checking';
statusColor = 'text-warning';
} else if (item.isStatusPaused()) {
statusClass = 'pause';
statusTitle = 'Paused';
statusColor = 'text-info';
} else if (item.isStatusSeeding()) {
statusClass = 'collapse-up';
statusTitle = 'Seeding';
statusColor = 'text-success';
} else if (item.isStatusDownloading()) {
statusClass = 'collapse-down';
statusTitle = 'Downloading';
statusColor = 'text-info';
btnClass = 'warning';
btnIcon = 'pause';
btnAction = 'pause';
} else if (item.isStatusStartAfterCheck()) {
statusClass = 'repeat';
statusTitle = 'Start after checking';
statusColor = 'text-info';
} else if (item.isStatusQueued()) {
statusClass = 'time';
statusTitle = 'Queued';
statusColor = 'text-info';
} else if (item.isStatusLoaded() && item.isStatusChecked()) {
if (item.isStatusCompleted()) {
statusClass = 'check';
statusTitle = 'Completed';
statusColor = 'text-success';
btnClass = '';
btnIcon = 'stop';
btnAction = 'stop';
} else {
statusClass = 'unchecked';
statusTitle = 'Ready';
statusColor = '';
btnClass = 'success';
btnIcon = 'play-circle';
btnAction = 'start';
}
} else {
statusClass = 'question-sign';
statusTitle = 'Status not supported: ' + parseInt(item.status).toString(2);
}
scope.statusClass = 'glyphicon-' + statusClass;
scope.statusTitle = statusTitle;
scope.statusColor = statusColor;
scope.btnClass = 'btn-' + btnClass;
scope.btnIcon = 'glyphicon-' + btnIcon;
}
};
}); | gpl-3.0 |
dryabkov/activiti-modeler-experiment | editor/src/scripts/erdfparser.js | 12898 | /*******************************************************************************
* Signavio Core Components
* Copyright (C) 2012 Signavio GmbH
*
* 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/>.
******************************************************************************/
var ERDF = {
LITERAL: 0x01,
RESOURCE: 0x02,
DELIMITERS: ['.', '-'],
HASH: '#',
HYPHEN: "-",
schemas: [],
callback: undefined,
log: undefined,
init: function(callback) {
// init logging.
//ERDF.log = Log4js.getLogger("oryx");
//ERDF.log.setLevel(Log4js.Level.ALL);
//ERDF.log.addAppender(new ConsoleAppender(ERDF.log, false));
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("ERDF Parser is initialized.");
// register callbacks and default schemas.
ERDF.callback = callback;
ERDF.registerSchema('schema', XMLNS.SCHEMA);
ERDF.registerSchema('rdfs', XMLNS.RDFS);
},
run: function() {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("ERDF Parser is running.");
// do the work.
return ERDF._checkProfile() && ERDF.parse();
},
parse: function() {
//(ERDF.log.isDebugEnabled())
// ERDF.log.debug("Begin parsing document metadata.");
// time measuring
ERDF.__startTime = new Date();
var bodies = document.getElementsByTagNameNS(XMLNS.XHTML, 'body');
var subject = {type: ERDF.RESOURCE, value: ''};
var result = ERDF._parseDocumentMetadata() &&
ERDF._parseFromTag(bodies[0], subject);
// time measuring
ERDF.__stopTime = new Date();
var duration = (ERDF.__stopTime - ERDF.__startTime)/1000.;
//alert('ERDF parsing took ' + duration + ' s.');
return result;
},
_parseDocumentMetadata: function() {
// get links from head element.
var heads = document.getElementsByTagNameNS(XMLNS.XHTML, 'head');
var links = heads[0].getElementsByTagNameNS(XMLNS.XHTML, 'link');
var metas = heads[0].getElementsByTagNameNS(XMLNS.XHTML, 'meta');
// process links first, since they could contain schema definitions.
$A(links).each(function(link) {
var properties = link.getAttribute('rel');
var reversedProperties = link.getAttribute('rev');
var value = link.getAttribute('href');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
properties,
ERDF.RESOURCE, value);
ERDF._parseTriplesFrom(
ERDF.RESOURCE, value,
reversedProperties,
ERDF.RESOURCE, '');
});
// continue with metas.
$A(metas).each(function(meta) {
var property = meta.getAttribute('name');
var value = meta.getAttribute('content');
ERDF._parseTriplesFrom(
ERDF.RESOURCE, '',
property,
ERDF.LITERAL, value);
});
return true;
},
_parseFromTag: function(node, subject, depth) {
// avoid parsing non-xhtml content.
if(node.namespaceURI != XMLNS.XHTML) { return; }
// housekeeping.
if(!depth) depth=0;
var id = node.getAttribute('id');
// some logging.
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace(">".times(depth) + " Parsing " + node.nodeName + " ("+node.nodeType+") for data on " +
// ((subject.type == ERDF.RESOURCE) ? ('<' + subject.value + '>') : '') +
// ((subject.type == ERDF.LITERAL) ? '"' + subject.value + '"' : ''));
/* triple finding! */
// in a-tags...
if(node.nodeName.endsWith(':a') || node.nodeName == 'a') {
var properties = node.getAttribute('rel');
var reversedProperties = node.getAttribute('rev');
var value = node.getAttribute('href');
var title = node.getAttribute('title');
var content = node.textContent;
// rel triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.RESOURCE, value,
function(triple) {
var label = title? title : content;
// label triples
ERDF._parseTriplesFrom(
triple.object.type, triple.object.value,
'rdfs.label',
ERDF.LITERAL, label);
});
// rev triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
reversedProperties,
ERDF.RESOURCE, '');
// type triples
ERDF._parseTypeTriplesFrom(
subject.type, subject.value,
properties);
// in img-tags...
} else if(node.nodeName.endsWith(':img') || node.nodeName == 'img') {
var properties = node.getAttribute('class');
var value = node.getAttribute('src');
var alt = node.getAttribute('alt');
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.RESOURCE, value,
function(triple) {
var label = alt;
// label triples
ERDF._parseTriplesFrom(
triple.object.type, triple.object.value,
'rdfs.label',
ERDF.LITERAL, label);
});
}
// in every tag
var properties = node.getAttribute('class');
var title = node.getAttribute('title');
var content = node.textContent;
var label = title ? title : content;
// regular triples
ERDF._parseTriplesFrom(
subject.type, subject.value,
properties,
ERDF.LITERAL, label);
if(id) subject = {type: ERDF.RESOURCE, value: ERDF.HASH+id};
// type triples
ERDF._parseTypeTriplesFrom(
subject.type, subject.value,
properties);
// parse all children that are element nodes.
var children = node.childNodes;
if(children) $A(children).each(function(_node) {
if(_node.nodeType == _node.ELEMENT_NODE)
ERDF._parseFromTag(_node, subject, depth+1); });
},
_parseTriplesFrom: function(subjectType, subject, properties,
objectType, object, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( function(schema) {
return false || ERDF.DELIMITERS.find( function(delimiter) {
return property.startsWith(schema.prefix + delimiter);
});
});
if(schema && object) {
property = property.substring(
schema.prefix.length+1, property.length);
var triple = ERDF.registerTriple(
new ERDF.Resource(subject),
{prefix: schema.prefix, name: property},
(objectType == ERDF.RESOURCE) ?
new ERDF.Resource(object) :
new ERDF.Literal(object));
if(callback) callback(triple);
}
});
},
_parseTypeTriplesFrom: function(subjectType, subject, properties, callback) {
if(!properties) return;
properties.toLowerCase().split(' ').each( function(property) {
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Going for property " + property);
var schema = ERDF.schemas.find( function(schema) {
return false || ERDF.DELIMITERS.find( function(delimiter) {
return property.startsWith(ERDF.HYPHEN + schema.prefix + delimiter);
});
});
if(schema && subject) {
property = property.substring(schema.prefix.length+2, property.length);
var triple = ERDF.registerTriple(
(subjectType == ERDF.RESOURCE) ?
new ERDF.Resource(subject) :
new ERDF.Literal(subject),
{prefix: 'rdf', name: 'type'},
new ERDF.Resource(schema.namespace+property));
if(callback) callback(triple);
}
});
},
/**
* Checks for ERDF profile declaration in head of document.
*/
_checkProfile: function() {
// get profiles from head element.
var heads = document.getElementsByTagNameNS(XMLNS.XHTML, 'head');
var profiles = heads[0].getAttribute("profile");
var found = false;
// if erdf profile is contained.
if(profiles && profiles.split(" ").member(XMLNS.ERDF)) {
// pass check.
//if(ERDF.log.isTraceEnabled())
// ERDF.log.trace("Found ERDF profile " + XMLNS.ERDF);
return true;
} else {
// otherwise fail check.
//if(ERDF.log.isFatalEnabled())
// ERDF.log.fatal("No ERDF profile found.");
return false;
}
},
__stripHashes: function(s) {
return (s && s.substring(0, 1)=='#') ? s.substring(1, s.length) : s;
},
registerSchema: function(prefix, namespace) {
// TODO check whether already registered, if so, complain.
ERDF.schemas.push({
prefix: prefix,
namespace: namespace
});
//if(ERDF.log.isDebugEnabled())
// ERDF.log.debug("Prefix '"+prefix+"' for '"+namespace+"' registered.");
},
registerTriple: function(subject, predicate, object) {
// if prefix is schema, this is a schema definition.
if(predicate.prefix.toLowerCase() == 'schema')
this.registerSchema(predicate.name, object.value);
var triple = new ERDF.Triple(subject, predicate, object);
ERDF.callback(triple);
//if(ERDF.log.isInfoEnabled())
// ERDF.log.info(triple)
// return the registered triple.
return triple;
},
__enhanceObject: function() {
/* Resource state querying methods */
this.isResource = function() {
return this.type == ERDF.RESOURCE };
this.isLocal = function() {
return this.isResource() && this.value.startsWith('#') };
this.isCurrentDocument = function() {
return this.isResource() && (this.value == '') };
/* Resource getter methods.*/
this.getId = function() {
return this.isLocal() ? ERDF.__stripHashes(this.value) : false; };
/* Liiteral state querying methods */
this.isLiteral = function() {
return this.type == ERDF.LIITERAL };
},
serialize: function(literal) {
if(!literal){
return "";
}else if(literal.constructor == String) {
return literal;
} else if(literal.constructor == Boolean) {
return literal? 'true':'false';
} else {
return literal.toString();
}
}
};
ERDF.Triple = function(subject, predicate, object) {
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.toString = function() {
return "[ERDF.Triple] " +
this.subject.toString() + ' ' +
this.predicate.prefix + ':' + this.predicate.name + ' ' +
this.object.toString();
};
};
ERDF.Resource = function(uri) {
this.type = ERDF.RESOURCE;
this.value = uri;
ERDF.__enhanceObject.apply(this);
this.toString = function() {
return '<' + this.value + '>';
}
};
ERDF.Literal = function(literal) {
this.type = ERDF.LITERAL;
this.value = ERDF.serialize(literal);
ERDF.__enhanceObject.apply(this);
this.toString = function() {
return '"' + this.value + '"';
}
};
| gpl-3.0 |
erikgrinaker/BOUT-dev | tools/pylib/boututils/volume_integral.py | 2172 | from __future__ import print_function
from __future__ import division
from builtins import range
from past.utils import old_div
import numpy as np
from boututils import *
from bunch import bunchify
# Integrate over a volume
def volume_integral( var, g, xr=False):
s = np.ndim(var)
grid=bunchify(g)
if s == 4 :
# 4D [t,x,y,z] - integrate for each t
nx = np.shape(var)[1]
ny = np.shape(var)[2]
nt = np.shape(var)[0]
result = np.zeros(nt)
for t in range(nt) :
result[t] = volume_integral(var[t,:,:,:],g,xr=xr)
return result
elif s == 3 :
# 3D [x,y,z] - average in Z
nx = np.shape(var)[0]
ny = np.shape(var)[1]
# nz = np.shape(var)[2]
zi = np.zeros((nx, ny))
for x in range(nx):
for y in range(ny):
zi[x,y] = np.mean(var[x,y,:])
return volume_integral(zi, g, xr=xr)
elif s != 2 :
print("ERROR: volume_integral var must be 2, 3 or 4D")
# 2D [x,y]
nx = np.shape(var)[0]
ny = np.shape(var)[1]
if xr == False : xr=[0,nx-1]
result = 0.0
#status = gen_surface(mesh=grid) ; Start generator
xi = -1
yi = np.arange(0,ny,dtype=int)
last = 0
# iy = np.zeros(nx)
while True:
#yi = gen_surface(last=last, xi=xi, period=periodic)
xi = xi + 1
if xi == nx-1 : last = 1
if (xi >= np.min(xr)) & (xi <= np.max(xr)) :
dtheta = 2.*np.pi / np.float(ny)
r = grid.Rxy[xi,yi]
z = grid.Zxy[xi,yi]
n = np.size(r)
dl = old_div(np.sqrt( deriv(r)**2 + deriv(z)**2 ), dtheta)
# Area of flux-surface
dA = (grid.Bxy[xi,yi]/grid.Bpxy[xi,yi]*dl) * (r*2.*np.pi)
# Volume
if xi == nx-1 :
dpsi = (grid.psixy[xi,yi] - grid.psixy[xi-1,yi])
else:
dpsi = (grid.psixy[xi+1,yi] - grid.psixy[xi,yi])
dV = dA * dpsi / (r*(grid.Bpxy[xi,yi])) # May need factor of 2pi
dV = np.abs(dV)
result = result + np.sum(var[xi,yi] * dV)
if last==1 : break
return result
| gpl-3.0 |
sherisaac/TurteTracker_APIServer | src/main/java/com/turtletracker/api/server/handlers/nest/NestNotFoundException.java | 319 | /*
* Copyright TurtleTracker 2017
*/
package com.turtletracker.api.server.handlers.nest;
/**
*
* @author Ike [Admin@KudoDev.com]
*/
public class NestNotFoundException extends Exception {
public NestNotFoundException(String string) {
super("{\"err\":\"Nest: " + string + " not found...\"}");
}
}
| gpl-3.0 |
impomezia/screenpic | src/ShareNet.cpp | 2289 | /* Copyright (C) 2013-2015 Alexander Sedov <imp@schat.me>
*
* 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 <QMetaType>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QThread>
#include "ShareNet.h"
#include "uploaders/Uploader.h"
#include "Providers.h"
ShareNet::ShareNet(Providers *providers, QNetworkAccessManager *net, QObject *parent)
: QObject(parent)
, m_net(net)
{
providers->create(m_uploaders, this);
foreach (const Uploader *uploader, m_uploaders) {
connect(uploader, SIGNAL(finished(UploadResult)), SIGNAL(finished(UploadResult)));
connect(uploader, SIGNAL(finished(ChatId,QString,QVariant)), SIGNAL(finished(ChatId,QString,QVariant)));
connect(uploader, SIGNAL(uploadProgress(ChatId,int)), SIGNAL(uploadProgress(ChatId,int)));
}
}
ShareNet::~ShareNet()
{
qDeleteAll(m_uploaders);
}
void ShareNet::add(const ChatId &id, const QString &provider, const QVariant &data)
{
Q_ASSERT(m_uploaders.contains(provider));
if (m_uploaders.contains(provider))
m_uploaders[provider]->request(m_net, id, data);
}
void ShareNet::add(UploadItemPtr item, const QString &provider, const QVariant &data)
{
Q_ASSERT(m_uploaders.contains(provider));
if (m_uploaders.contains(provider))
m_uploaders[provider]->upload(m_net, item, data);
}
void ShareNet::remove(const QString &deletehash, const QString &provider, const QVariant &data)
{
if (m_uploaders.contains(provider))
m_uploaders[provider]->remove(m_net, deletehash, data);
}
QObject *ShareNetTask::create(QNetworkAccessManager *net, QObject *parent)
{
return new ShareNet(m_providers, net, parent);
}
| gpl-3.0 |
dgfiloso/C_IEIN | Practica4/html/navtreedata.js | 1060 | var NAVTREE =
[
[ "Presence_Observer", "index.html", [
[ "Documentacion Proyecto Observer IEIN", "index.html", [
[ "Abstract", "index.html#Abstract", null ],
[ "Descripcion del Proyect", "index.html#Desc", null ]
] ],
[ "Data Structures", "annotated.html", [
[ "Data Structures", "annotated.html", "annotated_dup" ],
[ "Data Structure Index", "classes.html", null ],
[ "Data Fields", "functions.html", [
[ "All", "functions.html", null ],
[ "Variables", "functions_vars.html", null ]
] ]
] ],
[ "Files", null, [
[ "File List", "files.html", "files" ],
[ "Globals", "globals.html", [
[ "All", "globals.html", null ],
[ "Functions", "globals_func.html", null ],
[ "Typedefs", "globals_type.html", null ],
[ "Macros", "globals_defs.html", null ]
] ]
] ]
] ]
];
var NAVTREEINDEX =
[
"_presence___observer_8c.html"
];
var SYNCONMSG = 'click to disable panel synchronisation';
var SYNCOFFMSG = 'click to enable panel synchronisation'; | gpl-3.0 |
ciasaboark/Nodyn | app/src/main/java/io/phobotic/nodyn_app/database/audit/model/AuditDetail.java | 3170 | /*
* Copyright (c) 2018 Jonathan Nelson <ciasaboark@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.phobotic.nodyn_app.database.audit.model;
import org.jetbrains.annotations.Nullable;
import java.io.Serializable;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import io.phobotic.nodyn_app.database.converter.StatusTypeListConverter;
/**
* Created by Jonathan Nelson on 1/14/18.
*/
@Entity(tableName = "audit_detail")
@TypeConverters({StatusTypeListConverter.class})
public class AuditDetail implements Serializable {
@PrimaryKey(autoGenerate = true)
private Integer id;
private int auditID;
private int assetID;
private long timestamp;
private Status status;
private String notes;
private boolean extracted;
//used solely to maintain expanded/collapsed state in recyclerview
private boolean isExpanded;
public AuditDetail(@Nullable Integer id, int auditID, int assetID, long timestamp, Status status, String notes, boolean extracted) {
this.id = id;
this.auditID = auditID;
this.assetID = assetID;
this.timestamp = timestamp;
this.status = status;
this.notes = notes;
this.extracted = extracted;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getAuditID() {
return auditID;
}
public void setAuditID(int auditID) {
this.auditID = auditID;
}
public int getAssetID() {
return assetID;
}
public void setAssetID(int assetID) {
this.assetID = assetID;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public boolean isExtracted() {
return extracted;
}
public void setExtracted(boolean extracted) {
this.extracted = extracted;
}
public boolean isExpanded() {
return isExpanded;
}
public void setExpanded(boolean expanded) {
isExpanded = expanded;
}
public enum Status {
UNDAMAGED,
DAMAGED,
OTHER,
NOT_AUDITED,
UNEXPECTED
}
}
| gpl-3.0 |
gohdan/DFC | known_files/hashes/bitrix/modules/forum/install/components/bitrix/forum.post_form/lang/en/help/.tooltips.php | 61 | Bitrix 16.5 Business Demo = f99a1f7c38f47c2b32733ccfa016c8f0
| gpl-3.0 |
apruden/opal | opal-core-ws/src/main/java/org/obiba/opal/web/security/DefaultOptionsMethodExceptionMapper.java | 1414 | package org.obiba.opal.web.security;
import java.util.Set;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.jboss.resteasy.spi.DefaultOptionsMethodException;
import org.obiba.opal.web.ws.inject.RequestAttributesProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.common.collect.ImmutableSet;
@Provider
@Component
public class DefaultOptionsMethodExceptionMapper implements ExceptionMapper<DefaultOptionsMethodException> {
private static final String ALLOW_HTTP_HEADER = "Allow";
@Autowired
private RequestAttributesProvider requestAttributeProvider;
@Override
public Response toResponse(DefaultOptionsMethodException exception) {
Response response = exception.getResponse();
// Extract the Allow header generated by RestEASY.
// This contains all the methods of the resource class for the given path
String availableMethods = (String) response.getMetadata().getFirst(ALLOW_HTTP_HEADER);
UriInfo uri = requestAttributeProvider.getUriInfo();
Set<String> allowed = AuthorizationInterceptor
.allowed(uri.getPath(), ImmutableSet.copyOf(availableMethods.split(", ")));
return Response.ok().header(ALLOW_HTTP_HEADER, AuthorizationInterceptor.asHeader(allowed)).build();
}
}
| gpl-3.0 |
zuiwuchang/king-document | data/tags/41.js | 165 | var __v=[
{
"Id": 40,
"Tag": 41,
"Name": "QUnit 單元測試",
"Sort": 0
},
{
"Id": 41,
"Tag": 41,
"Name": "CryptoJS",
"Sort": 0
}
] | gpl-3.0 |
onebone/EconomyS | EconomyAPI/src/onebone/economyapi/util/Transaction.php | 1683 | <?php
/*
* EconomyS, the massive economy plugin with many features for PocketMine-MP
* Copyright (C) 2013-2021 onebone <me@onebone.me>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace onebone\economyapi\util;
use InvalidArgumentException;
class Transaction {
const ACTION_SET = 0;
const ACTION_ADD = 1;
const ACTION_REDUCE = 2;
/** @var TransactionAction[] */
private $actions = [];
/**
* @param TransactionAction[] $actions
*/
public function __construct(array $actions) {
$players = [];
foreach($actions as $action) {
if(!$action instanceof TransactionAction) {
throw new InvalidArgumentException('TransactionAction[] is required to the constructor');
}
$username = strtolower($action->getPlayer());
if(in_array($username, $players)) {
throw new InvalidArgumentException('Two or more TransactionAction elements are targeting one player');
}
$players[] = $username;
}
$this->actions = $actions;
}
/**
* @return TransactionAction[]
*/
public function getActions(): array {
return $this->actions;
}
}
| gpl-3.0 |
francescamille/VERSION_AB1L_GROUP2 | search_result.php | 5311 | <?php
session_start();
$pgsql_conn = pg_connect("dbname=postgres host=localhost user=postgres password=12345");
//real query
//$query = "select * from blogs order by date_published limit 50;";
//echo $_SESSION['uname']."--,";
//$result = pg_query($pgsql_conn, $query);
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8"/>
<title>Online Diary - Search</title>
<link href="css/style1.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrap">
<header id="mainheader">
<h1>online <span>diary</span></h1>
</header><nav id="topnav">
<ul>
<li>
<form name = "search" method = "post" action = "search_result.php">
<span><input type="text" name = "searchme" class="search rounded" placeholder="Search"></span>
</form>
</li>
<li><a href="home.php">Home</a></li>
<li><a href="view_profile_own.php">Me</a></li>
<li><a href="add_blog.php">New Blog</a></li>
<li><a href="profile_settings.php">Profile Settings</a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
</nav>
<div id="maincontent">
<section id="leftcontent" class="normalpage">
<section id="leftcontents">
<header id="mainheading">
<h2>Search Results</h2>
</header>
<div id="contentwrap">
<?php
//counts the blog posts to determine how many pages
$find = $_SESSION['uname'];
$item = $_POST['searchme'];
//$query = "SELECT * from usertry where username LIKE '".$item."';";
$query = "SELECT * from usertry where username LIKE '".$item."' OR username LIKE '%".$item."' OR username LIKE '".$item."%' OR username LIKE '%".$item."%'";
$result = pg_query($pgsql_conn, $query);
$i=0;
while ($row = pg_fetch_array($result)) {
if($_SESSION['uname'] != $row['username']){
echo "<section class='postinfo'>";
//echo "<p class='postdata postdate'></p>";
echo "</section>";
echo "<article class='postpre'>";
echo "<header>";
//displays the title
echo "<a href='view_profile.php?username=".$row['username']."'><h3>".$row['username']."</h3></a><br/>";
echo "</header>";
if($row['dpic'] != ''){
echo "<a href='view_profile.php?username=".$row['username']."'><img id = 'pimage' src='dp/".$row['dpic']."'/></a>";}
else{
echo "<a href='view_profile.php?username=".$row['username']."'><img id = 'pimage' src='dp/default.jpg'/><a/>";}
echo "<p>";
echo $row['about'];
echo "</p>";
echo "</article>";
echo "<div class='postbtm'>";
echo "</div>";
}
$i++;
}//end-while
if($i<=0){
echo "<div id='none'>No results found for your query.</div>";
}
//PAGE NAVIGATION DAPAT!!!! :))
echo "<div class='wp-pagenavi'>";
$query0 = "SELECT count(*) from usertry where username LIKE '".$item."' OR username LIKE '%".$item."' OR username LIKE '".$item."%' OR username LIKE '%".$item."%'";
$result0 = pg_query($pgsql_conn, $query0);
$r = pg_fetch_array($result0);
$blog_count = $r[0];
$pages = ceil($blog_count/10);
for( $i=1; $i<=$pages; $i++ ){
if(isset($_GET['page']) && $_GET['page'] == $i){
echo "<span class='current'>".$i."</span>";
}
else if(isset($_GET['page'])){
echo "<a href='home.php?username=".$find."&page=".$i."' title='2'>".$i."</a>";
}
else if(!isset($_GET['page']) && $i == 1){
echo "<span class='current'>1</span>";
}
elseif(!isset($_GET['page'])){
echo "<a href='home.php?username=".$find."&page=".$i."' title='2'>".$i."</a>";
}
}
echo "</div>";
echo "</section></section>";
echo "<section id='sidebar'><h2 title='Categories'>";
//USER NAME LANG TO
echo $find;
echo "</h2><div class='sb-c'>";
$query = "SELECT * FROM usertry where username = '".$find."'";
$resulta = pg_query($pgsql_conn, $query);
while ($row1 = pg_fetch_array($resulta)) {
//displays the about of the user
if($row1['dpic'] != '')
echo "<img class = 'profpic' src = 'dp/".$row1['dpic']."'/><br/><br/>";
else
echo "<img class = 'profpic' src = 'dp/default.jpg'/><br/><br/>";
echo "<p class='testimonial'>";
echo $row1['about'];
echo "<br/><br/><b>".$row1['fname']." ".$row1['mname']." ".$row1['lname']."</b>";
echo "<br/>".$row1['gender'];
echo "<br/>".$row1['bday'];
echo "<br/>".$row1['email'];
echo "<br/>";
}
echo "</p></div>";
echo "<h2 title='Stars'>";
//FETCHES THE STAR COUNT OF THE USER
$find=$_SESSION['uname'];
//query para mag-count ng user-user relationships
$query1 = "SELECT COUNT(DISTINCT from_star) as total1 FROM stars where to_star = '".$find."';";
$query2 = "select count(distinct blog_id) from blogs where owner='".$find."';";
$result22 = pg_query($pgsql_conn, $query2);
$result2 = pg_query($pgsql_conn, $query1);
$r2 = pg_fetch_array($result22);
$r = pg_fetch_array($result2);
echo "     ★★★  ";
echo $r[0];
echo "  posts   ";
echo $r2[0];
echo "</h2><div class='sb-c'><ul>";
//LINK TO PROFILE PAGE
echo "<li><a href='view_profile_own.php?username=".$find."'>My Blogs</a></li>";
//LINK TO COMMENTS PAGE
echo "<li><a href = 'comment_profile.php?username=".$find."'>Comments</a></li>";
echo "</ul></div></section><div class='clear'></div></div>";
?>
</div>
</div>
<footer>
<p>2013 © Online Diary| All Rights Reserved</p>
</footer>
</body>
</html>
| gpl-3.0 |
pbl64k/Phorth | Phorth_Io.php | 854 | <?php
/*
Copyright 2010, 2011 Pavel Lepin
This file is part of Phorth.
Phorth 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.
Phorth 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 Phorth. If not, see <http://www.gnu.org/licenses/>.
*/
class PhorthEngine__Print extends PhorthEngine___Word
{
protected function decide()
{
print($this->popDatum());
return $this;
}
}
?>
| gpl-3.0 |
benhamidene/livingdoc-confluence | livingdoc-confluence-plugin/src/main/resources/includes/js/server-properties.js | 10324 | var LDProperties = Class.extend();
LDProperties.prototype =
{
init:function(ctx, action){
this.action = action;
this._ctx = ctx;
},
createParams:function(params){ return AJS.$.extend({decorator:'none', ctx:this._ctx}, params); },
getRunnersPane:function(id){
AJS.tabs.change(AJS.$('a[href=#tabs-runner]'));
this.action.getRunnersPane(this.createParams({id:'none'}));
},
getRunner:function(id, selectedRunnerName){ this.action.getRunnersPane(this.createParams({id:id, selectedRunnerName:(selectedRunnerName ? selectedRunnerName : $F('selectedRunner'))})); },
showRunnerInputs:function(id){this.action.getRunnersPane(this.createParams({id:id, addMode:true})); },
addRunner:function(id){
var runnerName = $F('runnerName');
var serverName = $F('serverName');
if (runnerName == '' || serverName == ''){
return;
}
var runnerClasspath;
if ($F('editClasspathInput') != ''){
runnerClasspath = $F('editClasspathInput').replace(/\\/g, "/");
}
this.action.addRunner(this.createParams({id:id, newRunnerName:runnerName, newCmdLineTemplate:$F('cmdLineTemplate'), newMainClass:$F('mainClass'), newServerName:$F('serverName'), newServerPort:$F('serverPort'), newEnvType:$F('envType'), secured:$('#secured').is(':checked'), classpath:runnerClasspath, addMode:true}));
},
removeRunner:function(id){this.action.removeRunner(this.createParams({id:id, selectedRunnerName:$F('selectedRunner')})); },
editRunnerProperties:function(id){this.action.editRunnerProperties(this.createParams({id:id, selectedRunnerName:$F('selectedRunner'), editPropertiesMode:true}));},
updateRunnerProperties:function(id){
var runnerName = $F('runnerName');
var serverName = $F('serverName');
if (runnerName == '' || serverName == ''){
return;
}
var runnerClasspath;
if ($F('editClasspathInput') != ''){
runnerClasspath = $F('editClasspathInput').replace(/\\/g, "/");
}
this.action.updateRunnerProperties(this.createParams({id:id, selectedRunnerName:$F('selectedRunner'), newRunnerName:$F('runnerName'), newServerName:$F('serverName'), newServerPort:$F('serverPort'), secured:$('#secured').is(':checked'), classpath:runnerClasspath, editPropertiesMode:true}));
},
editRunnerClasspaths:function(id){this.action.editRunnerClasspaths(this.createParams({id:id, selectedRunnerName:$F('selectedRunner'), editClasspathsMode:true})); },
editRunnerClasspath:function(id, classpath){
classpath = classpath.replace(/\\/g, "/");
this.action.editRunnerClasspath(this.createParams({id:id, selectedRunnerName:$F('selectedRunner'), classpath:classpath, editClasspathsMode:false}));
},
editSutClasspath:function(id, projectName, classpath){
classpath = classpath.replace(/\\/g, "/");
this.action.editSutClasspath(this.createParams({id:id, selectedSutName:$F('selectedSut'), projectName:projectName, sutClasspath:classpath, editClasspathsMode:false}));
},
getRegistration:function(id){
LD.View.switchView('registrationPane_display', 'fileSystemPane_display');
LD.View.hide('configurationPane_display');
this.action.getRegistration(this.createParams({id:id}));
},
editRegistration:function(id){this.action.editRegistration(this.createParams({id:id, projectName:($('#projectName')? $F('projectName') : ''), repositoryName:($('#repositoryName')? $F('repositoryName') : ''), readonly:true, editMode:true})); },
register:function(id){
if($F('repositoryName') === ''){ return; }
var newProjectName = $('#newProjectName') ? $F('newProjectName') : 'NA';
this.action.register(this.createParams({id:id, repositoryName:$F('repositoryName'), projectName:$F('projectName'), newProjectName:newProjectName, username:$F('username'), pwd:$F('pwd')}));
},
updateRegistration:function(id){
if($F('repositoryName') === ''){ return; }
var newProjectName = $('#newProjectName') ? $F('newProjectName') : 'NA';
this.action.updateRegistration(this.createParams({id:id, repositoryName:$F('repositoryName'), projectName:$F('projectName'), newProjectName:newProjectName, username:$F('username'), pwd:$F('pwd')}));
},
getSutsPane:function(id, projectName){
var readonly = $F('readonly') ? true : false;
this.action.getSutsPane(this.createParams({id:id, projectName:projectName ? projectName : $F('projectName'), readonly:readonly}));
},
getSut:function(id, projectName, selectedSutName){
var readonly = $F('readonly') ? true : false;
this.action.getSutsPane(this.createParams({id:id, projectName:projectName, selectedSutName:selectedSutName ? selectedSutName : $F('selectedSut'), readonly:readonly}));
},
showSutInputs:function(id, projectName){ this.action.getSutsPane(this.createParams({id:id, projectName:projectName, addMode:true})); },
addSut:function(id, projectName){
if ($F('newSutName') == ''){return;}
var classpath;
if ($F('editClasspathInput') != ''){
classpath = $F('editClasspathInput').replace(/\\/g, "/");
}
this.action.addSut(this.createParams({id:id, projectName:projectName, newSutName:$F('newSutName'), newFixtureFactory:$F('fixtureFactory'), newFixtureFactoryArgs:$F('fixtureFactoryArgs'), newRunnerName:$F('sutRunnerName'), newProjectDependencyDescriptor:$F('projectDependencyDescriptor'), sutClasspath:classpath, addMode:true}));
},
removeSut:function(id, projectName){ this.action.removeSut(this.createParams({id:id, projectName:projectName, selectedSutName:$F('selectedSut')})); },
editSutProperties:function(id, projectName){ this.action.editSutProperties(this.createParams({id:id, projectName:projectName, selectedSutName:$F('selectedSut'), editPropertiesMode:true})); },
updateSutProperties:function(id, projectName){
if ($F('newSutName') == ''){return;}
var classpath;
if ($F('editClasspathInput') != ''){
classpath = $F('editClasspathInput').replace(/\\/g, "/");
}
this.action.updateSutProperties(this.createParams({id:id, projectName:projectName, selectedSutName:$F('selectedSut'), newSutName:$F('newSutName'), newFixtureFactory:$F('fixtureFactory'), newFixtureFactoryArgs:$F('fixtureFactoryArgs'), newRunnerName:$F('sutRunnerName'), newProjectDependencyDescriptor:$F('projectDependencyDescriptor'), sutClasspath:classpath, editPropertiesMode:true}));
},
editSutClasspaths:function(id, projectName){ this.action.editSutClasspaths(this.createParams({id:id, projectName:projectName, selectedSutName:$F('selectedSut'), editClasspathsMode:true})); },
editSutFixtures:function(id, projectName){ this.action.editSutFixtures(this.createParams({id:id, projectName:projectName, selectedSutName:$F('selectedSut'), editFixturesMode:true})); },
editSutFixture:function(id, projectName, newFixtureClasspath) {
var newFixtureClasspath = newFixtureClasspath.replace(/\\/g, "/");
this.action.editSutFixture(this.createParams({id:id, projectName:projectName, selectedSutName:$F('selectedSut'), fixtureClasspath:newFixtureClasspath, editFixturesMode:false}));
},
removeSystemUnderTest:function(id, projectName){ this.action.removeSystemUnderTest(this.createParams({id:id, projectName:projectName, selectedSutName:$F('selectedSut')})); },
setSutAsDefault:function(id, projectName){ this.action.setSutAsDefault(this.createParams({id:id, projectName:projectName, selectedSutName:$F('selectedSut')})); },
editDbms:function(){
AJS.tabs.change(AJS.$('a[href=#tabs-dbms-config]'));
this.action.getInstallWizardPane(this.createParams({editMode:true}));
},
getDbmsConfigPane:function(){
AJS.tabs.change(AJS.$('a[href=#tabs-dbms-config]'));
this.action.getInstallWizardPane(this.createParams({id:'none'}));
},
updateQuickDbmsConfiguration:function(){ this.action.updateDbmsConfiguration(this.createParams({installType:$F('installType_Cmb'), hibernateDialect:'org.hibernate.dialect.HSQLDialect'})); },
updateCustomDbmsConfiguration:function(){
if($F('jndi_txtfield') === ''){ return; }
this.action.updateDbmsConfiguration(this.createParams({installType:$F('installType_Cmb'),jndiUrl:$F('jndi_txtfield'), hibernateDialect:$F('dbms')})); },
testDbmsConnection:function(){
if($F('jndi_txtfield') === ''){ return; }
LD.View.write('testConnection_display', ''); this.action.testDbmsConnection(this.createParams({jndiUrl:$F('jndi_txtfield'), hibernateDialect:$F('dbms')})); },
changeInstallationType:function(){ LD.View.write('dbmsChoice_display', ''); this.action.changeInstallationType(this.createParams({installType:$F('installType_Cmb')}));},
getLdProjectPane:function(){
AJS.tabs.change(AJS.$('a[href=#tabs-project]'));
this.action.getLdProjectPane(this.createParams({id:'none'}));
},
updateSettings:function(){
if($F('executionTimeout') === ''){ return; }
this.action.updateSettings(this.createParams({id:'none', executionTimeout:$F('executionTimeout'), editMode:false}));
},
editSettings:function(){
this.action.editSettings(this.createParams({id:'none', editMode:true}));
},
getGeneralSettingsPane:function(){
AJS.tabs.change(AJS.$('a[href=#tabs-settings]'));
this.action.getGeneralSettingsPane(this.createParams({id:'none', editMode:false}));
},
getDemoPane:function() {
AJS.tabs.change(AJS.$('a[href=#tabs-demo]'));
this.action.getDemoPane(this.createParams({id:'none'}));
},
createDemoSpace:function(checkUsername) {
if (checkUsername == 'true') {
if ($F('username') == ''){return;}
}
AJS.tabs.change(AJS.$('a[href=#tabs-demo]'));
this.action.createDemoSpace(this.createParams({username:$F('username'), pwd:$F('pwd')}));
},
removeDemoSpace:function() {
AJS.tabs.change(AJS.$('a[href=#tabs-demo]'));
this.action.removeDemoSpace(this.createParams({}));
},
/**
* Note: This listener responds to every single ajax requests, even non
* livingdoc requests (e.g. atlassian requests). But it seems as their are
* no other requests then ours using the AJS provided jQuery instance.
*/
addAjaxListeners:function(){
AJS.$(document).ajaxSend(function() {
LD.View.hide('sutsPaneError_display');
LD.View.hide('runnersPaneError_display');
LD.View.hide('registrationPaneError_display');
AJS.$('#waiting_display').css('opacity',1.0);
LD.View.switchView('waiting_display', 'systemError_display');
});
AJS.$(document).ajaxComplete(function() {
LD.View.fade('waiting_display', 0.3);
});
AJS.$(document).ajaxError(function() {
LD.View.switchView('systemError_display', 'waiting_display');
});
}
};
| gpl-3.0 |
Serg-Norseman/GEDKeeper | projects/GKv3/GEDKeeper3/GKUI/Forms/PortraitSelectDlg.cs | 3168 | /*
* "GEDKeeper", the personal genealogical database editor.
* Copyright (C) 2009-2018 by Sergey V. Zhdanovskih.
*
* This file is part of "GEDKeeper".
*
* 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/>.
*/
using System;
using Eto.Forms;
using GDModel;
using GKCore;
using GKCore.Controllers;
using GKCore.Interfaces;
using GKCore.MVP.Controls;
using GKCore.MVP.Views;
using GKUI.Components;
namespace GKUI.Forms
{
public sealed partial class PortraitSelectDlg : EditorDialog, IPortraitSelectDlg
{
private readonly PortraitSelectDlgController fController;
private ITimer fTimer;
public GDMMultimediaLink MultimediaLink
{
get { return fController.MultimediaLink; }
set { fController.MultimediaLink = value; }
}
#region View Interface
IImageView IPortraitSelectDlg.ImageCtl
{
get { return imageView1; }
}
#endregion
private void btnAccept_Click(object sender, EventArgs e)
{
DialogResult = fController.Accept() ? DialogResult.Ok : DialogResult.None;
}
public PortraitSelectDlg(IBaseWindow baseWin)
{
InitializeComponent();
btnAccept.Image = UIHelper.LoadResourceImage("Resources.btn_accept.gif");
btnCancel.Image = UIHelper.LoadResourceImage("Resources.btn_cancel.gif");
imageView1.SelectionMode = ImageBoxSelectionMode.Rectangle;
// SetLocale()
btnAccept.Text = LangMan.LS(LSID.LSID_DlgAccept);
btnCancel.Text = LangMan.LS(LSID.LSID_DlgCancel);
Title = LangMan.LS(LSID.LSID_PortraitSelect);
fTimer = AppHost.Instance.CreateTimer(100.0f, InitViewer_Tick);
fTimer.Start();
fController = new PortraitSelectDlgController(this);
fController.Init(baseWin);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (imageView1 != null) {
imageView1.Focus();
imageView1.Invalidate();
imageView1.ZoomToFit();
}
}
// dirty temporary hack
private void InitViewer_Tick(object sender, EventArgs e)
{
if (imageView1 != null && !imageView1.Viewport.Size.IsEmpty) {
imageView1.ZoomToFit();
fTimer.Stop();
}
}
}
}
| gpl-3.0 |
gmfrasca/pointstreak-groupme | psgroupme/bots/schedule_bot.py | 2722 | from recleagueparser.schedules import ScheduleFactory
from psgroupme.bots.base_bot import BaseBot
class ScheduleBot(BaseBot):
NEXTGAME_RESPONSE = 'The next game is: {0}'
LASTGAME_RESPONSE = 'The last game was: {0}'
SCHEDULE_RESPONSE = 'This is the current schedule:\n{0}'
DEFAULT_TEAM_ID = 3367048
DEFAULT_SEASON_ID = 481539
DEFAULT_TYPE = 'sportsengine'
def __init__(self, bot_cfg, schedule=None, *args, **kwargs):
"""Initialize the bot, and add ScheduleBot-specific responses"""
super(ScheduleBot, self).__init__(bot_cfg, *args, **kwargs)
self.schedule = schedule
def get_bot_specific_responses(self):
return self.brm.get_responses().get('schedulebot', list())
def load_schedule(self, *args, **kwargs):
super(ScheduleBot, self).get_extra_context()
self._load_schedule()
if self.schedule is not None:
self._logger.info("Getting Extra Context from Schedule Parser")
self.schedule.refresh_schedule() # TODO: do not need?
next_game = self.schedule.get_next_game()
last_game = self.schedule.get_last_game()
schedule = self.schedule.get_schedule()
nextgame_resp = self.NEXTGAME_RESPONSE.format(str(next_game))
lastgame_resp = self.LASTGAME_RESPONSE.format(str(last_game))
schedule_resp = self.SCHEDULE_RESPONSE.format(str(schedule))
if next_game is None:
nextgame_resp = "There are no games left on the schedule :("
if last_game is None:
lastgame_resp = "The season hasn't started yet"
if schedule is None or len(self.schedule.games) < 1:
schedule_resp = "No schedule yet :("
self.context.update(dict(nextgame_resp=nextgame_resp,
lastgame_resp=lastgame_resp,
schedule_resp=schedule_resp,
next_game=next_game,
last_game=last_game,
schedule=schedule))
def _load_schedule(self):
self._logger.debug("Loading Schedule Parser")
if self.schedule is not None:
self._logger.debug("Schedule Parser already loaded.")
return
if 'schedule' in self.bot_data:
self._logger.debug("Schedule Parser not loaded, creating new one")
schedule_cfg = self.bot_data.get('schedule', dict())
schedule_type = schedule_cfg.get('type', self.DEFAULT_TYPE)
schedule_cfg.update(dict(schedule_type=schedule_type))
self.schedule = ScheduleFactory.create(**schedule_cfg)
| gpl-3.0 |
hustr/OnlineJudge | Leetcode/019RemoveNode.java | 1431 | package Leetcode;
/**
* Created by yaning on 17-5-30.
*/
public class _019RemoveNode {
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
n1.next = n2;
ListNode n3 = new ListNode(3);
n2.next = n3;
ListNode n4 = new ListNode(4);
n3.next = n4;
ListNode n5 = new ListNode(5);
n4.next = n5;
n5.next = null;
Solution sol = new Solution();
// sol.removeNthFromEnd(n1, 1);
ListNode l = sol.removeNthFromEnd(n1, 3);
while (l != null) {
System.out.println(l.val);
l = l.next;
}
}
static class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (n == 0) {
return head;
}
ListNode pre = new ListNode(0);
pre.next = head;
ListNode temp = head;
for (int i = 0; i < n; i++) {
temp = temp.next;
}
while (temp != null) {
temp = temp.next;
pre = pre.next;
}
if (pre.next == head) {
return head.next;
}
pre.next = pre.next.next;
return head;
}
}
}
| gpl-3.0 |
archmon/RandomThoughtsMod | src/main/java/net/archmon/RandomThoughtsMod/item/ItemMapleLeaf.java | 680 | /*removed 6/29/15 3:15pm
* preparing for mod start
*
* package net.archmon.RandomThoughtsMod.item;
//import net.archmon.RandomThoughtsMod.creativetab.CreativeTab_RTM;
//example item class for item Maple Leaf
public class ItemMapleLeaf extends Item_RTM{
public ItemMapleLeaf(){
super();
//pahimar says that having this class and this public constructor and calling super is all you need to get an item.
//note, no name/texture/does nothing
setUnlocalizedName("mapleLeaf"); //makes it show on item randomthoughtsmod.mapleLeaf
//don't forget to go to en_US.lang and ModItems.java
//this.maxStackSize = 1;
//makes it to where each item is a full stack.
}
}*/
| gpl-3.0 |
hndgzkn/dpgame | org.dpgame/src/org/dpgame/tools/xml/XmlSections.java | 2460 | /*
* Copyright (C) 2014 Hande Özaygen
*
* This file is part of dpgame.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.dpgame.tools.xml;
public class XmlSections {
public static final String FILES = "files";
public static final String TYPES = "types";
public static final String TYPE = "type";
public static final String PUZZLE = "puzzle";
public static final String PUZZLES = "puzzles";
public static final String LOG = "log";
public static final String CLASS = "class";
public static final String LEVELS = "levels";
public static final String LEVEL = "level";
public static final String NAME = "name";
public static final String NUMBEROFROWS = "numberofrows";
public static final String NUMBEROFCOLUMNS = "numberofcolumns";
public static final String BOARD = "board";
public static final String SOLUTIONCOMPILER = "solutioncompiler";
public static final String TOOLBOX = "toolbox";
public static final String INCREMENT = "increment";
public static final String ACTIONS = "actions";
public static final String ACTION = "action";
public static final String PRECONDITION = "precondition";
public static final String PRECONDITIONTYPE = "preconditiontype";
public static final String MAX = "max";
public static final String OBJECTS = "objects";
public static final String OBJECT = "object";
public static final String TOOLS = "tools";
public static final String TOOL = "tool";
public static final String MINNUMBER = "minnumber";
public static final String MAXNUMBER = "maxnumber";
public static final String REPEATING = "repeating";
public static final String MINLENGTH = "minlength";
public static final String MAXLENGTH = "maxlength";
public static final String NUMBEROFACTIONS = "numberofactions";
public static final String COMPONENTS = "components";
public static final String COMPONENT = "component";
}
| gpl-3.0 |
phenix-factory/p.henix.be | plugins-dist/svp/lang/paquet-svp_pt.php | 692 | <?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de https://trad.spip.net/tradlang_module/paquet-svp?lang_cible=pt
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// S
'svp_description' => 'Por um lado, este plugin fornece um API que permite efectuar pesquisar multi-critério, recolher e apresentar informação sobre plugins SPIP (módulos funcionais, temas e modelos). Por outro lado, propõe uma nova interface de administração, para gerir as dependências entre plugins.',
'svp_slogan' => 'Servidor de informação e download de Plugins'
);
?>
| gpl-3.0 |
behradhg/TeleNfs | plugins/report.lua | 1904 | do
local function report(chat_id, msg_id, reporter, description)
local text = _('• <b>Message reported by</b>: %s'):format(reporter)
local link = redis:get('link' .. chat_id)
local title = redis:get('title' .. chat_id) or 'no name'
local logchat = redis:get('log' .. chat_id)
if link then
text = text .. _('\n• <b>Group</b>: %s (%s)'):format(title, link)
else
text = text .. _('\n• <b>Group</b>: %s'):format(title)
end
if #description > 1 then
text = text .. _('\n• <b>Description</b>: <i>%s</i>'):format(description)
end
local x = load_data(_config.chats.managed[msg.to.id])
for k,v in pairs(x.owners) do
api.sendMessage(k, text, 'html', nil, nil, true)
end
end
--------------------------------------------------------------------------------
local function run(msg, matches)
if msg.to.type == 'user' then
return
end
local chat_id, user_id = msg.to.id,msg.from.id
local desc = matches[2] or ''
local text = _('Moderators has been notified!')
if msg.reply_id then
td.getUser(user_id, function(a, d)
local name = d.first_name_ .. ' [<code>' .. d.id_ .. '</code>]'
local name = d.username_ and '@' .. d.username_ .. ' ' .. name or name
report(a.chat_id, a.msg_id, name, a.desc)
end, {chat_id = chat_id, msg_id = msg.id, desc = desc})
else
text = _('Please reply the message and give a description, e.g <code>!report [description]</code>')
end
return text
end
--------------------------------------------------------------------------------
return {
description = 'Notifies all moderators of an issue.',
usage = {
'<code>!report [description]</code>',
'Report a replied message and give a description.',
'',
},
patterns = {
'^(report)$',
'^(report) (.*)',
},
run = run
}
end | gpl-3.0 |
EcrituresNumeriques/anthologie-apiLite | src/post/images/new.php | 1250 | <?php
if(is_numeric($_POST['entity']) && !empty($_POST['url'])){
//TODO: If a file is provided, grab a copy on the server
try{
$insertNewImage = $db->prepare("INSERT INTO images (user_id,group_id,URL,title,credit) VALUES (:user,:group,:url,:title,:credit)");
$insertNewImage->bindParam(":url",$_POST['url']);
$title = (!empty($_POST['title'])?$_POST['title']:NULL);
$insertNewImage->bindParam(":title",$title);
$credit = (!empty($_POST['credit'])?$_POST['credit']:NULL);
$insertNewImage->bindParam(":credit",$credit);
$insertNewImage->bindParam(":user",$user['user']['id']);
(!empty($user['user']['groups'][0])?:$user['user']['groups'][0] = NULL);
$insertNewImage->bindParam(":group",$user['user']['groups'][0]);
$insertNewImage->execute();
$imageId = $db->lastInsertId();
//add assoc
$insertAssocImage = $db->prepare("INSERT INTO entities_images_assoc (entity_id,image_id) VALUES(:entity,:image)");
$insertAssocImage->bindParam(":entity",$_POST['entity']);
$insertAssocImage->bindParam(":image",$imageId);
$insertAssocImage->execute();
}
catch(Exception $e){
errorJSON('SQL error : ' . $e->getMessage(),500);
}
$data['newImage'] = $_POST['url'];
}
else{
errorJSON("missing information",400);
}
?>
| gpl-3.0 |
SimonItaly/duckhunt | doc/html/game__a_8h.js | 105 | var game__a_8h =
[
[ "GameA_MainLoop", "game__a_8h.html#ab0e0a867501ff7ebc03c03bcd378d197", null ]
]; | gpl-3.0 |
tuliotoffolo/tup | tup/src/be/kuleuven/codes/tup/heuristic/assignment/HungarianAlgorithm.java | 9438 | package be.kuleuven.codes.tup.heuristic.assignment;
import java.util.*;
/**
* An implementation of the classic hungarian algorithm for the assignment problem.
* <p>
* Copyright 2007 Gary Baker (GPL v3)
*
* @author gbaker
*/
public class HungarianAlgorithm implements AssignmentAlgorithm {
private int[][] zeroSequence;
public int[][] computeAssignments(int[][] matrix) {
// subtract minumum value from rows and columns to create lots of zeroes
reduceMatrix(matrix);
// non negative values are the index of the starred or primed zero in the row or column
int[] starsByRow = new int[matrix.length];
Arrays.fill(starsByRow, -1);
int[] starsByCol = new int[matrix[0].length];
Arrays.fill(starsByCol, -1);
int[] primesByRow = new int[matrix.length];
Arrays.fill(primesByRow, -1);
// 1s mean covered, 0s mean not covered
int[] coveredRows = new int[matrix.length];
int[] coveredCols = new int[matrix[0].length];
// star any zero that has no other starred zero in the same row or column
initStars(matrix, starsByRow, starsByCol);
coverColumnsOfStarredZeroes(starsByCol, coveredCols);
while (!allAreCovered(coveredCols)) {
int[] primedZero = primeSomeUncoveredZero(matrix, primesByRow, coveredRows, coveredCols);
int whileCount = 0; //added for bug in while loop
while (primedZero == null) {
if (whileCount > 1000) return null; //ugly hack for bug in this while loop!!! added by Tony
// keep making more zeroes until we find something that we can prime (i.e. a zero that is uncovered)
makeMoreZeroes(matrix, coveredRows, coveredCols);
primedZero = primeSomeUncoveredZero(matrix, primesByRow, coveredRows, coveredCols);
whileCount++;
}
// check if there is a starred zero in the primed zero's row
int columnIndex = starsByRow[primedZero[0]];
if (-1 == columnIndex) {
// if not, then we need to incrementPriority the zeroes and start over
incrementSetOfStarredZeroes(primedZero, starsByRow, starsByCol, primesByRow);
Arrays.fill(primesByRow, -1);
Arrays.fill(coveredRows, 0);
Arrays.fill(coveredCols, 0);
coverColumnsOfStarredZeroes(starsByCol, coveredCols);
}
else {
// cover the row of the primed zero and uncover the column of the starred zero in the same row
coveredRows[primedZero[0]] = 1;
coveredCols[columnIndex] = 0;
}
}
// ok now we should have assigned everything
// take the starred zeroes in each column as the correct assignments
int[][] retval = new int[matrix.length][];
for (int i = 0; i < starsByCol.length; i++) {
retval[i] = new int[]{ starsByCol[i], i };
}
return retval;
}
private boolean allAreCovered(int[] coveredCols) {
for (int covered : coveredCols) {
if (0 == covered) return false;
}
return true;
}
/**
* the first step of the hungarian algorithm
* is to find the smallest element in each row
* and subtract it's values from all elements
* in that row
*
* @return the next step to perform
*/
private void reduceMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
// find the min value in the row
int minValInRow = Integer.MAX_VALUE;
for (int j = 0; j < matrix[i].length; j++) {
if (minValInRow > matrix[i][j]) {
minValInRow = matrix[i][j];
}
}
// subtract it from all values in the row
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] -= minValInRow;
}
}
for (int i = 0; i < matrix[0].length; i++) {
int minValInCol = Integer.MAX_VALUE;
for (int j = 0; j < matrix.length; j++) {
if (minValInCol > matrix[j][i]) {
minValInCol = matrix[j][i];
}
}
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] -= minValInCol;
}
}
}
private void initStars(int costMatrix[][], int[] starsByRow, int[] starsByCol) {
int[] rowHasStarredZero = new int[costMatrix.length];
int[] colHasStarredZero = new int[costMatrix[0].length];
for (int i = 0; i < costMatrix.length; i++) {
for (int j = 0; j < costMatrix[i].length; j++) {
if (0 == costMatrix[i][j] && 0 == rowHasStarredZero[i] && 0 == colHasStarredZero[j]) {
starsByRow[i] = j;
starsByCol[j] = i;
rowHasStarredZero[i] = 1;
colHasStarredZero[j] = 1;
break; // move onto the next row
}
}
}
}
/**
* just marke the columns covered for any coluimn containing a starred zero
*
* @param starsByCol
* @param coveredCols
*/
private void coverColumnsOfStarredZeroes(int[] starsByCol, int[] coveredCols) {
for (int i = 0; i < starsByCol.length; i++) {
coveredCols[i] = -1 == starsByCol[i] ? 0 : 1;
}
}
/**
* finds some uncovered zero and primes it
*
* @param matrix
* @param primesByRow
* @param coveredRows
* @param coveredCols
* @return
*/
private int[] primeSomeUncoveredZero(int matrix[][], int[] primesByRow,
int[] coveredRows, int[] coveredCols) {
// find an uncovered zero and prime it
for (int i = 0; i < matrix.length; i++) {
if (1 == coveredRows[i]) continue;
for (int j = 0; j < matrix[i].length; j++) {
// if it's a zero and the column is not covered
if (0 == matrix[i][j] && 0 == coveredCols[j]) {
// ok this is an unstarred zero
// prime it
primesByRow[i] = j;
return new int[]{ i, j };
}
}
}
return null;
}
/**
* @param unpairedZeroPrime
* @param starsByRow
* @param starsByCol
* @param primesByRow
*/
private void incrementSetOfStarredZeroes(int[] unpairedZeroPrime, int[] starsByRow, int[] starsByCol, int[] primesByRow) {
// build the alternating zero sequence (prime, star, prime, star, etc)
int i, j = unpairedZeroPrime[1];
zeroSequence = new int[20][];
int total = 0;
zeroSequence[0] = unpairedZeroPrime;
total++;
boolean paired;
do {
i = starsByCol[j];
paired = -1 != i;
paired = paired && addZeroSequence(total, new int[]{ i, j });
if (paired) total++;
if (!paired) break;
j = primesByRow[i];
paired = -1 != j;
paired = paired && addZeroSequence(total, new int[]{ i, j });
if (paired) total++;
} while (paired);
// unstar each starred zero of the sequence
// and star each primed zero of the sequence
for (int k = 0; k < total; k++) {
int[] zero = zeroSequence[k];
if (starsByCol[zero[1]] == zero[0]) {
starsByCol[zero[1]] = -1;
starsByRow[zero[0]] = -1;
}
if (primesByRow[zero[0]] == zero[1]) {
starsByRow[zero[0]] = zero[1];
starsByCol[zero[1]] = zero[0];
}
}
}
private boolean addZeroSequence(int total, int[] ints) {
for (int i = 0; i < total; i++) {
if (Arrays.equals(zeroSequence[i], ints))
return false;
}
if (total == zeroSequence.length) {
zeroSequence = Arrays.copyOf(zeroSequence, total * 2);
}
zeroSequence[total] = ints;
return true;
}
private void makeMoreZeroes(int[][] matrix, int[] coveredRows, int[] coveredCols) {
// find the minimum uncovered value
int minUncoveredValue = Integer.MAX_VALUE;
for (int i = 0; i < matrix.length; i++) {
if (0 == coveredRows[i]) {
for (int j = 0; j < matrix[i].length; j++) {
if (0 == coveredCols[j] && matrix[i][j] < minUncoveredValue) {
minUncoveredValue = matrix[i][j];
}
}
}
}
// add the min value to all covered rows
for (int i = 0; i < coveredRows.length; i++) {
if (1 == coveredRows[i]) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] += minUncoveredValue;
}
}
}
// subtract the min value from all uncovered columns
for (int i = 0; i < coveredCols.length; i++) {
if (0 == coveredCols[i]) {
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] -= minUncoveredValue;
}
}
}
}
} | gpl-3.0 |
mfalkao/SmartStoreNET | src/Tests/SmartStore.Services.Tests/Catalog/PriceCalculationServiceTests.cs | 12809 | using System;
using SmartStore.Core;
using SmartStore.Core.Domain.Catalog;
using SmartStore.Core.Domain.Customers;
using SmartStore.Core.Domain.Discounts;
using SmartStore.Core.Domain.Orders;
using SmartStore.Services.Catalog;
using SmartStore.Services.Discounts;
using SmartStore.Tests;
using NUnit.Framework;
using Rhino.Mocks;
using System.Collections.Generic;
using SmartStore.Core.Domain.Stores;
using SmartStore.Services.Media;
using System.Web;
using SmartStore.Services.Tax;
namespace SmartStore.Services.Tests.Catalog
{
[TestFixture]
public class PriceCalculationServiceTests : ServiceTest
{
IStoreContext _storeContext;
IDiscountService _discountService;
ICategoryService _categoryService;
IManufacturerService _manufacturerService;
IProductAttributeParser _productAttributeParser;
IProductService _productService;
IProductAttributeService _productAttributeService;
IPriceCalculationService _priceCalcService;
IDownloadService _downloadService;
ICommonServices _services;
HttpRequestBase _httpRequestBase;
ITaxService _taxService;
ShoppingCartSettings _shoppingCartSettings;
CatalogSettings _catalogSettings;
Store _store;
[SetUp]
public new void SetUp()
{
_store = new Store() { Id = 1 };
_storeContext = MockRepository.GenerateMock<IStoreContext>();
_storeContext.Expect(x => x.CurrentStore).Return(_store);
_discountService = MockRepository.GenerateMock<IDiscountService>();
_categoryService = MockRepository.GenerateMock<ICategoryService>();
_manufacturerService = MockRepository.GenerateMock<IManufacturerService>();
_productAttributeParser = MockRepository.GenerateMock<IProductAttributeParser>();
_productService = MockRepository.GenerateMock<IProductService>();
_productAttributeService = MockRepository.GenerateMock<IProductAttributeService>();
_downloadService = MockRepository.GenerateMock<IDownloadService>();
_services = MockRepository.GenerateMock<ICommonServices>();
_services.Expect(x => x.StoreContext).Return(_storeContext);
_httpRequestBase = MockRepository.GenerateMock<HttpRequestBase>();
_taxService = MockRepository.GenerateMock<ITaxService>();
_shoppingCartSettings = new ShoppingCartSettings();
_catalogSettings = new CatalogSettings();
_priceCalcService = new PriceCalculationService(_discountService, _categoryService, _manufacturerService, _productAttributeParser, _productService,
_shoppingCartSettings, _catalogSettings, _productAttributeService, _downloadService, _services, _httpRequestBase, _taxService);
}
[Test]
public void Can_get_final_product_price()
{
var product = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
};
//customer
Customer customer = null;
_priceCalcService.GetFinalPrice(product, customer, 0, false, 1).ShouldEqual(12.34M);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 2).ShouldEqual(12.34M);
}
[Test]
public void Can_get_final_product_price_with_tier_prices()
{
var product = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
};
//add tier prices
product.TierPrices.Add(new TierPrice
{
Price = 10,
Quantity = 2,
Product = product
});
product.TierPrices.Add(new TierPrice
{
Price = 8,
Quantity = 5,
Product = product
});
// set HasTierPrices property
product.HasTierPrices = true;
// customer
Customer customer = null;
_priceCalcService.GetFinalPrice(product, customer, 0, false, 1).ShouldEqual(12.34M);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 2).ShouldEqual(10);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 3).ShouldEqual(10);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 5).ShouldEqual(8);
}
[Test]
public void Can_get_final_product_price_with_tier_prices_by_customerRole()
{
var product = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
};
//customer roles
var customerRole1 = new CustomerRole()
{
Id = 1,
Name = "Some role 1",
Active = true,
};
var customerRole2 = new CustomerRole()
{
Id = 2,
Name = "Some role 2",
Active = true,
};
//add tier prices
product.TierPrices.Add(new TierPrice()
{
Price = 10,
Quantity = 2,
Product = product,
CustomerRole = customerRole1
});
product.TierPrices.Add(new TierPrice()
{
Price = 9,
Quantity = 2,
Product = product,
CustomerRole = customerRole2
});
product.TierPrices.Add(new TierPrice()
{
Price = 8,
Quantity = 5,
Product = product,
CustomerRole = customerRole1
});
product.TierPrices.Add(new TierPrice()
{
Price = 5,
Quantity = 10,
Product = product,
CustomerRole = customerRole2
});
//set HasTierPrices property
product.HasTierPrices = true;
//customer
Customer customer = new Customer();
customer.CustomerRoles.Add(customerRole1);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 1).ShouldEqual(12.34M);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 2).ShouldEqual(10);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 3).ShouldEqual(10);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 5).ShouldEqual(8);
_priceCalcService.GetFinalPrice(product, customer, 0, false, 10).ShouldEqual(8);
}
[Test]
public void Can_get_final_product_price_with_additionalFee()
{
var product = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
};
//customer
Customer customer = null;
_priceCalcService.GetFinalPrice(product, customer, 5, false, 1).ShouldEqual(17.34M);
}
[Test]
public void Can_get_final_product_price_with_discount()
{
var product = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
};
//customer
Customer customer = null;
//discounts
var discount1 = new Discount()
{
Id = 1,
Name = "Discount 1",
DiscountType = DiscountType.AssignedToSkus,
DiscountAmount = 3,
DiscountLimitation = DiscountLimitationType.Unlimited
};
discount1.AppliedToProducts.Add(product);
product.AppliedDiscounts.Add(discount1);
//set HasDiscountsApplied property
product.HasDiscountsApplied = true;
_discountService.Expect(ds => ds.IsDiscountValid(discount1, customer)).Return(true);
_discountService.Expect(ds => ds.GetAllDiscounts(DiscountType.AssignedToCategories)).Return(new List<Discount>());
_discountService.Expect(ds => ds.GetAllDiscounts(DiscountType.AssignedToManufacturers)).Return(new List<Discount>());
_priceCalcService.GetFinalPrice(product, customer, 0, true, 1).ShouldEqual(9.34M);
}
[Test]
public void Can_get_final_product_price_with_special_price()
{
var product = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
SpecialPrice = 10.01M,
SpecialPriceStartDateTimeUtc = DateTime.UtcNow.AddDays(-1),
SpecialPriceEndDateTimeUtc = DateTime.UtcNow.AddDays(1),
CustomerEntersPrice = false,
Published = true,
};
_discountService.Expect(ds => ds.GetAllDiscounts(DiscountType.AssignedToCategories)).Return(new List<Discount>());
_discountService.Expect(ds => ds.GetAllDiscounts(DiscountType.AssignedToManufacturers)).Return(new List<Discount>());
//customer
Customer customer = null;
//valid dates
_priceCalcService.GetFinalPrice(product, customer, 0, true, 1).ShouldEqual(10.01M);
//invalid date
product.SpecialPriceStartDateTimeUtc = DateTime.UtcNow.AddDays(1);
_priceCalcService.GetFinalPrice(product, customer, 0, true, 1).ShouldEqual(12.34M);
//no dates
product.SpecialPriceStartDateTimeUtc = null;
product.SpecialPriceEndDateTimeUtc = null;
_priceCalcService.GetFinalPrice(product, customer, 0, true, 1).ShouldEqual(10.01M);
}
[Test]
public void Can_get_product_discount()
{
var product = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
};
//customer
Customer customer = null;
//discounts
var discount1 = new Discount()
{
Id = 1,
Name = "Discount 1",
DiscountType = DiscountType.AssignedToSkus,
DiscountAmount = 3,
DiscountLimitation = DiscountLimitationType.Unlimited
};
discount1.AppliedToProducts.Add(product);
product.AppliedDiscounts.Add(discount1);
//set HasDiscountsApplied property
product.HasDiscountsApplied = true;
_discountService.Expect(ds => ds.IsDiscountValid(discount1, customer)).Return(true);
_discountService.Expect(ds => ds.GetAllDiscounts(DiscountType.AssignedToCategories)).Return(new List<Discount>());
_discountService.Expect(ds => ds.GetAllDiscounts(DiscountType.AssignedToManufacturers)).Return(new List<Discount>());
var discount2 = new Discount()
{
Id = 2,
Name = "Discount 2",
DiscountType = DiscountType.AssignedToSkus,
DiscountAmount = 4,
DiscountLimitation = DiscountLimitationType.Unlimited
};
discount2.AppliedToProducts.Add(product);
product.AppliedDiscounts.Add(discount2);
_discountService.Expect(ds => ds.IsDiscountValid(discount2, customer)).Return(true);
var discount3 = new Discount()
{
Id = 3,
Name = "Discount 3",
DiscountType = DiscountType.AssignedToOrderSubTotal,
DiscountAmount = 5,
DiscountLimitation = DiscountLimitationType.Unlimited,
RequiresCouponCode = true,
CouponCode = "SECRET CODE"
};
discount3.AppliedToProducts.Add(product);
product.AppliedDiscounts.Add(discount3);
//discount is not valid
_discountService.Expect(ds => ds.IsDiscountValid(discount3, customer)).Return(false);
Discount appliedDiscount;
_priceCalcService.GetDiscountAmount(product, customer, 0, 1, out appliedDiscount).ShouldEqual(4);
appliedDiscount.ShouldNotBeNull();
appliedDiscount.ShouldEqual(discount2);
}
[Test]
public void Ensure_discount_is_not_applied_to_products_with_prices_entered_by_customer()
{
var product = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = true,
Published = true,
};
//customer
Customer customer = null;
//discounts
var discount1 = new Discount()
{
Id = 1,
Name = "Discount 1",
DiscountType = DiscountType.AssignedToSkus,
DiscountAmount = 3,
DiscountLimitation = DiscountLimitationType.Unlimited
};
discount1.AppliedToProducts.Add(product);
product.AppliedDiscounts.Add(discount1);
_discountService.Expect(ds => ds.IsDiscountValid(discount1, customer)).Return(true);
Discount appliedDiscount;
_priceCalcService.GetDiscountAmount(product, customer, 0, 1, out appliedDiscount).ShouldEqual(0);
appliedDiscount.ShouldBeNull();
}
[Test]
public void Can_get_shopping_cart_item_unitPrice()
{
//customer
var customer = new Customer();
//shopping cart
var product1 = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
};
var sci1 = new ShoppingCartItem()
{
Customer = customer,
CustomerId = customer.Id,
Product = product1,
ProductId = product1.Id,
Quantity = 2,
};
var item = new OrganizedShoppingCartItem(sci1);
_priceCalcService.GetUnitPrice(item, false).ShouldEqual(12.34);
}
[Test]
public void Can_get_shopping_cart_item_subTotal()
{
//customer
var customer = new Customer();
//shopping cart
var product1 = new Product
{
Id = 1,
Name = "Product name 1",
Price = 12.34M,
CustomerEntersPrice = false,
Published = true,
};
var sci1 = new ShoppingCartItem()
{
Customer = customer,
CustomerId = customer.Id,
Product = product1,
ProductId = product1.Id,
Quantity = 2,
};
var item = new OrganizedShoppingCartItem(sci1);
_priceCalcService.GetSubTotal(item, false).ShouldEqual(24.68);
}
}
}
| gpl-3.0 |
moparisthebest/aptIn16 | apt-mirror-api/src/main/java/com/sun/mirror/util/SimpleTypeVisitor.java | 5151 | /*
* @(#)SimpleTypeVisitor.java 1.4 04/06/07
*
* Copyright (c) 2004, Sun Microsystems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Sun Microsystems, Inc. nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sun.mirror.util;
import com.sun.mirror.type.*;
/**
* A simple visitor for types.
* <p/>
* <p> The implementations of the methods of this class do nothing but
* delegate up the type hierarchy. A subclass should override the
* methods that correspond to the kinds of types on which it will
* operate.
*
* @author Joseph D. Darcy
* @author Scott Seligman
* @version 1.4 04/06/07
* @since 1.5
*/
public class SimpleTypeVisitor implements TypeVisitor {
/**
* Creates a new <tt>SimpleTypeVisitor</tt>.
*/
public SimpleTypeVisitor() {
}
/**
* Visits a type mirror.
* The implementation does nothing.
*
* @param t the type to visit
*/
public void visitTypeMirror(TypeMirror t) {
}
/**
* Visits a primitive type.
* The implementation simply invokes
* {@link #visitTypeMirror visitTypeMirror}.
*
* @param t the type to visit
*/
public void visitPrimitiveType(PrimitiveType t) {
visitTypeMirror(t);
}
/**
* Visits a void type.
* The implementation simply invokes
* {@link #visitTypeMirror visitTypeMirror}.
*
* @param t the type to visit
*/
public void visitVoidType(VoidType t) {
visitTypeMirror(t);
}
/**
* Visits a reference type.
* The implementation simply invokes
* {@link #visitTypeMirror visitTypeMirror}.
*
* @param t the type to visit
*/
public void visitReferenceType(ReferenceType t) {
visitTypeMirror(t);
}
/**
* Visits a declared type.
* The implementation simply invokes
* {@link #visitReferenceType visitReferenceType}.
*
* @param t the type to visit
*/
public void visitDeclaredType(DeclaredType t) {
visitReferenceType(t);
}
/**
* Visits a class type.
* The implementation simply invokes
* {@link #visitDeclaredType visitDeclaredType}.
*
* @param t the type to visit
*/
public void visitClassType(ClassType t) {
visitDeclaredType(t);
}
/**
* Visits an enum type.
* The implementation simply invokes
* {@link #visitClassType visitClassType}.
*
* @param t the type to visit
*/
public void visitEnumType(EnumType t) {
visitClassType(t);
}
/**
* Visits an interface type.
* The implementation simply invokes
* {@link #visitDeclaredType visitDeclaredType}.
*
* @param t the type to visit
*/
public void visitInterfaceType(InterfaceType t) {
visitDeclaredType(t);
}
/**
* Visits an annotation type.
* The implementation simply invokes
* {@link #visitInterfaceType visitInterfaceType}.
*
* @param t the type to visit
*/
public void visitAnnotationType(AnnotationType t) {
visitInterfaceType(t);
}
/**
* Visits an array type.
* The implementation simply invokes
* {@link #visitReferenceType visitReferenceType}.
*
* @param t the type to visit
*/
public void visitArrayType(ArrayType t) {
visitReferenceType(t);
}
/**
* Visits a type variable.
* The implementation simply invokes
* {@link #visitReferenceType visitReferenceType}.
*
* @param t the type to visit
*/
public void visitTypeVariable(TypeVariable t) {
visitReferenceType(t);
}
/**
* Visits a wildcard.
* The implementation simply invokes
* {@link #visitTypeMirror visitTypeMirror}.
*
* @param t the type to visit
*/
public void visitWildcardType(WildcardType t) {
visitTypeMirror(t);
}
}
| gpl-3.0 |
sustmi/sus107-dt | src/ui/DebuggerView.cpp | 8060 | // DebuggerView.cpp
// Copyright (C) 2012 Miroslav Sustek <sus107@vsb.cz>
// 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/>.
// -*- C++ -*- generated by wxGlade HG on Fri Feb 3 02:55:31 2012
#include "DebuggerView.h"
// begin wxGlade: ::extracode
// end wxGlade
DebuggerView::DebuggerView(wxWindow* parent, int id, const wxString& title, const wxPoint& pos, const wxSize& size, long style):
wxFrame(parent, id, title, pos, size, wxDEFAULT_FRAME_STYLE)
{
// begin wxGlade: DebuggerView::DebuggerView
notebook = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0);
notebook_pane_hex = new wxPanel(notebook, wxID_ANY);
debugger_menubar = new wxMenuBar();
wxMenu* wxglade_tmp_menu_1 = new wxMenu();
wxglade_tmp_menu_1->Append(DEBUGGER_EDIT_GOTO, _("Go to address..."), _("Add or remove breakpoint at selected address"), wxITEM_NORMAL);
debugger_menubar->Append(wxglade_tmp_menu_1, _("Edit"));
wxMenu* wxglade_tmp_menu_2 = new wxMenu();
wxglade_tmp_menu_2->Append(DEBUGGER_VIEW_REGISTERS, _("Registers..."), wxEmptyString, wxITEM_NORMAL);
debugger_menubar->Append(wxglade_tmp_menu_2, _("View"));
wxMenu* wxglade_tmp_menu_3 = new wxMenu();
wxglade_tmp_menu_3->Append(DEBUGGER_TOOL_CONTINUE, _("Continue"), wxEmptyString, wxITEM_NORMAL);
wxglade_tmp_menu_3->Append(DEBUGGER_TOOL_BREAK, _("Break"), wxEmptyString, wxITEM_NORMAL);
wxglade_tmp_menu_3->Append(DEBUGGER_TOOL_STEP, _("Step instruction"), wxEmptyString, wxITEM_NORMAL);
debugger_menubar->Append(wxglade_tmp_menu_3, _("Debugger"));
SetMenuBar(debugger_menubar);
debugger_view_toolbar = new wxToolBar(this, -1);
SetToolBar(debugger_view_toolbar);
debugger_view_toolbar->SetToolBitmapSize(wxSize(24, 24));
debugger_view_toolbar->AddTool(DEBUGGER_TOOL_CONTINUE, _("Continue"), (*_img_media_playback_start_4), wxNullBitmap, wxITEM_NORMAL, _("Continue program execution"), wxEmptyString);
debugger_view_toolbar->AddTool(DEBUGGER_TOOL_BREAK, _("Break"), (*_img_media_playback_pause_4), wxNullBitmap, wxITEM_NORMAL, _("Break program"), wxEmptyString);
debugger_view_toolbar->AddTool(DEBUGGER_TOOL_STEP, _("Step"), (*_img_debug_step_into_instruction), wxNullBitmap, wxITEM_NORMAL, _("Step instruction"), wxEmptyString);
debugger_view_toolbar->AddSeparator();
debugger_view_toolbar->AddTool(DEBUGGER_TOOL_GOTOPC, _("Go to PC"), (*_img_go_next_4), wxNullBitmap, wxITEM_NORMAL, _("Go to Program Counter"), wxEmptyString);
debugger_view_toolbar->Realize();
debugger_code_view = new DebuggerCodeGui(notebook, wxID_ANY);
hex_view = new DebuggerHexGui(notebook_pane_hex, wxID_ANY);
set_properties();
do_layout();
// end wxGlade
emulator = NULL;
debugger = NULL;
}
DebuggerView::~DebuggerView()
{
if (emulator) {
emulator->removeListener(this);
}
if (debugger) {
debugger->removeListener(this);
}
}
void DebuggerView::emulatorEvent(EmulatorEvent event)
{
if (event == EMULATOR_EVENT_EMULATION_START ||
event == EMULATOR_EVENT_EMULATION_STOP ||
event == EMULATOR_EVENT_EMULATION_STEP)
{
uiUpdate();
}
}
void DebuggerView::debuggerEvent(DebuggerEvent event)
{
// nothing ?
}
void DebuggerView::attach(Emulator *emulator, Debugger *debugger)
{
this->emulator = emulator;
this->debugger = debugger;
debugger_code_view->attach(emulator, debugger);
hex_view->attach(emulator, debugger);
emulator->addListener(this);
debugger->addListener(this);
}
BEGIN_EVENT_TABLE(DebuggerView, wxFrame)
// begin wxGlade: DebuggerView::event_table
EVT_MENU(DEBUGGER_EDIT_GOTO, DebuggerView::OnEditGotoAddress)
EVT_MENU(DEBUGGER_VIEW_REGISTERS, DebuggerView::OnViewRegisters)
EVT_TOOL(DEBUGGER_TOOL_CONTINUE, DebuggerView::OnDebuggerContinue)
EVT_TOOL(DEBUGGER_TOOL_BREAK, DebuggerView::OnDebuggerBreak)
EVT_TOOL(DEBUGGER_TOOL_STEP, DebuggerView::OnDebuggerStep)
EVT_TOOL(DEBUGGER_TOOL_GOTOPC, DebuggerView::OnDebuggerGotoPc)
EVT_NOTEBOOK_PAGE_CHANGED(wxID_ANY, DebuggerView::OnDebuggerNotebookPageChanged)
// end wxGlade
EVT_MENU(DEBUGGER_SHOW_IN_HEXVIEW, DebuggerView::OnShowInHexView)
EVT_MENU(DEBUGGER_SHOW_IN_CODEVIEW, DebuggerView::OnShowInCodeView)
END_EVENT_TABLE();
void DebuggerView::uiUpdate()
{
if (debugger->getEmulator()->isRunning()) {
GetMenuBar()->Enable(DEBUGGER_TOOL_CONTINUE, false);
GetMenuBar()->Enable(DEBUGGER_TOOL_BREAK, true);
GetMenuBar()->Enable(DEBUGGER_TOOL_STEP, false);
GetToolBar()->EnableTool(DEBUGGER_TOOL_CONTINUE, false);
GetToolBar()->EnableTool(DEBUGGER_TOOL_BREAK, true);
GetToolBar()->EnableTool(DEBUGGER_TOOL_STEP, false);
} else {
GetMenuBar()->Enable(DEBUGGER_TOOL_CONTINUE, true);
GetMenuBar()->Enable(DEBUGGER_TOOL_BREAK, false);
GetMenuBar()->Enable(DEBUGGER_TOOL_STEP, true);
GetToolBar()->EnableTool(DEBUGGER_TOOL_CONTINUE, true);
GetToolBar()->EnableTool(DEBUGGER_TOOL_BREAK, false);
GetToolBar()->EnableTool(DEBUGGER_TOOL_STEP, true);
}
}
void DebuggerView::OnDebuggerStep(wxCommandEvent &event)
{
debugger->stepInstruction();
}
void DebuggerView::OnDebuggerContinue(wxCommandEvent &event)
{
debugger->emulationContinue();
}
void DebuggerView::OnDebuggerBreak(wxCommandEvent &event)
{
debugger->emulationBreak();
}
void DebuggerView::OnDebuggerGotoPc(wxCommandEvent & event)
{
debugger_code_view->gotoAddress(debugger->getCpuRegister(regPC));
}
void DebuggerView::OnEditGotoAddress(wxCommandEvent & event)
{
wxTextEntryDialog *dialog = new wxTextEntryDialog(this, _("Address (hex):"), _("Go to address..."));
if (dialog->ShowModal() == wxID_OK) {
unsigned long int val;
if (dialog->GetValue().ToULong(&val, 16)) {
debugger_code_view->gotoAddress(val);
hex_view->Select(val, val);
hex_view->MakeAddressVisible(val);
}
}
}
void DebuggerView::OnViewRegisters(wxCommandEvent &event)
{
DebuggerRegistersView *registersView = new DebuggerRegistersView(this, wxID_ANY, wxEmptyString);
registersView->attach(emulator, debugger);
registersView->Show(true);
registersView->uiUpdate();
debugger->addListener(registersView);
}
void DebuggerView::OnDebuggerNotebookPageChanged(wxNotebookEvent & event)
{
if (event.GetSelection() == 0) {
debugger_code_view->uiUpdate();
}
}
void DebuggerView::OnShowInHexView(wxCommandEvent & event)
{
hex_view->Select(debugger_code_view->getSelectedStartAddress(), debugger_code_view->getSelectedEndAddress());
hex_view->MakeAddressVisible(debugger_code_view->getSelectedStartAddress());
notebook->ChangeSelection(1);
}
void DebuggerView::OnShowInCodeView(wxCommandEvent & event)
{
if (hex_view->select->GetState()) {
debugger_code_view->selectAddresses(hex_view->select->StartOffset, hex_view->select->EndOffset);
} else {
debugger_code_view->gotoAddress(hex_view->CursorOffset());
}
hex_view->MakeAddressVisible(debugger_code_view->getSelectedStartAddress());
notebook->ChangeSelection(0);
}
// wxGlade: add DebuggerView event handlers
void DebuggerView::set_properties()
{
// begin wxGlade: DebuggerView::set_properties
SetTitle(_("Debugger"));
SetSize(wxSize(430, 480));
// end wxGlade
}
void DebuggerView::do_layout()
{
// begin wxGlade: DebuggerView::do_layout
wxBoxSizer* debugger_panes = new wxBoxSizer(wxVERTICAL);
wxBoxSizer* sizer_1 = new wxBoxSizer(wxHORIZONTAL);
sizer_1->Add(hex_view, 1, wxEXPAND, 0);
notebook_pane_hex->SetSizer(sizer_1);
notebook->AddPage(debugger_code_view, _("Code view"));
notebook->AddPage(notebook_pane_hex, _("Hex view"));
debugger_panes->Add(notebook, 1, wxEXPAND, 0);
SetSizer(debugger_panes);
Layout();
// end wxGlade
}
| gpl-3.0 |
airfield/betaflight-toolbox | tabs/motors.js | 19481 | 'use strict';
TABS.motors = {
allowTestMode: false,
feature3DEnabled: false,
feature3DSupported: false
};
TABS.motors.initialize = function (callback) {
var self = this;
self.armed = false;
self.feature3DSupported = false;
self.allowTestMode = true;
if (GUI.active_tab != 'motors') {
GUI.active_tab = 'motors';
//googleAnalytics.sendAppView('Motors');
}
function get_arm_status() {
MSP.send_message(MSP_codes.MSP_STATUS, false, false, load_config);
}
function load_config() {
MSP.send_message(MSP_codes.MSP_BF_CONFIG, false, false, load_3d);
}
function load_3d() {
var next_callback = get_motor_data;
if (semver.gte(CONFIG.apiVersion, "1.14.0")) {
self.feature3DSupported = true;
MSP.send_message(MSP_codes.MSP_3D, false, false, next_callback);
} else {
next_callback();
}
}
function get_motor_data() {
update_arm_status();
MSP.send_message(MSP_codes.MSP_MOTOR, false, false, load_html);
}
function load_html() {
$('#content').load("./tabs/motors.html", process_html);
}
MSP.send_message(MSP_codes.MSP_MISC, false, false, get_arm_status);
function update_arm_status() {
self.armed = bit_check(CONFIG.mode, 0);
}
function initSensorData() {
for (var i = 0; i < 3; i++) {
SENSOR_DATA.accelerometer[i] = 0;
}
}
function initDataArray(length) {
var data = new Array(length);
for (var i = 0; i < length; i++) {
data[i] = new Array();
data[i].min = -1;
data[i].max = 1;
}
return data;
}
function addSampleToData(data, sampleNumber, sensorData) {
for (var i = 0; i < data.length; i++) {
var dataPoint = sensorData[i];
data[i].push([sampleNumber, dataPoint]);
if (dataPoint < data[i].min) {
data[i].min = dataPoint;
}
if (dataPoint > data[i].max) {
data[i].max = dataPoint;
}
}
while (data[0].length > 300) {
for (i = 0; i < data.length; i++) {
data[i].shift();
}
}
return sampleNumber + 1;
}
var margin = {top: 20, right: 30, bottom: 10, left: 20};
function updateGraphHelperSize(helpers) {
helpers.width = helpers.targetElement.width() - margin.left - margin.right;
helpers.height = helpers.targetElement.height() - margin.top - margin.bottom;
helpers.widthScale.range([0, helpers.width]);
helpers.heightScale.range([helpers.height, 0]);
helpers.xGrid.tickSize(-helpers.height, 0, 0);
helpers.yGrid.tickSize(-helpers.width, 0, 0);
}
function initGraphHelpers(selector, sampleNumber, heightDomain) {
var helpers = {selector: selector, targetElement: $(selector), dynamicHeightDomain: !heightDomain};
helpers.widthScale = d3.scale.linear()
.clamp(true)
.domain([(sampleNumber - 299), sampleNumber]);
helpers.heightScale = d3.scale.linear()
.clamp(true)
.domain(heightDomain || [1, -1]);
helpers.xGrid = d3.svg.axis();
helpers.yGrid = d3.svg.axis();
updateGraphHelperSize(helpers);
helpers.xGrid
.scale(helpers.widthScale)
.orient("bottom")
.ticks(5)
.tickFormat("");
helpers.yGrid
.scale(helpers.heightScale)
.orient("left")
.ticks(5)
.tickFormat("");
helpers.xAxis = d3.svg.axis()
.scale(helpers.widthScale)
.ticks(5)
.orient("bottom")
.tickFormat(function (d) {return d;});
helpers.yAxis = d3.svg.axis()
.scale(helpers.heightScale)
.ticks(5)
.orient("left")
.tickFormat(function (d) {return d;});
helpers.line = d3.svg.line()
.x(function (d) { return helpers.widthScale(d[0]); })
.y(function (d) { return helpers.heightScale(d[1]); });
return helpers;
}
function drawGraph(graphHelpers, data, sampleNumber) {
var svg = d3.select(graphHelpers.selector);
if (graphHelpers.dynamicHeightDomain) {
var limits = [];
$.each(data, function (idx, datum) {
limits.push(datum.min);
limits.push(datum.max);
});
graphHelpers.heightScale.domain(d3.extent(limits));
}
graphHelpers.widthScale.domain([(sampleNumber - 299), sampleNumber]);
svg.select(".x.grid").call(graphHelpers.xGrid);
svg.select(".y.grid").call(graphHelpers.yGrid);
svg.select(".x.axis").call(graphHelpers.xAxis);
svg.select(".y.axis").call(graphHelpers.yAxis);
var group = svg.select("g.data");
var lines = group.selectAll("path").data(data, function (d, i) {return i;});
var newLines = lines.enter().append("path").attr("class", "line");
lines.attr('d', graphHelpers.line);
}
function update_model(val) {
$('.mixerPreview img').attr('src', './resources/motor_order/' + mixerList[val - 1].image + '.svg');
}
function process_html() {
// translate to user-selected language
localize();
self.feature3DEnabled = bit_check(BF_CONFIG.features, 12);
if (self.feature3DEnabled && !self.feature3DSupported) {
self.allowTestMode = false;
}
$('#motorsEnableTestMode').prop('checked', false);
$('#motorsEnableTestMode').prop('disabled', true);
update_model(CONFIG.multiType);
// Always start with default/empty sensor data array, clean slate all
initSensorData();
// Setup variables
var samples_accel_i = 0,
accel_data = initDataArray(3),
accelHelpers = initGraphHelpers('#accel', samples_accel_i, [-2, 2]),
accel_max_read = [0, 0, 0],
accel_offset = [0, 0, 0],
accel_offset_established = false;
var raw_data_text_ements = {
x: [],
y: [],
z: [],
rms: []
};
$('.plot_control .x, .plot_control .y, .plot_control .z, .plot_control .rms').each(function () {
var el = $(this);
if (el.hasClass('x')) {
raw_data_text_ements.x.push(el);
} else if (el.hasClass('y')) {
raw_data_text_ements.y.push(el);
} else if (el.hasClass('z')) {
raw_data_text_ements.z.push(el);
} else if (el.hasClass('rms')) {
raw_data_text_ements.rms.push(el);
}
});
// set refresh speeds according to configuration saved in storage
chrome.storage.local.get('motors_tab_accel_settings', function (result) {
if (result.motors_tab_accel_settings) {
$('.tab-motors select[name="accel_refresh_rate"]').val(result.motors_tab_accel_settings.rate);
$('.tab-motors select[name="accel_scale"]').val(result.motors_tab_accel_settings.scale);
// start polling data by triggering refresh rate change event
$('.tab-motors .rate select:first').change();
} else {
// start polling immediatly (as there is no configuration saved in the storage)
$('.tab-motors .rate select:first').change();
}
});
$('.tab-motors .rate select, .tab-motors .scale select').change(function () {
var rate = parseInt($('.tab-motors select[name="accel_refresh_rate"]').val(), 10);
var scale = parseFloat($('.tab-motors select[name="accel_scale"]').val());
// store current/latest refresh rates in the storage
chrome.storage.local.set({'motors_tab_accel_settings': {'rate': rate, 'scale': scale}});
accelHelpers = initGraphHelpers('#accel', samples_accel_i, [-scale, scale]);
// timer initialization
GUI.interval_kill_all(['motor_and_status_pull']);
GUI.interval_add('IMU_pull', function imu_data_pull() {
MSP.send_message(MSP_codes.MSP_RAW_IMU, false, false, update_accel_graph);
}, rate, true);
function update_accel_graph() {
if (!accel_offset_established) {
for (var i = 0; i < 3; i++) {
accel_offset[i] = SENSOR_DATA.accelerometer[i] * -1;
}
accel_offset_established = true;
}
var accel_with_offset = [
accel_offset[0] + SENSOR_DATA.accelerometer[0],
accel_offset[1] + SENSOR_DATA.accelerometer[1],
accel_offset[2] + SENSOR_DATA.accelerometer[2]
];
updateGraphHelperSize(accelHelpers);
samples_accel_i = addSampleToData(accel_data, samples_accel_i, accel_with_offset);
drawGraph(accelHelpers, accel_data, samples_accel_i);
// Compute RMS of acceleration in displayed period of time
// This is particularly useful for motor balancing as it
// eliminates the need for external tools
var sum = 0.0;
for (var j = 0; j < accel_data.length; j++)
for (var k = 0; k < accel_data[j].length; k++)
sum += accel_data[j][k][1]*accel_data[j][k][1];
var rms = Math.sqrt(sum/(accel_data[0].length+accel_data[1].length+accel_data[2].length));
raw_data_text_ements.x[0].text(accel_with_offset[0].toFixed(2) + ' (' + accel_max_read[0].toFixed(2) + ')');
raw_data_text_ements.y[0].text(accel_with_offset[1].toFixed(2) + ' (' + accel_max_read[1].toFixed(2) + ')');
raw_data_text_ements.z[0].text(accel_with_offset[2].toFixed(2) + ' (' + accel_max_read[2].toFixed(2) + ')');
raw_data_text_ements.rms[0].text(rms.toFixed(4));
for (var i = 0; i < 3; i++) {
if (Math.abs(accel_with_offset[i]) > Math.abs(accel_max_read[i])) accel_max_read[i] = accel_with_offset[i];
}
}
});
$('a.reset_accel_max').click(function () {
accel_max_read = [0, 0, 0];
accel_offset_established = false;
});
var number_of_valid_outputs = (MOTOR_DATA.indexOf(0) > -1) ? MOTOR_DATA.indexOf(0) : 8;
var motors_wrapper = $('.motors .bar-wrapper'),
servos_wrapper = $('.servos .bar-wrapper');
for (var i = 0; i < 8; i++) {
motors_wrapper.append('\
<div class="m-block motor-' + i + '">\
<div class="meter-bar">\
<div class="label"></div>\
<div class="indicator">\
<div class="label">\
<div class="label"></div>\
</div>\
</div>\
</div>\
</div>\
');
servos_wrapper.append('\
<div class="m-block servo-' + (7 - i) + '">\
<div class="meter-bar">\
<div class="label"></div>\
<div class="indicator">\
<div class="label">\
<div class="label"></div>\
</div>\
</div>\
</div>\
</div>\
');
}
$('div.sliders input').prop('min', MISC.mincommand);
$('div.sliders input').prop('max', MISC.maxthrottle);
$('div.values li:not(:last)').text(MISC.mincommand);
if(self.feature3DEnabled && self.feature3DSupported) {
//Arbitrary sanity checks
//Note: values may need to be revisited
if(_3D.neutral3d > 1575 || _3D.neutral3d < 1425)
_3D.neutral3d = 1500;
$('div.sliders input').val(_3D.neutral3d);
} else {
$('div.sliders input').val(MISC.mincommand);
}
if(self.allowTestMode){
// UI hooks
var buffering_set_motor = [],
buffer_delay = false;
$('div.sliders input:not(.master)').on('input', function () {
var index = $(this).index(),
buffer = [],
i;
$('div.values li').eq(index).text($(this).val());
for (i = 0; i < 8; i++) {
var val = parseInt($('div.sliders input').eq(i).val());
buffer.push(lowByte(val));
buffer.push(highByte(val));
}
buffering_set_motor.push(buffer);
if (!buffer_delay) {
buffer_delay = setTimeout(function () {
buffer = buffering_set_motor.pop();
MSP.send_message(MSP_codes.MSP_SET_MOTOR, buffer);
buffering_set_motor = [];
buffer_delay = false;
}, 10);
}
});
}
$('div.sliders input.master').on('input', function () {
var val = $(this).val();
$('div.sliders input:not(:disabled, :last)').val(val);
$('div.values li:not(:last)').slice(0, number_of_valid_outputs).text(val);
$('div.sliders input:not(:last):first').trigger('input');
});
$('#motorsEnableTestMode').change(function () {
if ($(this).is(':checked')) {
$('div.sliders input').slice(0, number_of_valid_outputs).prop('disabled', false);
// unlock master slider
$('div.sliders input:last').prop('disabled', false);
} else {
// disable sliders / min max
$('div.sliders input').prop('disabled', true);
// change all values to default
if (self.feature3DEnabled && self.feature3DSupported) {
$('div.sliders input').val(_3D.neutral3d);
} else {
$('div.sliders input').val(MISC.mincommand);
}
$('div.sliders input').trigger('input');
}
});
// check if motors are already spinning
var motors_running = false;
for (var i = 0; i < number_of_valid_outputs; i++) {
if( !self.feature3DEnabled ){
if (MOTOR_DATA[i] > MISC.mincommand) {
motors_running = true;
break;
}
}else{
if( (MOTOR_DATA[i] < _3D.deadband3d_low) || (MOTOR_DATA[i] > _3D.deadband3d_high) ){
motors_running = true;
break;
}
}
}
if (motors_running) {
if (!self.armed && self.allowTestMode) {
$('#motorsEnableTestMode').prop('checked', true);
}
// motors are running adjust sliders to current values
var sliders = $('div.sliders input:not(.master)');
var master_value = MOTOR_DATA[0];
for (var i = 0; i < MOTOR_DATA.length; i++) {
if (MOTOR_DATA[i] > 0) {
sliders.eq(i).val(MOTOR_DATA[i]);
if (master_value != MOTOR_DATA[i]) {
master_value = false;
}
}
}
// only fire events when all values are set
sliders.trigger('input');
// slide master slider if condition is valid
if (master_value) {
$('div.sliders input.master').val(master_value);
$('div.sliders input.master').trigger('input');
}
}
$('#motorsEnableTestMode').change();
// data pulling functions used inside interval timer
function get_status() {
// status needed for arming flag
MSP.send_message(MSP_codes.MSP_STATUS, false, false, get_motor_data);
}
function get_motor_data() {
MSP.send_message(MSP_codes.MSP_MOTOR, false, false, get_servo_data);
}
function get_servo_data() {
MSP.send_message(MSP_codes.MSP_SERVO, false, false, update_ui);
}
var full_block_scale = MISC.maxthrottle - MISC.mincommand;
function update_ui() {
var previousArmState = self.armed;
var block_height = $('div.m-block:first').height();
for (var i = 0; i < MOTOR_DATA.length; i++) {
var data = MOTOR_DATA[i] - MISC.mincommand,
margin_top = block_height - (data * (block_height / full_block_scale)).clamp(0, block_height),
height = (data * (block_height / full_block_scale)).clamp(0, block_height),
color = parseInt(data * 0.009);
$('.motor-' + i + ' .label', motors_wrapper).text(MOTOR_DATA[i]);
$('.motor-' + i + ' .indicator', motors_wrapper).css({'margin-top' : margin_top + 'px', 'height' : height + 'px', 'background-color' : 'rgba(89,170,41,1.'+ color +')'});
}
// servo indicators are still using old (not flexible block scale), it will be changed in the future accordingly
for (var i = 0; i < SERVO_DATA.length; i++) {
var data = SERVO_DATA[i] - 1000,
margin_top = block_height - (data * (block_height / 1000)).clamp(0, block_height),
height = (data * (block_height / 1000)).clamp(0, block_height),
color = parseInt(data * 0.009);
$('.servo-' + i + ' .label', servos_wrapper).text(SERVO_DATA[i]);
$('.servo-' + i + ' .indicator', servos_wrapper).css({'margin-top' : margin_top + 'px', 'height' : height + 'px', 'background-color' : 'rgba(89,170,41,1'+ color +')'});
}
//keep the following here so at least we get a visual cue of our motor setup
update_arm_status();
if (!self.allowTestMode) return;
if (self.armed) {
$('#motorsEnableTestMode').prop('disabled', true);
$('#motorsEnableTestMode').prop('checked', false);
} else {
if (self.allowTestMode) {
$('#motorsEnableTestMode').prop('disabled', false);
}
}
if (previousArmState != self.armed) {
console.log('arm state change detected');
$('#motorsEnableTestMode').change();
}
}
// enable Status and Motor data pulling
GUI.interval_add('motor_and_status_pull', get_status, 50, true);
GUI.content_ready(callback);
}
};
TABS.motors.cleanup = function (callback) {
if (callback) callback();
};
| gpl-3.0 |
wasare/ciaweb | app/sagu/lib/GetField.php | 1183 | <?
/**
*
*/
function GetField($id,$field,$table,$SaguAssert)
{
$sql = "select " . $field . " from " . $table . " where id = '$id'";
$conn = new Connection;
$conn->Open();
$query = @$conn->CreateQuery($sql);
if ( @$query->MoveNext() )
$obj = $query->GetValue(1);
$query->Close();
$conn->Close();
// if ( $SaguAssert )
// SaguAssert(!empty($obj),"$field [<b><i>$id</b></i>] não cadastrado ou código Inválido!");
return $obj;
}
function GetField2($id,$field,$table,$conn)
{
$sql = "select " . $field . " from " . $table . " where id = '$id'";
$query_field2 = $conn->CreateQuery($sql);
if ( $query_field2->MoveNext() )
$obj = $query_field2->GetValue(1);
$query_field2->Close();
return $obj;
}
function GetField3($id,$field,$table,$field_name,$conn)
{
$sql = "select " . $field . " from " . $table . " where " . $field_name . " = '$id'";
$query_field3 = $conn->CreateQuery($sql);
if ( $query_field3->MoveNext() )
$obj = $query_field3->GetValue(1);
$query_field3->Close();
return $obj;
}
?>
| gpl-3.0 |
feimermt/bountify | database/migrations/2014_10_12_000000_create_users_table.php | 706 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
cde $table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| gpl-3.0 |
madirish/hector | app/scripts/nessus_scan/form.php | 1427 | <!-- nessus form -->
<script type="text/javascript">
</script>
<?php
/**
* Require the XSRF safe form
*/
require_once($approot . 'lib/class.Form.php');
$form = new Form();
$formname = 'add_scan_type_form';
$form->set_name($formname);
$token = $form->get_token();
$form->save();
?>
<fieldset>
<legend>Nessus Scan</legend>
<p>Configure your Nessus scan to perform patch, configuration, and compliance auditing.</p>
<table>
<tr><td><strong>Scan name:</strong></td><td><input type="text" id="name" name="name" class="input-block-level" placeholder="Descriptive scan name"/></td></tr>
<tr><td style="vertical-align: text-top;"><strong>Specifications:<strong></td><td>
<div class="form-group">
<div class="control-group">
<label for="scanPolicy">Scan Policy:</label>
<select id="nessusPolicy" name="nessusPolicy">
<?php foreach ($policy as $key => $val) {?>
<?php foreach ($val as $key1 => $val1) {?>
<option value="<?php echo $key1;?>"><?php echo $val1["policyName"]; ?></option>
<?php }} ?>
</select>
</div>
<div class="control-group">
<label for="scanHostname">Hostname:</label>
<input name="Scan Hostname" type="text" id="scanHostname" value="" class="input-block-level" placeholder="ex: infosec.sas.upenn.edu"/>
</div>
</div>
</td></tr>
<tr><td> </td><td><input type="button" id="saveScan" value="Save Scan"/></td></tr>
</table>
</fieldset> | gpl-3.0 |
qt-haiku/LibreOffice | qadevOOo/tests/java/mod/_forms/OPatternModel.java | 6157 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package mod._forms;
import com.sun.star.beans.NamedValue;
import java.io.PrintWriter;
import lib.TestEnvironment;
import lib.TestParameters;
import util.DBTools;
/**
* Test for object which is represented by service
* <code>com.sun.star.form.component.PatternField</code>. <p>
* Object implements the following interfaces :
* <ul>
* <li> <code>com::sun::star::io::XPersistObject</code></li>
* <li> <code>com::sun::star::form::XReset</code></li>
* <li> <code>com::sun::star::form::XBoundComponent</code></li>
* <li> <code>com::sun::star::form::FormComponent</code></li>
* <li> <code>com::sun::star::beans::XFastPropertySet</code></li>
* <li> <code>com::sun::star::beans::XMultiPropertySet</code></li>
* <li> <code>com::sun::star::form::component::PatternField</code></li>
* <li> <code>com::sun::star::form::DataAwareControlModel</code></li>
* <li> <code>com::sun::star::form::XUpdateBroadcaster</code></li>
* <li> <code>com::sun::star::awt::UnoControlPatternFieldModel</code></li>
* <li> <code>com::sun::star::form::component::DatabasePatternField</code></li>
* <li> <code>com::sun::star::form::FormControlModel</code></li>
* <li> <code>com::sun::star::beans::XPropertyState</code></li>
* <li> <code>com::sun::star::container::XNamed</code></li>
* <li> <code>com::sun::star::lang::XComponent</code></li>
* <li> <code>com::sun::star::lang::XEventListener</code></li>
* <li> <code>com::sun::star::beans::XPropertyAccess</code></li>
* <li> <code>com::sun::star::beans::XPropertyContainer</code></li>
* <li> <code>com::sun::star::beans::XPropertySet</code></li>
* <li> <code>com::sun::star::form::XLoadListener</code></li>
* <li> <code>com::sun::star::container::XChild</code></li>
* </ul> <p>
*
* This object test <b> is NOT </b> designed to be run in several
* threads concurently.
*
* @see com.sun.star.io.XPersistObject
* @see com.sun.star.form.XReset
* @see com.sun.star.form.XBoundComponent
* @see com.sun.star.form.FormComponent
* @see com.sun.star.beans.XFastPropertySet
* @see com.sun.star.beans.XMultiPropertySet
* @see com.sun.star.form.component.PatternField
* @see com.sun.star.form.DataAwareControlModel
* @see com.sun.star.form.XUpdateBroadcaster
* @see com.sun.star.awt.UnoControlPatternFieldModel
* @see com.sun.star.form.component.DatabasePatternField
* @see com.sun.star.form
* @see com.sun.star.beans.XPropertyState
* @see com.sun.star.container.XNamed
* @see com.sun.star.lang.XComponent
* @see com.sun.star.lang.XEventListener
* @see com.sun.star.beans.XPropertyAccess
* @see com.sun.star.beans.XPropertyContainer
* @see com.sun.star.beans.XPropertySet
* @see com.sun.star.form.XLoadListener
* @see com.sun.star.container.XChild
* @see ifc.io._XPersistObject
* @see ifc.form._XReset
* @see ifc.form._XBoundComponent
* @see ifc.form._FormComponent
* @see ifc.beans._XFastPropertySet
* @see ifc.beans._XMultiPropertySet
* @see ifc.form.component._PatternField
* @see ifc.form._DataAwareControlModel
* @see ifc.form._XUpdateBroadcaster
* @see ifc.awt._UnoControlPatternFieldModel
* @see ifc.form.component._DatabasePatternField
* @see ifc.form._FormControlModel
* @see ifc.beans._XPropertyState
* @see ifc.container._XNamed
* @see ifc.lang._XComponent
* @see ifc.lang._XEventListener
* @see ifc.beans._XPropertySet
* @see ifc.form._XLoadListener
* @see ifc.container._XChild
*/
public class OPatternModel extends GenericModelTest {
/**
* Set some member variable of the super class <CODE>GenericModelTest</CODE>:
* <pre>
* super.m_ChangePropertyName = "Text";
* super.m_kindOfControl="PatternField";
* super.m_ObjectName = "stardiv.one.form.component.PatternField";
* NamedValue DataField = new NamedValue();
* DataField.Name = "DataField";
* DataField.Value = DBTools.TST_STRING_F;
* super.m_propertiesToSet.add(DataField);
*
* super.m_LCShape_Type = "FixedText";
* </pre>
* Then <CODE>super.initialize()</CODE> was called.
* @param tParam the test parameter
* @param log the log writer
*/
protected void initialize(TestParameters tParam, PrintWriter log) {
super.initialize(tParam, log);
super.m_ChangePropertyName = "Text";
super.m_kindOfControl="PatternField";
super.m_ObjectName = "stardiv.one.form.component.PatternField";
NamedValue DataField = new NamedValue();
DataField.Name = "DataField";
DataField.Value = DBTools.TST_STRING_F;
super.m_propertiesToSet.add(DataField);
super.m_LCShape_Type = "FixedText";
} /**
* calls <CODE>cleanup()</CODE> from it's super class
* @param tParam the test parameter
* @param log the log writer
*/
protected void cleanup(TestParameters tParam, PrintWriter log) {
super.cleanup(tParam, log);
}
/**
* calls <CODE>createTestEnvironment()</CODE> from it's super class
* @param Param the test parameter
* @param log the log writer
* @return lib.TestEnvironment
*/
protected synchronized TestEnvironment createTestEnvironment(TestParameters Param,
PrintWriter log) {
return super.createTestEnvironment(Param, log);
}
} // finish class OPatternModel
| gpl-3.0 |
saophaisau/port | Core/AIO Ports/ReformedAIO/Champions/Xerath/Drawings/Damage/DamageDrawing.cs | 1928 | using EloBuddy;
using LeagueSharp.Common;
namespace ReformedAIO.Champions.Xerath.Drawings.Damage
{
using System;
using System.Linq;
using LeagueSharp;
using LeagueSharp.Common;
using ReformedAIO.Champions.Xerath.Core.Damage;
using ReformedAIO.Library.Drawings;
using RethoughtLib.FeatureSystem.Abstract_Classes;
using SharpDX;
internal sealed class DamageDrawing : ChildBase
{
public override string Name { get; set; } = "Damage";
public readonly XerathDamage Damage;
public DamageDrawing(XerathDamage damage)
{
this.Damage = damage;
}
private HeroHealthBarIndicator heroHealthBarIndicator;
public void OnDraw(EventArgs args)
{
if (ObjectManager.Player.IsDead) return;
foreach (var enemy in ObjectManager.Get<AIHeroClient>().Where(ene => ene.IsValidTarget(3500)))
{
heroHealthBarIndicator.Unit = enemy;
heroHealthBarIndicator.DrawDmg(Damage.GetComboDamage(enemy),
enemy.Health <= Damage.GetComboDamage(enemy) * .9
? Color.LawnGreen
: Color.Yellow);
}
}
protected override void OnDisable(object sender, FeatureBaseEventArgs eventArgs)
{
base.OnDisable(sender, eventArgs);
Drawing.OnDraw -= OnDraw;
}
protected override void OnEnable(object sender, FeatureBaseEventArgs eventArgs)
{
base.OnEnable(sender, eventArgs);
Drawing.OnDraw += OnDraw;
}
protected override void OnLoad(object sender, FeatureBaseEventArgs eventArgs)
{
base.OnLoad(sender, eventArgs);
heroHealthBarIndicator = new HeroHealthBarIndicator();
}
}
}
| gpl-3.0 |
zerjioang/OnTheStreet | app/src/main/java/zerjioang/onthestreet/util/Util.java | 823 | package zerjioang.onthestreet.util;
/**
* Created by .local on 23/04/2017.
*/
public class Util {
public static double getDistanceFromLatLonInKm(double lat1, double lon1, double lat2, double lon2) {
int R = 6371; // Radius of the earth in km
double dLat = deg2rad(lat2-lat1); // deg2rad below
double dLon = deg2rad(lon2-lon1);
double a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c; // Distance in km
return d;
}
private static double deg2rad(double deg) {
return deg * (Math.PI/180);
}
}
| gpl-3.0 |
davidam/python-examples | scikit/plot_denoise.py | 3210 | """
====================
Denoising a picture
====================
In this example, we denoise a noisy version of a picture using the total
variation, bilateral, and wavelet denoising filters.
Total variation and bilateral algorithms typically produce "posterized" images
with flat domains separated by sharp edges. It is possible to change the degree
of posterization by controlling the tradeoff between denoising and faithfulness
to the original image.
Total variation filter
----------------------
The result of this filter is an image that has a minimal total variation norm,
while being as close to the initial image as possible. The total variation is
the L1 norm of the gradient of the image.
Bilateral filter
----------------
A bilateral filter is an edge-preserving and noise reducing filter. It averages
pixels based on their spatial closeness and radiometric similarity.
Wavelet denoising filter
------------------------
A wavelet denoising filter relies on the wavelet representation of the image.
The noise is represented by small values in the wavelet domain which are set to
0.
In color images, wavelet denoising is typically done in the `YCbCr color
space`_ as denoising in separate color channels may lead to more apparent
noise.
.. _`YCbCr color space`: https://en.wikipedia.org/wiki/YCbCr
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage.restoration import (denoise_tv_chambolle, denoise_bilateral,
denoise_wavelet, estimate_sigma)
from skimage import data, img_as_float, color
from skimage.util import random_noise
original = img_as_float(data.chelsea()[100:250, 50:300])
sigma = 0.155
noisy = random_noise(original, var=sigma**2)
fig, ax = plt.subplots(nrows=2, ncols=4, figsize=(8, 5),
sharex=True, sharey=True)
plt.gray()
# Estimate the average noise standard deviation across color channels.
sigma_est = estimate_sigma(noisy, multichannel=True, average_sigmas=True)
# Due to clipping in random_noise, the estimate will be a bit smaller than the
# specified sigma.
print("Estimated Gaussian noise standard deviation = {}".format(sigma_est))
ax[0, 0].imshow(noisy)
ax[0, 0].axis('off')
ax[0, 0].set_title('Noisy')
ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
ax[0, 1].axis('off')
ax[0, 1].set_title('TV')
ax[0, 2].imshow(denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15,
multichannel=True))
ax[0, 2].axis('off')
ax[0, 2].set_title('Bilateral')
ax[0, 3].imshow(denoise_wavelet(noisy, multichannel=True))
ax[0, 3].axis('off')
ax[0, 3].set_title('Wavelet denoising')
ax[1, 1].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True))
ax[1, 1].axis('off')
ax[1, 1].set_title('(more) TV')
ax[1, 2].imshow(denoise_bilateral(noisy, sigma_color=0.1, sigma_spatial=15,
multichannel=True))
ax[1, 2].axis('off')
ax[1, 2].set_title('(more) Bilateral')
ax[1, 3].imshow(denoise_wavelet(noisy, multichannel=True, convert2ycbcr=True))
ax[1, 3].axis('off')
ax[1, 3].set_title('Wavelet denoising\nin YCbCr colorspace')
ax[1, 0].imshow(original)
ax[1, 0].axis('off')
ax[1, 0].set_title('Original')
fig.tight_layout()
plt.show()
| gpl-3.0 |
kerimlcr/ab2017-dpyo | ornek/sayonara/sayonara-0.9.2/src/GUI/Playlist/Model/PlaylistItemModel.cpp | 8323 | /* PlaylistItemModel.cpp */
/* Copyright (C) 2011-2016 Lucio Carreras
*
* This file is part of sayonara player
*
* 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/>.
*/
/*
* PlaylistItemModel.cpp
*
* Created on: Apr 8, 2011
* Author: Lucio Carreras
*/
#include "PlaylistItemModel.h"
#include "Helper/FileHelper.h"
#include "GUI/Helper/CustomMimeData.h"
#include "Helper/Settings/Settings.h"
#include "Helper/LibrarySearchMode.h"
PlaylistItemModel::PlaylistItemModel(PlaylistPtr pl, QObject* parent) :
AbstractSearchListModel(parent),
_pl(pl)
{
connect(_pl.get(), &Playlist::sig_data_changed, this, &PlaylistItemModel::playlist_changed);
}
PlaylistItemModel::~PlaylistItemModel() {
}
int PlaylistItemModel::rowCount(const QModelIndex &parent) const{
Q_UNUSED(parent);
return _pl->get_count();
}
QVariant PlaylistItemModel::data(const QModelIndex &index, int role) const{
if (!index.isValid()) {
return QVariant();
}
if ( !between(index.row(), _pl->get_count())) {
return QVariant();
}
if (role == Qt::DisplayRole) {
return MetaData::toVariant( _pl->at_const_ref(index.row()) );
}
else{
return QVariant();
}
}
const MetaData& PlaylistItemModel::get_md(int row) const
{
return _pl->at_const_ref(row);
}
Qt::ItemFlags PlaylistItemModel::flags(const QModelIndex &index = QModelIndex()) const{
int row = index.row();
if (!index.isValid()){
return Qt::ItemIsEnabled;
}
if( row >= 0 && row < _pl->get_count()){
const MetaData& md = get_md(row);
if(md.is_disabled){
return Qt::NoItemFlags;
}
}
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}
bool PlaylistItemModel::setData(const QModelIndex&index, const QVariant&var, int role)
{
Q_UNUSED(var)
Q_UNUSED(role)
if(!index.isValid()){
return false;
}
return true;
}
void PlaylistItemModel::clear()
{
_pl->clear();
}
void PlaylistItemModel::remove_rows(const SP::Set<int>& indexes){
_pl->delete_tracks(indexes);
}
void PlaylistItemModel::move_rows(const SP::Set<int>& indexes, int target_index){
_pl->move_tracks(indexes, target_index);
playlist_changed(0);
}
void PlaylistItemModel::copy_rows(const SP::Set<int>& indexes, int target_index){
_pl->copy_tracks(indexes, target_index);
playlist_changed(0);
}
int PlaylistItemModel::get_current_track() const {
return _pl->get_cur_track_idx();
}
void PlaylistItemModel::set_current_track(int row)
{
_pl->change_track(row);
}
void PlaylistItemModel::insert_metadata(const MetaDataList& v_md, int target_index){
_pl->insert_tracks(v_md, target_index);
}
void PlaylistItemModel::get_metadata(const IdxList& rows, MetaDataList& v_md) {
v_md.clear();
for(int row : rows){
v_md << _pl->at_const_ref(row);
}
}
#define ALBUM_SEARCH '%'
#define ARTIST_SEARCH '$'
#define JUMP ':'
QModelIndex PlaylistItemModel::getFirstRowIndexOf(QString substr) {
if(_pl->is_empty()) {
return this->index(-1, -1);
}
return getNextRowIndexOf(substr, 0);
}
QModelIndex PlaylistItemModel::getPrevRowIndexOf(QString substr, int row, const QModelIndex &parent) {
Q_UNUSED(parent)
Settings* settings = Settings::getInstance();
LibraryHelper::SearchModeMask mask = settings->get(Set::Lib_SearchMode);
int len = _pl->get_count();
if(len < row) row = len - 1;
// ALBUM
if(substr.startsWith(ALBUM_SEARCH)) {
substr.remove(ALBUM_SEARCH);
substr = LibraryHelper::convert_search_string(substr, mask);
for(int i=0; i<len; i++) {
if(row - i < 0) row = len - 1;
int row_idx = (row - i) % len;
QString album = _pl->at_const_ref(row_idx).album;
album = LibraryHelper::convert_search_string(album, mask);
if(album.contains(substr))
{
return this->index(row_idx, 0);
}
}
}
//ARTIST
else if(substr.startsWith(ARTIST_SEARCH)) {
substr.remove(ARTIST_SEARCH);
substr = LibraryHelper::convert_search_string(substr, mask);
for(int i=0; i<len; i++) {
if(row - i < 0) row = len - 1;
int row_idx = (row - i) % len;
QString artist = _pl->at_const_ref(row_idx).artist;
artist = LibraryHelper::convert_search_string(artist, mask);
if(artist.contains(substr))
{
return this->index(row_idx, 0);
}
}
}
// JUMP
else if(substr.startsWith(JUMP)) {
substr.remove(JUMP).trimmed();
bool ok;
int line = substr.toInt(&ok);
if(ok && len > line) {
return this->index(line, 0);
}
}
// TITLE
else {
for(int i=0; i<len; i++)
{
if(row - i < 0) row = len - 1;
int row_idx = (row - i) % len;
QString title = _pl->at_const_ref(row_idx).title;
title = LibraryHelper::convert_search_string(title, mask);
if(title.contains(substr))
{
return this->index(row_idx, 0);
}
}
}
return this->index(-1, -1);
}
QModelIndex PlaylistItemModel::getNextRowIndexOf(QString substr, int row, const QModelIndex &parent) {
Q_UNUSED(parent)
Settings* settings = Settings::getInstance();
LibraryHelper::SearchModeMask mask = settings->get(Set::Lib_SearchMode);
int len = _pl->get_count();
if(len < row) row = len - 1;
// ALBUM
if(substr.startsWith(ALBUM_SEARCH)) {
substr.remove(ALBUM_SEARCH);
substr = LibraryHelper::convert_search_string(substr, mask);
for(int i=0; i< len; i++) {
int row_idx = (i + row) % len;
QString album = _pl->at_const_ref(row_idx).album;
album = LibraryHelper::convert_search_string(album, mask);
if(album.contains(substr))
{
return this->index(row_idx, 0);
}
}
}
//ARTIST
else if(substr.startsWith(ARTIST_SEARCH)) {
substr.remove(ARTIST_SEARCH);
substr = LibraryHelper::convert_search_string(substr, mask);
for(int i=0; i< len; i++) {
int row_idx = (i + row) % len;
QString artist = _pl->at_const_ref(row_idx).artist;
artist = LibraryHelper::convert_search_string(artist, mask);
if(artist.contains(substr))
{
return this->index(row_idx, 0);
}
}
}
// JUMP
else if(substr.startsWith(JUMP)) {
substr.remove(JUMP).trimmed();
bool ok;
int line = substr.toInt(&ok);
if(ok && (_pl->get_count() > line) ){
return this->index(line, 0);
}
else return this->index(-1, -1);
}
// TITLE
else {
for(int i=0; i< len; i++) {
int row_idx = (i + row) % len;
QString title = _pl->at_const_ref(row_idx).title;
title = LibraryHelper::convert_search_string(title, mask);
if(title.contains(substr))
{
return this->index(row_idx, 0);
}
}
}
return this->index(-1, -1);
}
QMap<QChar, QString> PlaylistItemModel::getExtraTriggers() {
QMap<QChar, QString> map;
map.insert(ARTIST_SEARCH, tr("Artist"));
map.insert(ALBUM_SEARCH, tr("Album"));
map.insert(JUMP, tr("Goto row"));
return map;
}
CustomMimeData* PlaylistItemModel::get_custom_mimedata(const QModelIndexList& indexes) const {
CustomMimeData* mimedata = new CustomMimeData();
MetaDataList v_md;
QList<QUrl> urls;
for(const QModelIndex& idx : indexes){
if(idx.row() >= _pl->get_count()){
continue;
}
v_md << _pl->at_const_ref(idx.row());
QUrl url(QString("file://") + _pl->at_const_ref(idx.row()).filepath());
urls << url;
}
if(v_md.isEmpty()){
return nullptr;
}
mimedata->setMetaData(v_md);
mimedata->setText("tracks");
mimedata->setUrls(urls);
return mimedata;
}
QMimeData* PlaylistItemModel::mimeData(const QModelIndexList& indexes) const {
CustomMimeData* cmd = get_custom_mimedata(indexes);
return static_cast<QMimeData*> (cmd);
}
bool PlaylistItemModel::has_local_media(const IdxList& idxs) const
{
const MetaDataList& tracks = _pl->get_playlist();
for(int idx : idxs){
if(!Helper::File::is_www(tracks[idx].filepath())){
return true;
}
}
return false;
}
void PlaylistItemModel::playlist_changed(int pl_idx)
{
Q_UNUSED(pl_idx)
emit dataChanged(this->index(0),
this->index(_pl->get_count() - 1));
}
| gpl-3.0 |
vb2005xu/eduTrac | eduTrac/Application/Views/ftp/index.php | 2164 | <?php if ( ! defined('BASE_PATH') ) exit('No direct script access allowed');
/**
*
* FTP View
*
* PHP 5.4+
*
* eduTrac(tm) : Student Information System (http://www.7mediaws.org/)
* @copyright (c) 2013 7 Media Web Solutions, LLC
*
* 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/>.
*
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License, version 3
* @link http://www.7mediaws.org/
* @since 3.0.3
* @package eduTrac
* @author Joshua Parker <josh@7mediaws.org>
*/
?>
<script type="text/javascript" src="<?=BASE_URL;?>static/assets/plugins/elfinder/js/elfinder.min.js"></script>
<script type="text/javascript">
$().ready(function() {
var elf = $('#elfinder').elfinder({
url : '<?=BASE_URL;?>ftp/connector/',
modal: true,
resizable:false
}).elfinder('instance');
});
</script>
<ul class="breadcrumb">
<li><?=_t( 'You are here' );?></li>
<li><a href="<?=BASE_URL;?>dashboard/<?=bm();?>" class="glyphicons dashboard"><i></i> <?=_t( 'Dashboard' );?></a></li>
<li class="divider"></li>
<li><?=_t( 'FTP' );?></li>
</ul>
<h3><?=_t( 'FTP' );?></h3>
<div class="innerLR">
<!-- Widget -->
<div class="widget widget-heading-simple widget-body-gray">
<div class="widget-body">
<div class="row">
<div class="col-md-12">
<div class="panel-body">
<div id="elfinder"></div>
</div>
</div>
</div>
</div>
</div>
<!-- // Widget END -->
</div>
</div>
<!-- // Content END --> | gpl-3.0 |
AlbRoehm/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/TaskFormActivity.java | 57779 | package com.habitrpg.android.habitica.ui.activities;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import com.habitrpg.android.habitica.R;
import com.habitrpg.android.habitica.components.AppComponent;
import com.habitrpg.android.habitica.data.TagRepository;
import com.habitrpg.android.habitica.data.TaskRepository;
import com.habitrpg.android.habitica.helpers.FirstDayOfTheWeekHelper;
import com.habitrpg.android.habitica.helpers.RemindersManager;
import com.habitrpg.android.habitica.helpers.RemoteConfigManager;
import com.habitrpg.android.habitica.helpers.RxErrorHandler;
import com.habitrpg.android.habitica.helpers.TaskFilterHelper;
import com.habitrpg.android.habitica.models.Tag;
import com.habitrpg.android.habitica.models.tasks.ChecklistItem;
import com.habitrpg.android.habitica.models.tasks.Days;
import com.habitrpg.android.habitica.models.tasks.RemindersItem;
import com.habitrpg.android.habitica.models.tasks.Task;
import com.habitrpg.android.habitica.models.user.Stats;
import com.habitrpg.android.habitica.modules.AppModule;
import com.habitrpg.android.habitica.ui.WrapContentRecyclerViewLayoutManager;
import com.habitrpg.android.habitica.ui.adapter.tasks.CheckListAdapter;
import com.habitrpg.android.habitica.ui.adapter.tasks.RemindersAdapter;
import com.habitrpg.android.habitica.ui.helpers.MarkdownParser;
import com.habitrpg.android.habitica.ui.helpers.SimpleItemTouchHelperCallback;
import com.habitrpg.android.habitica.ui.helpers.ViewHelper;
import net.pherth.android.emoji_library.EmojiEditText;
import net.pherth.android.emoji_library.EmojiPopup;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.OnClick;
import io.realm.RealmList;
public class TaskFormActivity extends BaseActivity implements AdapterView.OnItemSelectedListener {
public static final String TASK_ID_KEY = "taskId";
public static final String USER_ID_KEY = "userId";
public static final String TASK_TYPE_KEY = "type";
public static final String SHOW_TAG_SELECTION = "show_tag_selection";
public static final String ALLOCATION_MODE_KEY = "allocationModeKey";
public static final String SHOW_CHECKLIST = "show_checklist";
public static final String PARCELABLE_TASK = "parcelable_task";
public static final String SAVE_TO_DB = "saveToDb";
// in order to disable the event handler in MainActivity
public static final String SET_IGNORE_FLAG = "ignoreFlag";
@BindView(R.id.task_value_edittext)
EditText taskValue;
@BindView(R.id.task_value_layout)
TextInputLayout taskValueLayout;
@BindView(R.id.task_checklist_wrapper)
LinearLayout checklistWrapper;
@BindView(R.id.task_difficulty_wrapper)
LinearLayout difficultyWrapper;
@BindView(R.id.task_attribute_wrapper)
LinearLayout attributeWrapper;
@BindView(R.id.task_main_wrapper)
LinearLayout mainWrapper;
@BindView(R.id.task_text_edittext)
EmojiEditText taskText;
@BindView(R.id.task_notes_edittext)
EmojiEditText taskNotes;
@BindView(R.id.task_difficulty_spinner)
Spinner taskDifficultySpinner;
@BindView(R.id.task_attribute_spinner)
Spinner taskAttributeSpinner;
@BindView(R.id.btn_delete_task)
Button btnDelete;
@BindView(R.id.task_startdate_layout)
LinearLayout startDateLayout;
@BindView(R.id.task_task_wrapper)
LinearLayout taskWrapper;
@BindView(R.id.task_positive_checkbox)
CheckBox positiveCheckBox;
@BindView(R.id.task_negative_checkbox)
CheckBox negativeCheckBox;
@BindView(R.id.task_actions_wrapper)
LinearLayout actionsLayout;
@BindView(R.id.task_weekdays_wrapper)
LinearLayout weekdayWrapper;
@BindView(R.id.frequency_title)
TextView frequencyTitleTextView;
@BindView(R.id.task_frequency_spinner)
Spinner dailyFrequencySpinner;
@BindView(R.id.task_frequency_container)
LinearLayout frequencyContainer;
@BindView(R.id.checklist_recycler_view)
RecyclerView recyclerView;
@BindView(R.id.new_checklist)
EmojiEditText newCheckListEditText;
@BindView(R.id.add_checklist_button)
Button addChecklistItemButton;
@BindView(R.id.task_reminders_wrapper)
LinearLayout remindersWrapper;
@BindView(R.id.new_reminder_edittext)
EditText newRemindersEditText;
@BindView(R.id.reminders_recycler_view)
RecyclerView remindersRecyclerView;
@BindView(R.id.emoji_toggle_btn0)
ImageButton emojiToggle0;
@BindView(R.id.emoji_toggle_btn1)
ImageButton emojiToggle1;
ImageButton emojiToggle2;
@BindView(R.id.task_duedate_layout)
LinearLayout dueDateLayout;
@BindView(R.id.task_duedate_picker_layout)
LinearLayout dueDatePickerLayout;
@BindView(R.id.duedate_checkbox)
CheckBox dueDateCheckBox;
@BindView(R.id.startdate_text_title)
TextView startDateTitleTextView;
@BindView(R.id.startdate_text_edittext)
EditText startDatePickerText;
@BindView (R.id.repeatables_startdate_text_edittext)
EditText repeatablesStartDatePickerText;
DateEditTextListener startDateListener;
@BindView(R.id.repeatables)
LinearLayout repeatablesLayout;
@BindView(R.id.repeatables_on_title)
TextView reapeatablesOnTextView;
@BindView(R.id.task_repeatables_on_spinner)
Spinner repeatablesOnSpinner;
@BindView(R.id.task_repeatables_every_x_spinner)
NumberPicker repeatablesEveryXSpinner;
@BindView(R.id.task_repeatables_frequency_container)
LinearLayout repeatablesFrequencyContainer;
@BindView(R.id.summary)
TextView summaryTextView;
@BindView(R.id.duedate_text_edittext)
EditText dueDatePickerText;
DateEditTextListener dueDateListener;
@BindView(R.id.task_tags_wrapper)
LinearLayout tagsWrapper;
@BindView(R.id.task_tags_checklist)
LinearLayout tagsContainerLinearLayout;
@BindView(R.id.task_repeatables_frequency_spinner)
Spinner repeatablesFrequencySpinner;
@Inject
TaskFilterHelper taskFilterHelper;
@Inject
TaskRepository taskRepository;
@Inject
TagRepository tagRepository;
@Inject
@Named(AppModule.NAMED_USER_ID)
String userId;
@Inject
RemoteConfigManager remoteConfigManager;
private Task task;
private boolean taskBasedAllocation;
private List<CheckBox> weekdayCheckboxes = new ArrayList<>();
private List<CheckBox> repeatablesWeekDayCheckboxes = new ArrayList<>();
private NumberPicker frequencyPicker;
private List<Tag> tags;
private CheckListAdapter checklistAdapter;
private RemindersAdapter remindersAdapter;
private List<CheckBox> tagCheckBoxList;
private List<Tag> selectedTags;
private RemindersManager remindersManager;
private FirstDayOfTheWeekHelper firstDayOfTheWeekHelper;
private String taskType;
private String taskId;
private EmojiPopup popup;
@Override
protected int getLayoutResId() {
return R.layout.activity_task_form;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
taskType = bundle.getString(TASK_TYPE_KEY);
taskId = bundle.getString(TASK_ID_KEY);
taskBasedAllocation = bundle.getBoolean(ALLOCATION_MODE_KEY);
boolean showTagSelection = bundle.getBoolean(SHOW_TAG_SELECTION, true);
tagCheckBoxList = new ArrayList<>();
tagsWrapper.setVisibility(showTagSelection ? View.VISIBLE : View.GONE);
if(bundle.containsKey(PARCELABLE_TASK)){
task = bundle.getParcelable(PARCELABLE_TASK);
if (task != null) {
taskType = task.type;
}
}
tagCheckBoxList = new ArrayList<>();
selectedTags = new ArrayList<>();
if (taskType == null) {
return;
}
remindersManager = new RemindersManager(taskType);
dueDateListener = new DateEditTextListener(dueDatePickerText);
startDateListener = new DateEditTextListener(startDatePickerText);
btnDelete.setEnabled(false);
ViewHelper.SetBackgroundTint(btnDelete, ContextCompat.getColor(this, R.color.red_10));
btnDelete.setOnClickListener(view -> new AlertDialog.Builder(view.getContext())
.setTitle(getString(R.string.taskform_delete_title))
.setMessage(getString(R.string.taskform_delete_message)).setPositiveButton(getString(R.string.yes), (dialog, which) -> {
if (task != null && task.isValid()) {
taskRepository.deleteTask(task.getId());
}
finish();
dismissKeyboard();
taskRepository.deleteTask(taskId).subscribe(aVoid -> {}, RxErrorHandler.handleEmptyError());
}).setNegativeButton(getString(R.string.no), (dialog, which) -> dialog.dismiss()).show());
ArrayAdapter<CharSequence> difficultyAdapter = ArrayAdapter.createFromResource(this,
R.array.task_difficulties, android.R.layout.simple_spinner_item);
difficultyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
taskDifficultySpinner.setAdapter(difficultyAdapter);
taskDifficultySpinner.setSelection(1);
ArrayAdapter<CharSequence> attributeAdapter = ArrayAdapter.createFromResource(this,
R.array.task_attributes, android.R.layout.simple_spinner_item);
attributeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
taskAttributeSpinner.setAdapter(attributeAdapter);
taskAttributeSpinner.setSelection(0);
if (!taskBasedAllocation) {
attributeWrapper.setVisibility(View.GONE);
}
if (taskType.equals("habit")) {
taskWrapper.removeView(startDateLayout);
mainWrapper.removeView(checklistWrapper);
mainWrapper.removeView(remindersWrapper);
positiveCheckBox.setChecked(true);
negativeCheckBox.setChecked(true);
} else {
mainWrapper.removeView(actionsLayout);
}
if (taskType.equals("daily")) {
ArrayAdapter<CharSequence> frequencyAdapter = ArrayAdapter.createFromResource(this,
R.array.daily_frequencies, android.R.layout.simple_spinner_item);
frequencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.dailyFrequencySpinner.setAdapter(frequencyAdapter);
this.dailyFrequencySpinner.setOnItemSelectedListener(this);
} else {
mainWrapper.removeView(weekdayWrapper);
mainWrapper.removeView(startDateLayout);
}
if (taskType.equals("todo")) {
dueDatePickerLayout.removeView(dueDatePickerText);
//Allows user to decide if they want to add a due date or not
dueDateCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (buttonView.isChecked()) {
dueDatePickerLayout.addView(dueDatePickerText);
} else {
dueDatePickerLayout.removeView(dueDatePickerText);
}
});
} else {
mainWrapper.removeView(dueDateLayout);
}
if (!taskType.equals("reward")) {
taskValueLayout.setVisibility(View.GONE);
} else {
mainWrapper.removeView(checklistWrapper);
mainWrapper.removeView(remindersWrapper);
difficultyWrapper.setVisibility(View.GONE);
attributeWrapper.setVisibility(View.GONE);
}
if (taskType.equals("todo") || taskType.equals("daily")) {
createCheckListRecyclerView();
createRemindersRecyclerView();
}
// Emoji keyboard stuff
boolean isTodo = false;
if (taskType.equals("todo")) {
isTodo = true;
}
// If it's a to-do, change the emojiToggle2 to the actual emojiToggle2 (prevents NPEs when not a to-do task)
if (isTodo) {
emojiToggle2 = (ImageButton) findViewById(R.id.emoji_toggle_btn2);
} else {
emojiToggle2 = emojiToggle0;
}
// if showChecklist is inactive the wrapper is wrapper, so the reference can't be found
if(emojiToggle2 == null) {
emojiToggle2 = emojiToggle0;
}
popup = new EmojiPopup(emojiToggle0.getRootView(), this, ContextCompat.getColor(this, R.color.brand));
popup.setSizeForSoftKeyboard();
popup.setOnDismissListener(() -> changeEmojiKeyboardIcon(false));
popup.setOnSoftKeyboardOpenCloseListener(new EmojiPopup.OnSoftKeyboardOpenCloseListener() {
@Override
public void onKeyboardOpen(int keyBoardHeight) {
}
@Override
public void onKeyboardClose() {
if (popup != null && popup.isShowing()) {
popup.dismiss();
}
}
});
popup.setOnEmojiconClickedListener(emojicon -> {
EmojiEditText emojiEditText = null;
if (getCurrentFocus() == null || !isEmojiEditText(getCurrentFocus()) || emojicon == null) {
return;
} else {
emojiEditText = (EmojiEditText) getCurrentFocus();
}
int start = emojiEditText.getSelectionStart();
int end = emojiEditText.getSelectionEnd();
if (start < 0) {
emojiEditText.append(emojicon.getEmoji());
} else {
emojiEditText.getText().replace(Math.min(start, end),
Math.max(start, end), emojicon.getEmoji(), 0,
emojicon.getEmoji().length());
}
});
popup.setOnEmojiconBackspaceClickedListener(v -> {
if (isEmojiEditText(getCurrentFocus())) {
KeyEvent event = new KeyEvent(
0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
getCurrentFocus().dispatchKeyEvent(event);
}
});
emojiToggle0.setOnClickListener(new emojiClickListener(taskText));
emojiToggle1.setOnClickListener(new emojiClickListener(taskNotes));
if (isTodo) {
emojiToggle2.setOnClickListener(new emojiClickListener(newCheckListEditText));
}
enableRepeatables();
tagRepository.getTags(userId)
.first()
.subscribe(loadedTags -> {
tags = loadedTags;
createTagsCheckBoxes();
}, RxErrorHandler.handleEmptyError()
);
if (taskId != null) {
taskRepository.getTask(taskId)
.first()
.subscribe(task -> {
this.task = task;
if (task != null) {
populate(task);
setTitle(task);
if (taskType.equals("todo") || taskType.equals("daily")) {
populateChecklistRecyclerView();
populateRemindersRecyclerView();
}
}
setTitle(task);
}, RxErrorHandler.handleEmptyError());
btnDelete.setEnabled(true);
} else {
setTitle((Task) null);
taskText.requestFocus();
}
}
@Override
protected void onDestroy() {
tagRepository.close();
super.onDestroy();
}
@Override
protected void injectActivity(AppComponent component) {
component.inject(this);
}
public void hideMonthOptions () {
ViewGroup.LayoutParams repeatablesOnSpinnerParams = repeatablesOnSpinner.getLayoutParams();
repeatablesOnSpinnerParams.height = 0;
repeatablesOnSpinner.setLayoutParams(repeatablesOnSpinnerParams);
ViewGroup.LayoutParams repeatablesOnTitleParams = reapeatablesOnTextView.getLayoutParams();
repeatablesOnTitleParams.height = 0;
reapeatablesOnTextView.setLayoutParams(repeatablesOnTitleParams);
}
public void hideWeekOptions () {
ViewGroup.LayoutParams repeatablesFrequencyContainerParams = repeatablesFrequencyContainer.getLayoutParams();
repeatablesFrequencyContainerParams.height = 0;
repeatablesFrequencyContainer.setLayoutParams(repeatablesFrequencyContainerParams);
}
// @TODO: abstract business logic to Presenter and only modify view?
private void enableRepeatables()
{
if (!remoteConfigManager.repeatablesAreEnabled() || !taskType.equals("daily")){
repeatablesLayout.setVisibility(View.INVISIBLE);
ViewGroup.LayoutParams repeatablesLayoutParams = repeatablesLayout.getLayoutParams();
repeatablesLayoutParams.height = 0;
repeatablesLayout.setLayoutParams(repeatablesLayoutParams);
return;
};
startDateLayout.setVisibility(View.INVISIBLE);
// Hide old stuff
ViewGroup.LayoutParams startDateLayoutParams = startDateLayout.getLayoutParams();
startDateLayoutParams.height = 0;
startDateLayout.setLayoutParams(startDateLayoutParams);
ViewGroup.LayoutParams startDatePickerTextParams = startDatePickerText.getLayoutParams();
startDatePickerTextParams.height = 0;
startDatePickerText.setLayoutParams(startDatePickerTextParams);
ViewGroup.LayoutParams startDateTitleTextViewParams = startDateTitleTextView.getLayoutParams();
startDateTitleTextViewParams.height = 0;
startDateTitleTextView.setLayoutParams(startDateTitleTextViewParams);
weekdayWrapper.setVisibility(View.INVISIBLE);
ViewGroup.LayoutParams weekdayWrapperParams = weekdayWrapper.getLayoutParams();
weekdayWrapperParams.height = 0;
weekdayWrapper.setLayoutParams(weekdayWrapperParams);
ViewGroup.LayoutParams frequencyTitleTextViewParams = frequencyTitleTextView.getLayoutParams();
frequencyTitleTextViewParams.height = 0;
frequencyTitleTextView.setLayoutParams(frequencyTitleTextViewParams);
ViewGroup.LayoutParams dailyFrequencySpinnerParams = dailyFrequencySpinner.getLayoutParams();
dailyFrequencySpinnerParams.height = 0;
dailyFrequencySpinner.setLayoutParams(dailyFrequencySpinnerParams);
// Start Date
startDateListener = new DateEditTextListener(repeatablesStartDatePickerText);
// Frequency
ArrayAdapter<CharSequence> frequencyAdapter = ArrayAdapter.createFromResource(this,
R.array.repeatables_frequencies, android.R.layout.simple_spinner_item);
frequencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.repeatablesFrequencySpinner.setAdapter(frequencyAdapter);
this.repeatablesFrequencySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
generateSummary();
Resources r = getResources();
// @TODO: remove magic numbers
if (position == 2) {
hideWeekOptions();
ViewGroup.LayoutParams repeatablesOnSpinnerParams = repeatablesOnSpinner.getLayoutParams();
repeatablesOnSpinnerParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, r.getDisplayMetrics());
repeatablesOnSpinner.setLayoutParams(repeatablesOnSpinnerParams);
ViewGroup.LayoutParams repeatablesOnTitleParams = reapeatablesOnTextView.getLayoutParams();
repeatablesOnTitleParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, r.getDisplayMetrics());
reapeatablesOnTextView.setLayoutParams(repeatablesOnTitleParams);
}else if (position == 1) {
hideMonthOptions();
ViewGroup.LayoutParams repeatablesFrequencyContainerParams = repeatablesFrequencyContainer.getLayoutParams();
repeatablesFrequencyContainerParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 220, r.getDisplayMetrics());
repeatablesFrequencyContainer.setLayoutParams(repeatablesFrequencyContainerParams);
} else {
hideWeekOptions();
hideMonthOptions();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Repeat On
ArrayAdapter<CharSequence> repeatablesOnAdapter = ArrayAdapter.createFromResource(this,
R.array.repeatables_on, android.R.layout.simple_spinner_item);
repeatablesOnAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.repeatablesOnSpinner.setAdapter(repeatablesOnAdapter);
this.repeatablesOnSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
generateSummary();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Every X
setEveryXSpinner(repeatablesEveryXSpinner);
repeatablesEveryXSpinner.setOnValueChangedListener((picker, oldVal, newVal) -> generateSummary());
// WeekDays
this.repeatablesFrequencyContainer.removeAllViews();
String[] weekdays = getResources().getStringArray(R.array.weekdays);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String dayOfTheWeek = sharedPreferences.getString("FirstDayOfTheWeek",
Integer.toString(Calendar.getInstance().getFirstDayOfWeek()));
firstDayOfTheWeekHelper =
FirstDayOfTheWeekHelper.newInstance(Integer.parseInt(dayOfTheWeek));
ArrayList<String> weekdaysTemp = new ArrayList<>(Arrays.asList(weekdays));
Collections.rotate(weekdaysTemp, firstDayOfTheWeekHelper.getDailyTaskFormOffset());
weekdays = weekdaysTemp.toArray(new String[1]);
for (int i = 0; i < 7; i++) {
View weekdayRow = getLayoutInflater().inflate(R.layout.row_checklist, this.repeatablesFrequencyContainer, false);
CheckBox checkbox = (CheckBox) weekdayRow.findViewById(R.id.checkbox);
checkbox.setText(weekdays[i]);
checkbox.setChecked(true);
checkbox.setOnClickListener(v -> generateSummary());
repeatablesWeekDayCheckboxes.add(checkbox);
repeatablesFrequencyContainer.addView(weekdayRow);
}
generateSummary();
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
}
private void generateSummary () {
String frequency = repeatablesFrequencySpinner.getSelectedItem().toString();
String everyX = String.valueOf(repeatablesEveryXSpinner.getValue());
String frequencyQualifier = "";
switch (frequency) {
case "Daily":
frequencyQualifier = "day(s)";
break;
case "Weekly":
frequencyQualifier = "week(s)";
break;
case "Monthly":
frequencyQualifier = "month(s)";
break;
case "Yearly":
frequencyQualifier = "year(s)";
break;
}
String weekdays;
List<String> weekdayStrings = new ArrayList<>();
int offset = firstDayOfTheWeekHelper.getDailyTaskFormOffset();
if (this.repeatablesWeekDayCheckboxes.get(offset).isChecked()) {
weekdayStrings.add("Monday");
}
if (this.repeatablesWeekDayCheckboxes.get((offset + 1) % 7).isChecked()) {
weekdayStrings.add("Tuesday");
}
if (this.repeatablesWeekDayCheckboxes.get((offset + 2) % 7).isChecked()) {
weekdayStrings.add("Wednesday");
}
if (this.repeatablesWeekDayCheckboxes.get((offset + 3) % 7).isChecked()) {
weekdayStrings.add("Thursday");
}
if (this.repeatablesWeekDayCheckboxes.get((offset + 4) % 7).isChecked()) {
weekdayStrings.add("Friday");
}
if (this.repeatablesWeekDayCheckboxes.get((offset + 5) % 7).isChecked()) {
weekdayStrings.add("Saturday");
}
if (this.repeatablesWeekDayCheckboxes.get((offset + 6) % 7).isChecked()) {
weekdayStrings.add("Sunday");
}
weekdays = " on " + TextUtils.join(", ", weekdayStrings);
if (!frequency.equals("Weekly")) {
weekdays = "";
}
if (frequency.equals("Monthly")) {
weekdays = "";
Calendar calendar = startDateListener.getCalendar();
String monthlyFreq = repeatablesOnSpinner.getSelectedItem().toString();
if (monthlyFreq.equals("Day of Month")) {
Integer date = calendar.get(Calendar.DATE);
weekdays = " on the " + date.toString();
} else {
Integer week = calendar.get(Calendar.WEEK_OF_MONTH);
String dayLongName = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
weekdays = " on the " + week.toString() + " week on " + dayLongName;
}
}
String summary = getResources().getString(R.string.repeat_summary, frequency, everyX, frequencyQualifier, weekdays);
summaryTextView.setText(summary);
}
private void populateRepeatables(Task task) {
// Frequency
int frequencySelection = 0;
if (task.getFrequency().equals("weekly")) {
frequencySelection = 1;
} else if (task.getFrequency().equals("monthly")) {
frequencySelection = 2;
} else if (task.getFrequency().equals("yearly")) {
frequencySelection = 3;
}
this.repeatablesFrequencySpinner.setSelection(frequencySelection);
// Every X
this.repeatablesEveryXSpinner.setValue(task.getEveryX());
// Weekdays
if (task.getFrequency().equals("weekly")) {
if (repeatablesWeekDayCheckboxes.size() == 7) {
int offset = firstDayOfTheWeekHelper.getDailyTaskFormOffset();
this.repeatablesWeekDayCheckboxes.get(offset).setChecked(this.task.getRepeat().getM());
this.repeatablesWeekDayCheckboxes.get((offset + 1) % 7).setChecked(this.task.getRepeat().getT());
this.repeatablesWeekDayCheckboxes.get((offset + 2) % 7).setChecked(this.task.getRepeat().getW());
this.repeatablesWeekDayCheckboxes.get((offset + 3) % 7).setChecked(this.task.getRepeat().getTh());
this.repeatablesWeekDayCheckboxes.get((offset + 4) % 7).setChecked(this.task.getRepeat().getF());
this.repeatablesWeekDayCheckboxes.get((offset + 5) % 7).setChecked(this.task.getRepeat().getS());
this.repeatablesWeekDayCheckboxes.get((offset + 6) % 7).setChecked(this.task.getRepeat().getSu());
}
}
// Repeats On
if (task.getDaysOfMonth() != null && task.getDaysOfMonth().size() > 0) {
this.repeatablesOnSpinner.setSelection(0);
} else if (task.getWeeksOfMonth() != null && task.getWeeksOfMonth().size() > 0) {
this.repeatablesOnSpinner.setSelection(1);
}
}
private void setEveryXSpinner(NumberPicker frequencyPicker) {
// View dayRow = getLayoutInflater().inflate(R.layout.row_number_picker, this.frequencyContainer, false);
// frequencyPicker = (NumberPicker) dayRow.findViewById(R.id.numberPicker);
frequencyPicker.setMinValue(1);
frequencyPicker.setMaxValue(366);
// TextView tv = (TextView) dayRow.findViewById(R.id.label);
// tv.setText(getResources().getString(R.string.frequency_daily));
// this.frequencyContainer.addView(dayRow);
}
private boolean isEmojiEditText(@Nullable View view) {
return view instanceof EmojiEditText;
}
private void changeEmojiKeyboardIcon(Boolean keyboardOpened) {
if (keyboardOpened) {
emojiToggle0.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_keyboard_grey600_24dp));
emojiToggle1.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_keyboard_grey600_24dp));
emojiToggle2.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_keyboard_grey600_24dp));
} else {
emojiToggle0.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_emoticon_grey600_24dp));
emojiToggle1.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_emoticon_grey600_24dp));
emojiToggle2.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_emoticon_grey600_24dp));
}
}
private void createCheckListRecyclerView() {
checklistAdapter = new CheckListAdapter();
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(checklistAdapter);
recyclerView.setLayoutManager(new WrapContentRecyclerViewLayoutManager(this));
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(checklistAdapter);
ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(recyclerView);
}
private void populateChecklistRecyclerView() {
List<ChecklistItem> checklistItems = new ArrayList<>();
if (task != null && task.getChecklist() != null) {
checklistItems = taskRepository.getUnmanagedCopy(task.getChecklist());
}
checklistAdapter.setItems(checklistItems);
}
@OnClick(R.id.add_checklist_button)
public void addChecklistItem() {
String text = newCheckListEditText.getText().toString();
ChecklistItem item = new ChecklistItem(text);
checklistAdapter.addItem(item);
newCheckListEditText.setText("");
}
private void createRemindersRecyclerView() {
remindersAdapter = new RemindersAdapter(taskType);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
remindersRecyclerView.setLayoutManager(llm);
remindersRecyclerView.setAdapter(remindersAdapter);
remindersRecyclerView.setLayoutManager(new WrapContentRecyclerViewLayoutManager(this));
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(remindersAdapter);
ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(remindersRecyclerView);
}
private void populateRemindersRecyclerView() {
List<RemindersItem> reminders = new ArrayList<>();
if (task != null && task.getReminders() != null) {
reminders = taskRepository.getUnmanagedCopy(task.getReminders());
}
remindersAdapter.setReminders(reminders);
}
private void addNewReminder(RemindersItem remindersItem) {
remindersAdapter.addItem(remindersItem);
}
@OnClick(R.id.new_reminder_edittext)
public void selectNewReminderTime() {
remindersManager.createReminderTimeDialog(this::addNewReminder, taskType, this, null);
}
private void createTagsCheckBoxes() {
int position = 0;
this.tagsContainerLinearLayout.removeAllViews();
for (Tag tag : tags) {
TableRow row = (TableRow) getLayoutInflater().inflate(R.layout.row_checklist, this.tagsContainerLinearLayout, false);
CheckBox checkbox = (CheckBox) row.findViewById(R.id.checkbox);
row.setId(position);
checkbox.setText(tag.getName()); // set text Name
checkbox.setId(position);
//This is to check if the tag was selected by the user. Similar to onClickListener
checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (buttonView.isChecked()) {
if (!selectedTags.contains(tag)) {
selectedTags.add(tag);
}
} else {
if (selectedTags.contains(tag)) {
selectedTags.remove(tag);
}
}
});
checkbox.setChecked(taskFilterHelper.isTagChecked(tag.getId()));
tagsContainerLinearLayout.addView(row);
tagCheckBoxList.add(checkbox);
position++;
}
if (task != null) {
fillTagCheckboxes();
}
}
private void setTitle(@Nullable Task task) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
String title = "";
if (task != null && task.isValid()) {
title = getResources().getString(R.string.action_edit) + " " + task.getText();
} else {
switch (taskType) {
case "todo":
title = getResources().getString(R.string.new_todo);
break;
case "daily":
title = getResources().getString(R.string.new_daily);
break;
case "habit":
title = getResources().getString(R.string.new_habit);
break;
case "reward":
title = getResources().getString(R.string.new_reward);
break;
}
}
actionBar.setTitle(title);
}
}
private void setDailyFrequencyViews() {
this.frequencyContainer.removeAllViews();
if (this.dailyFrequencySpinner.getSelectedItemPosition() == 0) {
String[] weekdays = getResources().getStringArray(R.array.weekdays);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String dayOfTheWeek = sharedPreferences.getString("FirstDayOfTheWeek",
Integer.toString(Calendar.getInstance().getFirstDayOfWeek()));
firstDayOfTheWeekHelper =
FirstDayOfTheWeekHelper.newInstance(Integer.parseInt(dayOfTheWeek));
ArrayList<String> weekdaysTemp = new ArrayList<>(Arrays.asList(weekdays));
Collections.rotate(weekdaysTemp, firstDayOfTheWeekHelper.getDailyTaskFormOffset());
weekdays = weekdaysTemp.toArray(new String[1]);
for (int i = 0; i < 7; i++) {
View weekdayRow = getLayoutInflater().inflate(R.layout.row_checklist, this.frequencyContainer, false);
CheckBox checkbox = (CheckBox) weekdayRow.findViewById(R.id.checkbox);
checkbox.setText(weekdays[i]);
checkbox.setChecked(true);
this.weekdayCheckboxes.add(checkbox);
this.frequencyContainer.addView(weekdayRow);
}
} else {
View dayRow = getLayoutInflater().inflate(R.layout.row_number_picker, this.frequencyContainer, false);
this.frequencyPicker = (NumberPicker) dayRow.findViewById(R.id.numberPicker);
this.frequencyPicker.setMinValue(1);
this.frequencyPicker.setMaxValue(366);
TextView tv = (TextView) dayRow.findViewById(R.id.label);
tv.setText(getResources().getString(R.string.frequency_daily));
this.frequencyContainer.addView(dayRow);
}
if (this.task != null && this.task.isValid()) {
if (this.dailyFrequencySpinner.getSelectedItemPosition() == 0) {
int offset = firstDayOfTheWeekHelper.getDailyTaskFormOffset();
this.weekdayCheckboxes.get(offset).setChecked(this.task.getRepeat().getM());
this.weekdayCheckboxes.get((offset + 1) % 7).setChecked(this.task.getRepeat().getT());
this.weekdayCheckboxes.get((offset + 2) % 7).setChecked(this.task.getRepeat().getW());
this.weekdayCheckboxes.get((offset + 3) % 7).setChecked(this.task.getRepeat().getTh());
this.weekdayCheckboxes.get((offset + 4) % 7).setChecked(this.task.getRepeat().getF());
this.weekdayCheckboxes.get((offset + 5) % 7).setChecked(this.task.getRepeat().getS());
this.weekdayCheckboxes.get((offset + 6) % 7).setChecked(this.task.getRepeat().getSu());
} else {
this.frequencyPicker.setValue(this.task.getEveryX());
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_save, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_save_changes) {
finishActivitySuccessfully();
return true;
}
return super.onOptionsItemSelected(item);
}
private void populate(Task task) {
if (!task.isValid()) {
return;
}
taskText.setText(task.text);
taskNotes.setText(task.notes);
taskValue.setText(String.format(Locale.getDefault(), "%.2f", task.value));
for (Tag tag : task.getTags()) {
selectedTags.add(tag);
}
if (tags != null) {
fillTagCheckboxes();
}
float priority = task.getPriority();
if (Math.abs(priority - 0.1) < 0.000001) {
this.taskDifficultySpinner.setSelection(0);
} else if (Math.abs(priority - 1.0) < 0.000001) {
this.taskDifficultySpinner.setSelection(1);
} else if (Math.abs(priority - 1.5) < 0.000001) {
this.taskDifficultySpinner.setSelection(2);
} else if (Math.abs(priority - 2.0) < 0.000001) {
this.taskDifficultySpinner.setSelection(3);
}
String attribute = task.getAttribute();
if (attribute != null) {
switch (attribute) {
case Stats.STRENGTH:
taskAttributeSpinner.setSelection(0);
break;
case Stats.INTELLIGENCE:
taskAttributeSpinner.setSelection(1);
break;
case Stats.CONSTITUTION:
taskAttributeSpinner.setSelection(2);
break;
case Stats.PERCEPTION:
taskAttributeSpinner.setSelection(3);
break;
}
}
if (task.type.equals("habit")) {
positiveCheckBox.setChecked(task.getUp());
negativeCheckBox.setChecked(task.getDown());
}
if (task.type.equals("daily")) {
if (task.getStartDate() != null) {
startDateListener.setCalendar(task.getStartDate());
}
if (task.getFrequency().equals("weekly")) {
this.dailyFrequencySpinner.setSelection(0);
if (weekdayCheckboxes.size() == 7) {
int offset = firstDayOfTheWeekHelper.getDailyTaskFormOffset();
this.weekdayCheckboxes.get(offset).setChecked(this.task.getRepeat().getM());
this.weekdayCheckboxes.get((offset + 1) % 7).setChecked(this.task.getRepeat().getT());
this.weekdayCheckboxes.get((offset + 2) % 7).setChecked(this.task.getRepeat().getW());
this.weekdayCheckboxes.get((offset + 3) % 7).setChecked(this.task.getRepeat().getTh());
this.weekdayCheckboxes.get((offset + 4) % 7).setChecked(this.task.getRepeat().getF());
this.weekdayCheckboxes.get((offset + 5) % 7).setChecked(this.task.getRepeat().getS());
this.weekdayCheckboxes.get((offset + 6) % 7).setChecked(this.task.getRepeat().getSu());
}
} else {
this.dailyFrequencySpinner.setSelection(1);
if (this.frequencyPicker != null) {
this.frequencyPicker.setValue(task.getEveryX());
}
}
populateRepeatables(task);
}
if (task.type.equals("todo")) {
if (task.getDueDate() != null) {
dueDateCheckBox.setChecked(true);
dueDateListener.setCalendar(task.getDueDate());
}
}
if (task.isGroupTask()) {
new AlertDialog.Builder(this)
.setTitle(R.string.group_tasks_edit_title)
.setMessage(R.string.group_tasks_edit_description)
.setPositiveButton(android.R.string.ok, (dialog, which) -> finish())
.show();
}
}
private void fillTagCheckboxes() {
for (Tag tag : task.getTags()) {
int position = tags.indexOf(tag);
if (tagCheckBoxList.size() > position && position >= 0) {
tagCheckBoxList.get(position).setChecked(true);
}
}
}
private boolean saveTask(Task task) {
String text = MarkdownParser.parseCompiled(taskText.getText());
if (text == null || text.isEmpty()) {
return false;
}
if (!task.isValid()) {
return true;
}
taskRepository.executeTransaction(realm -> {
try {
task.text = text;
task.notes = MarkdownParser.parseCompiled(taskNotes.getText());
} catch (IllegalArgumentException ignored) {
}
if (checklistAdapter != null) {
if (checklistAdapter.getCheckListItems() != null) {
RealmList<ChecklistItem> newChecklist = new RealmList<>();
newChecklist.addAll(realm.copyToRealmOrUpdate(checklistAdapter.getCheckListItems()));
task.setChecklist(newChecklist);
}
}
if (remindersAdapter != null) {
if (remindersAdapter.getRemindersItems() != null) {
RealmList<RemindersItem> newReminders = new RealmList<>();
newReminders.addAll(realm.copyToRealmOrUpdate(remindersAdapter.getRemindersItems()));
task.setReminders(newReminders);
}
}
RealmList<Tag> taskTags = new RealmList<>();
taskTags.addAll(selectedTags);
task.setTags(taskTags);
if (taskDifficultySpinner.getSelectedItemPosition() == 0) {
task.setPriority((float) 0.1);
} else if (taskDifficultySpinner.getSelectedItemPosition() == 1) {
task.setPriority((float) 1.0);
} else if (taskDifficultySpinner.getSelectedItemPosition() == 2) {
task.setPriority((float) 1.5);
} else if (taskDifficultySpinner.getSelectedItemPosition() == 3) {
task.setPriority((float) 2.0);
}
if (!taskBasedAllocation) {
task.setAttribute(Stats.STRENGTH);
} else {
switch (taskAttributeSpinner.getSelectedItemPosition()) {
case 0:
task.setAttribute(Stats.STRENGTH);
break;
case 1:
task.setAttribute(Stats.INTELLIGENCE);
break;
case 2:
task.setAttribute(Stats.CONSTITUTION);
break;
case 3:
task.setAttribute(Stats.PERCEPTION);
break;
}
}
switch (task.type != null ? task.type : "") {
case "habit": {
task.setUp(positiveCheckBox.isChecked());
task.setDown(negativeCheckBox.isChecked());
}
break;
case "daily": {
task.setStartDate(new Date(startDateListener.getCalendar().getTimeInMillis()));
if (this.dailyFrequencySpinner.getSelectedItemPosition() == 0) {
task.setFrequency("weekly");
Days repeat = task.getRepeat();
if (repeat == null) {
repeat = new Days();
task.setRepeat(repeat);
}
int offset = firstDayOfTheWeekHelper.getDailyTaskFormOffset();
repeat.setM(this.weekdayCheckboxes.get(offset).isChecked());
repeat.setT(this.weekdayCheckboxes.get((offset + 1) % 7).isChecked());
repeat.setW(this.weekdayCheckboxes.get((offset + 2) % 7).isChecked());
repeat.setTh(this.weekdayCheckboxes.get((offset + 3) % 7).isChecked());
repeat.setF(this.weekdayCheckboxes.get((offset + 4) % 7).isChecked());
repeat.setS(this.weekdayCheckboxes.get((offset + 5) % 7).isChecked());
repeat.setSu(this.weekdayCheckboxes.get((offset + 6) % 7).isChecked());
} else {
task.setFrequency("daily");
task.setEveryX(this.frequencyPicker.getValue());
}
if (remoteConfigManager.repeatablesAreEnabled()) {
int frequency = this.repeatablesFrequencySpinner.getSelectedItemPosition();
String frequencyString = "";
switch (frequency) {
case 0:
frequencyString = "daily";
break;
case 1:
frequencyString = "weekly";
break;
case 2:
frequencyString = "monthly";
break;
case 3:
frequencyString = "yearly";
break;
}
task.setFrequency(frequencyString);
task.setEveryX(this.repeatablesEveryXSpinner.getValue());
Days repeat = task.getRepeat();
if (repeat == null) {
repeat = new Days();
task.setRepeat(repeat);
}
if ("weekly".equals(frequencyString)) {
int offset = firstDayOfTheWeekHelper.getDailyTaskFormOffset();
repeat.setM(this.repeatablesWeekDayCheckboxes.get(offset).isChecked());
repeat.setT(this.repeatablesWeekDayCheckboxes.get((offset + 1) % 7).isChecked());
repeat.setW(this.repeatablesWeekDayCheckboxes.get((offset + 2) % 7).isChecked());
repeat.setTh(this.repeatablesWeekDayCheckboxes.get((offset + 3) % 7).isChecked());
repeat.setF(this.repeatablesWeekDayCheckboxes.get((offset + 4) % 7).isChecked());
repeat.setS(this.repeatablesWeekDayCheckboxes.get((offset + 5) % 7).isChecked());
repeat.setSu(this.repeatablesWeekDayCheckboxes.get((offset + 6) % 7).isChecked());
}
if ("monthly".equals(frequencyString)) {
Calendar calendar = startDateListener.getCalendar();
String monthlyFreq = repeatablesOnSpinner.getSelectedItem().toString();
if (monthlyFreq.equals("Day of Month")) {
Integer date = calendar.get(Calendar.DATE);
List<Integer> daysOfMonth = new ArrayList<>();
daysOfMonth.add(date);
task.setDaysOfMonth(daysOfMonth);
task.setWeeksOfMonth(new ArrayList<>());
} else {
Integer week = calendar.get(Calendar.WEEK_OF_MONTH);
List<Integer> weeksOfMonth = new ArrayList<>();
weeksOfMonth.add(week);
task.setWeeksOfMonth(weeksOfMonth);
task.setDaysOfMonth(new ArrayList<>());
}
}
}
}
break;
case "todo": {
if (dueDateCheckBox.isChecked()) {
task.setDueDate(new Date(dueDateListener.getCalendar().getTimeInMillis()));
} else {
task.setDueDate(null);
}
}
break;
case "reward": {
String value = taskValue.getText().toString();
if (!value.isEmpty()) {
NumberFormat localFormat = DecimalFormat.getInstance(Locale.getDefault());
try {
task.setValue(localFormat.parse(value).doubleValue());
} catch (ParseException ignored) {
}
} else {
task.setValue(0.0d);
}
}
break;
}
});
return true;
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
this.setDailyFrequencyViews();
}
public void onNothingSelected(AdapterView<?> parent) {
this.setDailyFrequencyViews();
}
private void prepareSave() {
if (this.task == null) {
this.task = new Task();
this.task.setType(taskType);
}
if (this.saveTask(this.task) && task.isValid()) {
//send back to other elements.
if (TaskFormActivity.this.task.getId() == null) {
taskRepository.createTaskInBackground(task);
} else {
taskRepository.updateTaskInBackground(task);
}
}
}
@Override
public boolean onSupportNavigateUp() {
finish();
dismissKeyboard();
return true;
}
@Override
public void onBackPressed() {
finish();
dismissKeyboard();
}
private void finishActivitySuccessfully() {
this.prepareSave();
finishWithSuccess();
dismissKeyboard();
}
private void finishWithSuccess() {
Handler mainHandler = new Handler(this.getMainLooper());
mainHandler.postDelayed(() -> {
Intent resultIntent = new Intent();
resultIntent.putExtra(TaskFormActivity.TASK_TYPE_KEY, taskType);
setResult(RESULT_OK, resultIntent);
finish();
}, 500);
}
private void dismissKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View currentFocus = getCurrentFocus();
if (currentFocus != null) {
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
if (popup != null) {
popup.dismiss();
popup = null;
}
}
private class DateEditTextListener implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
Calendar calendar;
DatePickerDialog datePickerDialog;
EditText datePickerText;
DateFormat dateFormatter;
DateEditTextListener(EditText dateText) {
calendar = Calendar.getInstance();
this.datePickerText = dateText;
this.datePickerText.setOnClickListener(this);
this.dateFormatter = DateFormat.getDateInstance();
this.datePickerDialog = new DatePickerDialog(datePickerText.getContext(), this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String dayOfTheWeek = sharedPreferences.getString("FirstDayOfTheWeek",
Integer.toString(Calendar.getInstance().getFirstDayOfWeek()));
FirstDayOfTheWeekHelper firstDayOfTheWeekHelper =
FirstDayOfTheWeekHelper.newInstance(Integer.parseInt(dayOfTheWeek));
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH) {
datePickerDialog.getDatePicker().getCalendarView().setFirstDayOfWeek(
firstDayOfTheWeekHelper.getFirstDayOfTheWeek());
} else {
datePickerDialog.getDatePicker().setFirstDayOfWeek(firstDayOfTheWeekHelper
.getFirstDayOfTheWeek());
}
this.datePickerDialog.setButton(DialogInterface.BUTTON_NEUTRAL, getResources().getString(R.string.today), (dialog, which) -> {
setCalendar(Calendar.getInstance().getTime());
});
updateDateText();
}
public void onClick(View view) {
datePickerDialog.show();
}
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(year, monthOfYear, dayOfMonth);
updateDateText();
}
public Calendar getCalendar() {
return (Calendar) calendar.clone();
}
public void setCalendar(Date date) {
calendar.setTime(date);
datePickerDialog.updateDate(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
updateDateText();
}
private void updateDateText() {
datePickerText.setText(dateFormatter.format(calendar.getTime()));
}
}
private class emojiClickListener implements View.OnClickListener {
EmojiEditText view;
emojiClickListener(EmojiEditText view) {
this.view = view;
}
@Override
public void onClick(View v) {
if (!popup.isShowing()) {
if (popup.isKeyBoardOpen()) {
popup.showAtBottom();
changeEmojiKeyboardIcon(true);
} else {
view.setFocusableInTouchMode(true);
view.requestFocus();
popup.showAtBottomPending();
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
changeEmojiKeyboardIcon(true);
}
} else {
popup.dismiss();
changeEmojiKeyboardIcon(false);
}
}
}
}
| gpl-3.0 |
thunder033/RMWA | pulsar/app/shared/index.js | 363 | /**
* Created by Greg on 11/27/2016.
*/
'use strict';
/**
* Misc. shared utilities
* @module shared
*/
var shared = require('angular').module('shared', []);
require('./capitalize.filter');
require('./es6-warning-banner.directive');
require('./loader.directive');
require('./secondsToDate.filter');
require('./accordion.directive');
module.exports = shared; | gpl-3.0 |
ranog/coursera_python | n_impares.py | 179 | #!/usr/bin/env python3
n = int(input("Digite o valor de n: "))
i = 0 #contador
impar = 1
while(i < n):
print(impar)
impar = impar + 2
i = i + 1
| gpl-3.0 |
jegoyalu/jariscms | modules/calendar/functions.php | 19748 | <?php
/**
* Copyright 2008, Jefferson González (JegoYalu.com)
* This file is part of Jaris CMS and licensed under the GPL,
* check the LICENSE.txt file for version and details or visit
* https://opensource.org/licenses/GPL-3.0.
*
* Jaris CMS module functions file.
*/
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\System::SIGNAL_GENERATE_ADMIN_PAGE,
function (&$sections) {
if (
Jaris\Authentication::groupHasPermission(
"add_blocks",
Jaris\Authentication::currentUserGroup()
)
) {
$content = [
"title" => t("Add Calendar Block"),
"url" => Jaris\Uri::url(
"admin/blocks/add",
["calendar_block" => 1]
),
"description" => t("Create blocks to display events of a particular calendar page.")
];
}
if (isset($content)) {
foreach ($sections as $section_index => $section_data) {
if ($section_data["class"] == "blocks") {
$sections[$section_index]["sub_sections"][] = $content;
break;
}
}
}
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\System::SIGNAL_ADD_EDIT_TAB,
function (&$uri, &$page_data, &$is_page_owner) {
if ($page_data["type"] == "calendar") {
if (calendar_event_can_add(Jaris\Uri::get(), $page_data)) {
Jaris\View::addTab(
t("Add Event"),
Jaris\Modules::getPageUri(
"admin/calendar/events/add",
"calendar"
),
["uri"=>$uri]
);
Jaris\View::addTab(
t("Manage Events"),
Jaris\Modules::getPageUri(
"admin/calendar/events",
"calendar"
),
["uri"=>$uri]
);
}
}
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\Forms::SIGNAL_GENERATE_FORM,
function (&$parameters, &$fieldsets) {
if (
Jaris\Uri::get() == "admin/pages/add" &&
$parameters["name"] == "add-page-calendar"
) {
$fieldset = [];
$field_style[] = [
"type" => "select",
"label" => t("Calendar Style:"),
"name" => "calendar_style",
"value" => [
t("Traditional") => "traditional",
t("Consecutive") => "consecutive"
],
"selected" => empty($_REQUEST["calendar_style"]) ?
"traditional" : $_REQUEST["calendar_style"],
"description" => t("Select the default style used to display the calendar events.")
];
$fieldset[] = [
"fields" => $field_style
];
$fieldset[] = [
"fields" => Jaris\Groups::generateFields(
null,
"groups_add_event",
["administrator", "guest"],
true
),
"name" => t("Groups"),
"description" => t("The groups that can publish events to this calendar."),
"collapsible" => true,
"collapsed" => false
];
$approval = [
t("Enable") => true,
t("Disable") => false
];
$field_approval[] = [
"type" => "radio",
"name" => "add_event_approval",
"value" => $approval,
"checked" => $_REQUEST["add_event_approval"]
];
$fieldset[] = [
"fields" => $field_approval,
"name" => t("Require Approval"),
"description" => t("Enable if adding events require approval."),
"collapsible" => true,
"collapsed" => false
];
Jaris\Forms::addFieldsets(
$fieldset,
"Meta tags",
$fieldsets,
true
);
} elseif (
Jaris\Uri::get() == "admin/pages/edit" &&
$parameters["name"] == "edit-page-calendar"
) {
$page_data = Jaris\Pages::get($_REQUEST["uri"]);
$page_data["groups_add_event"] = unserialize(
$page_data["groups_add_event"]
);
$url_add = Jaris\Uri::url(
Jaris\Modules::getPageUri(
"admin/calendar/events/add",
"calendar"
),
["uri"=>$_REQUEST["uri"]]
);
$url_edit = Jaris\Uri::url(
Jaris\Modules::getPageUri(
"admin/calendar/events",
"calendar"
),
["uri"=>$_REQUEST["uri"]]
);
$html = '<div id="calendar-buttons">';
$html .= '<a href="'.$url_add.'">'.t("Add Event").'</a> | ';
$html .= '<a href="'.$url_edit.'">'.t("View Events").'</a>';
$html .= '<hr />';
$html .= '</div>';
$field = ["type"=>"other", "html_code"=>$html];
Jaris\Forms::addFieldBefore($field, "title", $fieldsets);
$fieldset = [];
$field_style[] = [
"type" => "select",
"label" => t("Calendar Style:"),
"name" => "calendar_style",
"value" => [
t("Traditional") => "traditional",
t("Consecutive") => "consecutive"
],
"selected" => empty($page_data["calendar_style"]) ?
"traditional" : $page_data["calendar_style"],
"description" => t("Select the default style used to display the calendar events.")
];
$fieldset[] = [
"fields" => $field_style
];
$fieldset[] = [
"fields" => Jaris\Groups::generateFields(
$page_data["groups_add_event"],
"groups_add_event",
["administrator", "guest"],
true
),
"name" => t("Groups"),
"description" => t("The groups that can publish events to this calendar."),
"collapsible" => true,
"collapsed" => false
];
$approval = [
t("Enable") => true,
t("Disable") => false
];
$field_approval[] = [
"type" => "radio",
"name" => "add_event_approval",
"value" => $approval,
"checked" => $page_data["add_event_approval"]
];
$fieldset[] = [
"fields" => $field_approval,
"name" => t("Require Approval"),
"description" => t("Enable if adding events require approval."),
"collapsible" => true,
"collapsed" => false
];
Jaris\Forms::addFieldsets(
$fieldset,
"Meta tags",
$fieldsets,
true
);
} elseif (Jaris\Uri::get() == "admin/blocks/add") {
if (isset($_REQUEST["calendar_block"])) {
$fields[] = [
"type" => "hidden",
"name" => "calendar_block",
"value" => 1
];
$fields[] = [
"type" => "textarea",
"name" => "pre_content",
"id" => "pre_content",
"label" => t("Pre-content:"),
"value" => isset($_REQUEST["pre_content"]) ?
$_REQUEST["pre_content"]
:
"",
"description" => t("Content that will appear above the results.")
];
$fields[] = [
"type" => "textarea",
"name" => "sub_content",
"id" => "sub_content",
"label" => t("Sub-content:"),
"value" => isset($_REQUEST["sub_content"]) ?
$_REQUEST["sub_content"]
:
"",
"description" => t("Content that will appear below the results.")
];
$fields[] = [
"type" => "text",
"name" => "results_to_show",
"value" => isset($_REQUEST["results_to_show"]) ?
$_REQUEST["results_to_show"]
:
5,
"label" => t("Results to show:"),
"id" => "results_to_show",
"required" => true,
"description" => t("The amount of results to display.")
];
$fields[] = [
"type" => "uri",
"name" => "calendar_uri",
"value" => isset($_REQUEST["calendar_uri"]) ?
$_REQUEST["calendar_uri"]
:
"",
"label" => t("Calendar uri:"),
"required" => true,
"description" => t("The uri of the calendar from which to display the events.")
];
$fieldset[] = [
"fields" => $fields,
];
Jaris\Forms::addFieldsets(
$fieldset,
"Users Access",
$fieldsets,
true
);
}
} elseif (Jaris\Uri::get() == "admin/blocks/edit") {
$block_data = Jaris\Blocks::get(
intval($_REQUEST["id"]),
$_REQUEST["position"]
);
if (isset($block_data["is_calendar_block"])) {
$fields[] = [
"type" => "hidden",
"name" => "calendar_block",
"value" => 1
];
$fields[] = [
"type" => "textarea",
"name" => "pre_content",
"id" => "pre_content",
"label" => t("Pre-content:"),
"value" => isset($_REQUEST["pre_content"]) ?
$_REQUEST["pre_content"]
:
$block_data["pre_content"],
"description" => t("Content that will appear above the results.")
];
$fields[] = [
"type" => "textarea",
"name" => "sub_content",
"id" => "sub_content",
"label" => t("Sub-content:"),
"value" => isset($_REQUEST["sub_content"]) ?
$_REQUEST["sub_content"]
:
$block_data["sub_content"],
"description" => t("Content that will appear below the results.")
];
$fields[] = [
"type" => "text",
"name" => "results_to_show",
"value" => isset($_REQUEST["results_to_show"]) ?
$_REQUEST["results_to_show"]
:
$block_data["results_to_show"],
"label" => t("Results to show:"),
"id" => "results_to_show",
"required" => true,
"description" => t("The amount of results to display.")
];
if (isset($block_data["calendar_uri"])) {
$fields[] = [
"type" => "uri",
"name" => "calendar_uri",
"value" => isset($_REQUEST["calendar_uri"]) ?
$_REQUEST["calendar_uri"]
:
$block_data["calendar_uri"],
"label" => t("Calendar uri:"),
"required" => true,
"description" => t("The uri of the calendar from which to display the events.")
];
}
$fieldset[] = [
"fields" => $fields,
];
Jaris\Forms::addFieldsets(
$fieldset,
"Users Access",
$fieldsets,
true
);
}
}
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\Pages::SIGNAL_CREATE_PAGE,
function (&$uri, &$data, &$path) {
if (
Jaris\Uri::get() == "admin/pages/add" &&
$data["type"] == "calendar"
) {
$data["calendar_style"] = $_REQUEST["calendar_style"];
$data["add_event_approval"] = $_REQUEST["add_event_approval"];
if (is_array($_REQUEST["groups_add_event"])) {
$data["groups_add_event"] = serialize(
$_REQUEST["groups_add_event"]
);
} else {
$data["groups_add_event"] = serialize([]);
}
}
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\Pages::SIGNAL_EDIT_PAGE_DATA,
function (&$page, &$new_data, &$page_path) {
if (
Jaris\Uri::get() == "admin/pages/edit" &&
$new_data["type"] == "calendar"
) {
$new_data["calendar_style"] = $_REQUEST["calendar_style"];
$new_data["add_event_approval"] = $_REQUEST["add_event_approval"];
if (is_array($_REQUEST["groups_add_event"])) {
$new_data["groups_add_event"] = serialize(
$_REQUEST["groups_add_event"]
);
} else {
$new_data["groups_add_event"] = serialize([]);
}
}
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\Pages::SIGNAL_MOVE_PAGE,
function (&$actual_uri, &$new_uri) {
$current_path = Jaris\Files::getDir()
. "calendar/" . str_replace("/", "-", $actual_uri)
;
if (is_dir($current_path)) {
$new_path = Jaris\Files::getDir()
. "calendar/" . str_replace("/", "-", $new_uri)
;
rename($current_path, $new_path);
}
// Update calendar events from global db.
$db = Jaris\Sql::open("calendar_events");
Jaris\Sql::query(
"update calendar_events set "
. "uri='$new_uri' "
. "where uri='$actual_uri'",
$db
);
Jaris\Sql::close($db);
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\Pages::SIGNAL_DELETE_PAGE,
function (&$page, &$page_path) {
$current_path = Jaris\Files::getDir()
. "calendar/" . str_replace("/", "-", $page)
;
if (is_dir($current_path)) {
Jaris\FileSystem::recursiveRemoveDir($current_path);
}
// Delete calendar events from global db.
$db = Jaris\Sql::open("calendar_events");
Jaris\Sql::query(
"delete from calendar_events where uri='$page'",
$db
);
Jaris\Sql::close($db);
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\Blocks::SIGNAL_ADD_BLOCK,
function (&$fields, &$position, &$page) {
if (
Jaris\Uri::get() == "admin/blocks/add" &&
isset($_REQUEST["calendar_block"])
) {
if (trim($_REQUEST["content"]) == "") {
$fields["content"] = "<div></div>";
}
$fields["pre_content"] = $_REQUEST["pre_content"];
$fields["sub_content"] = $_REQUEST["sub_content"];
$fields["is_calendar_block"] = 1;
$fields["results_to_show"] = intval($_REQUEST["results_to_show"]);
$fields["calendar_uri"] = $_REQUEST["calendar_uri"];
}
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\Blocks::SIGNAL_EDIT_BLOCK,
function (&$id, &$position, &$new_data, &$page) {
if (
Jaris\Uri::get() == "admin/blocks/edit" &&
isset($_REQUEST["calendar_block"])
) {
if (trim($_REQUEST["content"]) == "") {
$new_data["content"] = "<div></div>";
}
$new_data["pre_content"] = $_REQUEST["pre_content"];
$new_data["sub_content"] = $_REQUEST["sub_content"];
$new_data["results_to_show"] = intval($_REQUEST["results_to_show"]);
if (isset($_REQUEST["calendar_uri"])) {
$new_data["calendar_uri"] = $_REQUEST["calendar_uri"];
}
}
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\View::SIGNAL_THEME_BLOCK,
function (&$position, &$page, &$field) {
if ($field["is_calendar_block"]) {
Jaris\View::addStyle(
Jaris\Modules::directory("calendar")
. "styles/events.css"
);
if (isset($field["calendar_uri"])) {
$field["content"] = Jaris\System::evalPHP(
$field["pre_content"]
);
$field["content"] .= calendar_block_print_results(
$field,
$field["calendar_uri"]
);
$field["content"] .= Jaris\System::evalPHP(
$field["sub_content"]
);
} else {
$field["content"] .= Jaris\System::evalPHP(
$field["pre_content"]
);
$field["content"] .= calendar_block_print_results(
$field
);
$field["content"] .= Jaris\System::evalPHP(
$field["sub_content"]
);
}
$field["is_system"] = true;
}
}
);
Jaris\Signals\SignalHandler::listenWithParams(
Jaris\View::SIGNAL_THEME_CONTENT,
function (&$content, &$content_title, &$content_data) {
if ($content_data["type"] == "calendar") {
Jaris\View::addStyle(
Jaris\Modules::directory("calendar")
. "styles/calendar.css"
);
if (
empty($content_data["calendar_style"]) ||
$content_data["calendar_style"] == "traditional"
) {
$month = date("n", time());
$year = date("Y", time());
if (isset($_REQUEST["month"])) {
$rmonth = intval($_REQUEST["month"]);
if ($rmonth >= 1 && $rmonth <= 12) {
$month = $rmonth;
}
}
if (isset($_REQUEST["year"])) {
$year = intval($_REQUEST["year"]);
}
$content .= calendar_generate(
$month,
$year,
Jaris\Uri::get()
);
} else {
$content .= calendar_generate_consecutive(
Jaris\Uri::get()
);
}
}
}
);
| gpl-3.0 |
wiki2014/Learning-Summary | alps/cts/hostsidetests/services/windowmanager/dndtargetappsdk23/src/android/wm/cts/dndtargetappsdk23/DropTarget.java | 2737 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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 android.wm.cts.dndtargetappsdk23;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.widget.TextView;
/**
* This application is compiled against SDK 23 and used to verify that apps targeting SDK 23 and
* below do not receive global drags.
*/
public class DropTarget extends Activity {
public static final String LOG_TAG = "DropTarget";
private static final String RESULT_KEY_DRAG_STARTED = "DRAG_STARTED";
private static final String RESULT_KEY_DROP_RESULT = "DROP";
public static final String RESULT_OK = "OK";
private TextView mTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = getLayoutInflater().inflate(R.layout.target_activity, null);
setContentView(view);
mTextView = (TextView) findViewById(R.id.drag_target);
mTextView.setOnDragListener(new OnDragListener());
}
private void logResult(String key, String value) {
String result = key + "=" + value;
Log.i(LOG_TAG, result);
mTextView.setText(result);
}
private class OnDragListener implements View.OnDragListener {
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
logResult(RESULT_KEY_DRAG_STARTED, RESULT_OK);
return true;
case DragEvent.ACTION_DRAG_ENTERED:
return true;
case DragEvent.ACTION_DRAG_LOCATION:
return true;
case DragEvent.ACTION_DRAG_EXITED:
return true;
case DragEvent.ACTION_DROP:
logResult(RESULT_KEY_DROP_RESULT, RESULT_OK);
return true;
case DragEvent.ACTION_DRAG_ENDED:
return true;
default:
return false;
}
}
}
}
| gpl-3.0 |
infiniteautomation/BACnet4J | src/main/java/com/serotonin/bacnet4j/obj/TrendLogObject.java | 36887 | package com.serotonin.bacnet4j.obj;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.RemoteDevice;
import com.serotonin.bacnet4j.event.DeviceEventAdapter;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.exception.BACnetServiceException;
import com.serotonin.bacnet4j.obj.logBuffer.LinkedListLogBuffer;
import com.serotonin.bacnet4j.obj.logBuffer.LogBuffer;
import com.serotonin.bacnet4j.obj.mixin.HasStatusFlagsMixin;
import com.serotonin.bacnet4j.obj.mixin.PollingDelegate;
import com.serotonin.bacnet4j.obj.mixin.ReadOnlyPropertyMixin;
import com.serotonin.bacnet4j.obj.mixin.event.IntrinsicReportingMixin;
import com.serotonin.bacnet4j.obj.mixin.event.eventAlgo.BufferReadyAlgo;
import com.serotonin.bacnet4j.service.confirmed.SubscribeCOVPropertyRequest;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.constructed.ClientCov;
import com.serotonin.bacnet4j.type.constructed.DateTime;
import com.serotonin.bacnet4j.type.constructed.DeviceObjectPropertyReference;
import com.serotonin.bacnet4j.type.constructed.EventTransitionBits;
import com.serotonin.bacnet4j.type.constructed.LogRecord;
import com.serotonin.bacnet4j.type.constructed.LogStatus;
import com.serotonin.bacnet4j.type.constructed.PropertyReference;
import com.serotonin.bacnet4j.type.constructed.PropertyValue;
import com.serotonin.bacnet4j.type.constructed.SequenceOf;
import com.serotonin.bacnet4j.type.constructed.StatusFlags;
import com.serotonin.bacnet4j.type.constructed.ValueSource;
import com.serotonin.bacnet4j.type.enumerated.ErrorClass;
import com.serotonin.bacnet4j.type.enumerated.ErrorCode;
import com.serotonin.bacnet4j.type.enumerated.EventState;
import com.serotonin.bacnet4j.type.enumerated.LoggingType;
import com.serotonin.bacnet4j.type.enumerated.NotifyType;
import com.serotonin.bacnet4j.type.enumerated.ObjectType;
import com.serotonin.bacnet4j.type.enumerated.PropertyIdentifier;
import com.serotonin.bacnet4j.type.enumerated.Reliability;
import com.serotonin.bacnet4j.type.error.ErrorClassAndCode;
import com.serotonin.bacnet4j.type.notificationParameters.BufferReadyNotif;
import com.serotonin.bacnet4j.type.primitive.Boolean;
import com.serotonin.bacnet4j.type.primitive.ObjectIdentifier;
import com.serotonin.bacnet4j.type.primitive.UnsignedInteger;
import com.serotonin.bacnet4j.util.DeviceObjectPropertyReferences;
import com.serotonin.bacnet4j.util.DeviceObjectPropertyValues;
import com.serotonin.bacnet4j.util.PropertyValues;
/**
* TODO
* - Time change events. See "time-change" in 12.25.14.
* - Log interrupted
* - Align intervals considering daylight savings time.
* - What if a device doesn't support SubscribeCOVPropertyRequest?
*/
public class TrendLogObject extends BACnetObject {
static final Logger LOG = LoggerFactory.getLogger(TrendLogObject.class);
// CreateObject constructor
public static TrendLogObject create(final LocalDevice localDevice, final int instanceNumber)
throws BACnetServiceException {
return new TrendLogObject(localDevice, instanceNumber, ObjectType.trendLog.toString() + " " + instanceNumber,
new LinkedListLogBuffer<>(), false, DateTime.UNSPECIFIED, DateTime.UNSPECIFIED,
new DeviceObjectPropertyReference(localDevice.getInstanceNumber(), localDevice.getId(),
PropertyIdentifier.databaseRevision),
60, false, 100) //
.supportIntrinsicReporting(20, 0, new EventTransitionBits(false, false, false),
NotifyType.event);
}
private final LogBuffer<LogRecord> buffer;
private boolean logDisabled;
private ScheduledFuture<?> startTimeFuture;
private ScheduledFuture<?> stopTimeFuture;
private PollingDelegate pollingDelegate;
private ScheduledFuture<?> pollingFuture;
private SubscribeCOVPropertyRequest covSubscription;
private DeviceEventAdapter covListener;
private ScheduledFuture<?> resubscriptionFuture;
private boolean configurationError;
/**
* Log buffers are expected to have been initialized to their buffer size.
*/
public TrendLogObject(final LocalDevice localDevice, final int instanceNumber, final String name,
final LogBuffer<LogRecord> buffer, final boolean enable, final DateTime startTime, final DateTime stopTime,
final DeviceObjectPropertyReference logDeviceObjectProperty, final int logInterval,
final boolean stopWhenFull, final int bufferSize) throws BACnetServiceException {
super(localDevice, ObjectType.trendLog, instanceNumber, name);
Objects.requireNonNull(startTime);
Objects.requireNonNull(stopTime);
Objects.requireNonNull(logDeviceObjectProperty);
set(PropertyIdentifier.enable, Boolean.valueOf(enable));
set(PropertyIdentifier.startTime, startTime);
set(PropertyIdentifier.stopTime, stopTime);
set(PropertyIdentifier.logDeviceObjectProperty, logDeviceObjectProperty);
set(PropertyIdentifier.logInterval, new UnsignedInteger(logInterval));
set(PropertyIdentifier.stopWhenFull, Boolean.valueOf(stopWhenFull));
set(PropertyIdentifier.bufferSize, new UnsignedInteger(bufferSize));
set(PropertyIdentifier.logBuffer, buffer);
set(PropertyIdentifier.recordCount, UnsignedInteger.ZERO);
set(PropertyIdentifier.totalRecordCount, UnsignedInteger.ZERO);
set(PropertyIdentifier.alignIntervals, Boolean.TRUE);
set(PropertyIdentifier.intervalOffset, UnsignedInteger.ZERO);
set(PropertyIdentifier.trigger, Boolean.FALSE);
set(PropertyIdentifier.statusFlags, new StatusFlags(false, false, false, false));
set(PropertyIdentifier.reliability, Reliability.noFaultDetected);
updateMonitoredProperty();
updateStartTime(startTime);
updateStopTime(stopTime);
withTriggered();
// Mixins
addMixin(new HasStatusFlagsMixin(this));
addMixin(new ReadOnlyPropertyMixin(this, PropertyIdentifier.logBuffer, PropertyIdentifier.reliability,
PropertyIdentifier.totalRecordCount));
this.buffer = buffer;
logDisabled = !allowLogging(getNow());
localDevice.addObject(this);
}
public TrendLogObject withPolled(final int logInterval, final TimeUnit logIntervalUnit,
final boolean alignIntervals, final int intervalOffset, final TimeUnit offsetUnit) {
set(PropertyIdentifier.logInterval, new UnsignedInteger(logIntervalUnit.toMillis(logInterval) / 10));
set(PropertyIdentifier.alignIntervals, Boolean.valueOf(alignIntervals));
set(PropertyIdentifier.intervalOffset, new UnsignedInteger(offsetUnit.toMillis(intervalOffset) / 10));
set(PropertyIdentifier.loggingType, LoggingType.polled);
updateLoggingType();
return this;
}
public TrendLogObject withCov(final int covResubscriptionIntervalSeconds, final ClientCov clientCovIncrement) {
Objects.requireNonNull(clientCovIncrement);
set(PropertyIdentifier.covResubscriptionInterval, new UnsignedInteger(covResubscriptionIntervalSeconds));
set(PropertyIdentifier.clientCovIncrement, clientCovIncrement);
set(PropertyIdentifier.loggingType, LoggingType.cov);
updateLoggingType();
return this;
}
public TrendLogObject withTriggered() {
set(PropertyIdentifier.loggingType, LoggingType.triggered);
updateLoggingType();
return this;
}
public TrendLogObject supportIntrinsicReporting(final int notificationThreshold, final int notificationClass,
final EventTransitionBits eventEnable, final NotifyType notifyType) {
Objects.requireNonNull(eventEnable);
Objects.requireNonNull(notifyType);
// Prepare the object with all of the properties that intrinsic reporting will need.
// User-defined properties
writePropertyInternal(PropertyIdentifier.notificationThreshold, new UnsignedInteger(notificationThreshold));
writePropertyInternal(PropertyIdentifier.recordsSinceNotification, UnsignedInteger.ZERO);
writePropertyInternal(PropertyIdentifier.lastNotifyRecord, UnsignedInteger.ZERO);
writePropertyInternal(PropertyIdentifier.eventState, EventState.normal);
writePropertyInternal(PropertyIdentifier.notificationClass, new UnsignedInteger(notificationClass));
writePropertyInternal(PropertyIdentifier.eventEnable, eventEnable);
writePropertyInternal(PropertyIdentifier.notifyType, notifyType);
writePropertyInternal(PropertyIdentifier.eventDetectionEnable, Boolean.TRUE);
final BufferReadyAlgo algo = new BufferReadyAlgo(PropertyIdentifier.totalRecordCount,
new DeviceObjectPropertyReference(getId(), PropertyIdentifier.logBuffer, null,
getLocalDevice().getId()),
PropertyIdentifier.notificationThreshold, PropertyIdentifier.lastNotifyRecord);
final PropertyIdentifier[] triggerProps = new PropertyIdentifier[] { //
PropertyIdentifier.totalRecordCount, //
PropertyIdentifier.notificationThreshold };
// Now add the mixin.
addMixin(new IntrinsicReportingMixin(this, algo, null, PropertyIdentifier.totalRecordCount, triggerProps)
.withPostNotificationAction((notifParams) -> {
if (notifParams.getParameter() instanceof BufferReadyNotif) {
// After a notification has been sent, a couple values need to be updated.
final BufferReadyNotif brn = (BufferReadyNotif) notifParams.getParameter();
writePropertyInternal(PropertyIdentifier.lastNotifyRecord, brn.getCurrentNotification());
writePropertyInternal(PropertyIdentifier.recordsSinceNotification, UnsignedInteger.ZERO);
}
}));
updateMonitoredProperty();
return this;
}
public boolean isLogDisabled() {
return logDisabled;
}
public LogBuffer<LogRecord> getBuffer() {
return buffer;
}
public void setEnabled(final boolean enabled) {
writePropertyInternal(PropertyIdentifier.enable, Boolean.valueOf(enabled));
}
/**
* Locally trigger a poll.
*
* @return true if the trigger was done, false if the trigger value was already true, indicating that a trigger
* was already in progress.
*/
public synchronized boolean trigger() {
final Boolean trigger = get(PropertyIdentifier.trigger);
if (trigger.booleanValue()) {
return false;
}
set(PropertyIdentifier.trigger, Boolean.TRUE);
doTrigger();
return true;
}
@Override
protected void beforeReadProperty(final PropertyIdentifier pid) throws BACnetServiceException {
if (PropertyIdentifier.logBuffer.equals(pid)) {
throw new BACnetServiceException(ErrorClass.property, ErrorCode.readAccessDenied);
}
}
@Override
protected boolean validateProperty(final ValueSource valueSource, final PropertyValue value)
throws BACnetServiceException {
if (PropertyIdentifier.enable.equals(value.getPropertyIdentifier())) {
final Boolean enable = value.getValue();
final Boolean stopWhenFull = get(PropertyIdentifier.stopWhenFull);
final UnsignedInteger bufferSize = get(PropertyIdentifier.bufferSize);
if (enable.booleanValue() && stopWhenFull.booleanValue() && bufferSize.intValue() == buffer.size()) {
throw new BACnetServiceException(ErrorClass.object, ErrorCode.logBufferFull);
}
} else if (PropertyIdentifier.startTime.equals(value.getPropertyIdentifier()) //
|| PropertyIdentifier.stopTime.equals(value.getPropertyIdentifier())) {
// Ensure that the date time is either entirely unspecified or entirely specified.
final DateTime dt = value.getValue();
if (dt.equals(DateTime.UNSPECIFIED))
return false;
if (!dt.isFullySpecified())
throw new BACnetServiceException(ErrorClass.property, ErrorCode.parameterOutOfRange);
} else if (PropertyIdentifier.logDeviceObjectProperty.equals(value.getPropertyIdentifier())) {
final DeviceObjectPropertyReference logDeviceObjectProperty = value.getValue();
if (logDeviceObjectProperty.getPropertyIdentifier().isOneOf(PropertyIdentifier.all,
PropertyIdentifier.required, PropertyIdentifier.optional)) {
throw new BACnetServiceException(ErrorClass.property, ErrorCode.parameterOutOfRange);
}
} else if (PropertyIdentifier.logInterval.equals(value.getPropertyIdentifier())) {
final LoggingType loggingType = get(PropertyIdentifier.loggingType);
if (!loggingType.isOneOf(LoggingType.polled, LoggingType.cov)) {
throw new BACnetServiceException(ErrorClass.property, ErrorCode.writeAccessDenied);
}
} else if (PropertyIdentifier.bufferSize.equals(value.getPropertyIdentifier())) {
final Boolean enable = get(PropertyIdentifier.enable);
if (enable.booleanValue()) {
throw new BACnetServiceException(ErrorClass.property, ErrorCode.writeAccessDenied);
}
} else if (PropertyIdentifier.recordCount.equals(value.getPropertyIdentifier())) {
// Only allowed to write a zero to this record. What would any other value do?
final UnsignedInteger recordCount = value.getValue();
if (recordCount.intValue() != 0)
throw new BACnetServiceException(ErrorClass.property, ErrorCode.writeAccessDenied);
}
return false;
}
@Override
protected void afterWriteProperty(final PropertyIdentifier pid, final Encodable oldValue,
final Encodable newValue) {
if (PropertyIdentifier.enable.equals(pid)) {
evaluateLogDisabled();
} else if (PropertyIdentifier.startTime.equals(pid)) {
updateStartTime((DateTime) newValue);
} else if (PropertyIdentifier.stopTime.equals(pid)) {
updateStopTime((DateTime) newValue);
} else if (PropertyIdentifier.logDeviceObjectProperty.equals(pid)) {
purge();
updateMonitoredProperty();
} else if (PropertyIdentifier.logInterval.equals(pid)) {
final int oldLogInterval = ((UnsignedInteger) oldValue).intValue();
final int logInterval = ((UnsignedInteger) newValue).intValue();
final LoggingType loggingType = get(PropertyIdentifier.loggingType);
if (loggingType.equals(LoggingType.polled) && oldLogInterval != 0 && logInterval == 0) {
set(PropertyIdentifier.loggingType, LoggingType.cov);
} else if (loggingType.equals(LoggingType.cov) && logInterval != 0) {
set(PropertyIdentifier.loggingType, LoggingType.polled);
}
updateLoggingType();
} else if (pid.isOneOf(PropertyIdentifier.covResubscriptionInterval, PropertyIdentifier.clientCovIncrement)) {
final LoggingType loggingType = get(PropertyIdentifier.loggingType);
if (loggingType.equals(LoggingType.cov)) {
updateLoggingType();
}
} else if (PropertyIdentifier.stopWhenFull.equals(pid)) {
final Boolean oldStopWhenFull = (Boolean) oldValue;
final Boolean stopWhenFull = (Boolean) newValue;
if (!oldStopWhenFull.booleanValue() && stopWhenFull.booleanValue()) {
// Turning StopWhenFull on.
final UnsignedInteger bufferSize = get(PropertyIdentifier.bufferSize);
if (buffer.size() >= bufferSize.intValue()) {
synchronized (buffer) {
while (buffer.size() >= bufferSize.intValue())
buffer.remove();
}
updateRecordCount();
writePropertyInternal(PropertyIdentifier.enable, Boolean.FALSE);
}
}
} else if (PropertyIdentifier.bufferSize.equals(pid)) {
final UnsignedInteger bufferSize = (UnsignedInteger) newValue;
// In case the buffer size was reduced, remove extra entries in the buffer.
synchronized (buffer) {
while (buffer.size() >= bufferSize.intValue())
buffer.remove();
}
updateRecordCount();
} else if (PropertyIdentifier.recordCount.equals(pid)) {
final UnsignedInteger recordCount = (UnsignedInteger) newValue;
if (recordCount.intValue() == 0)
purge();
} else if (PropertyIdentifier.loggingType.equals(pid)) {
updateLoggingType();
} else if (pid.isOneOf(PropertyIdentifier.alignIntervals, PropertyIdentifier.intervalOffset)) {
final LoggingType loggingType = get(PropertyIdentifier.loggingType);
if (loggingType.equals(LoggingType.polled)) {
updateLoggingType();
}
} else if (PropertyIdentifier.trigger.equals(pid)) {
// If the value has changed from false to true.
if (((Boolean) newValue).booleanValue() && !((Boolean) oldValue).booleanValue()) {
doTrigger();
}
}
}
private void purge() {
synchronized (buffer) {
buffer.clear();
}
writePropertyInternal(PropertyIdentifier.recordsSinceNotification, UnsignedInteger.ZERO);
addLogRecordImpl(new LogRecord(getNow(), new LogStatus(logDisabled, true, false), null));
}
private void updateStartTime(final DateTime startTime) {
cancelFuture(startTimeFuture);
if (!startTime.equals(DateTime.UNSPECIFIED)) {
final DateTime now = getNow();
final long diff = startTime.getGC().getTimeInMillis() - now.getGC().getTimeInMillis();
if (diff > 0) {
startTimeFuture = getLocalDevice().schedule(() -> evaluateLogDisabled(), diff, TimeUnit.MILLISECONDS);
}
}
evaluateLogDisabled();
}
private void updateStopTime(final DateTime stopTime) {
cancelFuture(stopTimeFuture);
if (!stopTime.equals(DateTime.UNSPECIFIED)) {
final DateTime now = getNow();
final long diff = stopTime.getGC().getTimeInMillis() - now.getGC().getTimeInMillis();
if (diff > 0) {
stopTimeFuture = getLocalDevice().schedule(() -> evaluateLogDisabled(), diff, TimeUnit.MILLISECONDS);
}
}
evaluateLogDisabled();
}
@Override
protected void terminateImpl() {
super.terminate();
cancelFuture(startTimeFuture);
cancelFuture(stopTimeFuture);
cancelFuture(pollingFuture);
cancelCov();
}
private static void cancelFuture(final ScheduledFuture<?> future) {
if (future != null)
future.cancel(false);
}
private void cancelCov() {
if (covSubscription != null) {
final DeviceObjectPropertyReference monitored = get(PropertyIdentifier.logDeviceObjectProperty);
// Cancel the subscription
final SubscribeCOVPropertyRequest cancellation = new SubscribeCOVPropertyRequest(covSubscription);
if (monitored.getDeviceIdentifier().getInstanceNumber() == getLocalDevice().getInstanceNumber()) {
try {
cancellation.handle(getLocalDevice(), getLocalDevice().getLoopbackAddress());
} catch (final BACnetException e) {
// Shouldn't really happen, but note it anyway.
LOG.error("Failed to unsubscribe locally", e);
}
} else {
RemoteDevice rd;
try {
rd = getLocalDevice().getRemoteDeviceBlocking(monitored.getDeviceIdentifier().getInstanceNumber());
} catch (final BACnetException e) {
LOG.warn("Failed to find remote device to which to send unsubscribe", e);
updateConfigurationError(true);
return;
}
getLocalDevice().send(rd, cancellation, null);
}
covSubscription = null;
}
if (covListener != null) {
getLocalDevice().getEventHandler().removeListener(covListener);
covListener = null;
}
cancelFuture(resubscriptionFuture);
}
private void updateMonitoredProperty() {
final DeviceObjectPropertyReference monitored = get(PropertyIdentifier.logDeviceObjectProperty);
// Add the monitored property.
final DeviceObjectPropertyReferences refs = new DeviceObjectPropertyReferences();
refs.addIndex(monitored.getDeviceIdentifier().getInstanceNumber(), monitored.getObjectIdentifier(),
monitored.getPropertyIdentifier(), monitored.getPropertyArrayIndex());
// Check if status flags exist for the object.
final ObjectPropertyTypeDefinition def = ObjectProperties.getObjectPropertyTypeDefinition(
monitored.getObjectIdentifier().getObjectType(), PropertyIdentifier.statusFlags);
if (def != null) {
refs.add(monitored.getDeviceIdentifier().getInstanceNumber(), monitored.getObjectIdentifier(),
PropertyIdentifier.statusFlags);
}
pollingDelegate = new PollingDelegate(getLocalDevice(), refs);
}
/**
* This method reinitializes all data retrieval.
*/
private void updateLoggingType() {
final LoggingType loggingType = get(PropertyIdentifier.loggingType);
cancelFuture(pollingFuture);
cancelCov();
if (loggingType.equals(LoggingType.polled)) {
final UnsignedInteger logInterval = get(PropertyIdentifier.logInterval);
final Boolean alignIntervals = get(PropertyIdentifier.alignIntervals);
final UnsignedInteger intervalOffset = get(PropertyIdentifier.intervalOffset);
long period = logInterval.longValue() * 10;
if (period == 0)
// 0 is a poor value. Default to 5 minutes in this case, since it "is a local matter".
period = TimeUnit.MINUTES.toMillis(5);
long initialDelay = 0;
int offsetToUse = 0;
if (alignIntervals.booleanValue()) {
final long now = getLocalDevice().getClock().millis();
// Find the largest time period to which the period aligns.
if (period % TimeUnit.DAYS.toMillis(1) == 0) {
initialDelay = TimeUnit.DAYS.toMillis(1) - now % TimeUnit.DAYS.toMillis(1);
} else if (period % TimeUnit.HOURS.toMillis(1) == 0) {
initialDelay = TimeUnit.HOURS.toMillis(1) - now % TimeUnit.HOURS.toMillis(1);
} else if (period % TimeUnit.MINUTES.toMillis(1) == 0) {
initialDelay = TimeUnit.MINUTES.toMillis(1) - now % TimeUnit.MINUTES.toMillis(1);
} else if (period % TimeUnit.SECONDS.toMillis(1) == 0) {
initialDelay = TimeUnit.SECONDS.toMillis(1) - now % TimeUnit.SECONDS.toMillis(1);
}
offsetToUse = intervalOffset.intValue() * 10;
offsetToUse %= period;
}
initialDelay += offsetToUse;
initialDelay %= period;
pollingFuture = getLocalDevice().scheduleAtFixedRate(() -> doPoll(), initialDelay, period,
TimeUnit.MILLISECONDS);
} else if (loggingType.equals(LoggingType.cov)) {
final DeviceObjectPropertyReference monitored = get(PropertyIdentifier.logDeviceObjectProperty);
set(PropertyIdentifier.logInterval, UnsignedInteger.ZERO);
final UnsignedInteger covResubscriptionInterval = get(PropertyIdentifier.covResubscriptionInterval);
final int resubscribeSeconds = covResubscriptionInterval.intValue();
final ClientCov clientCovIncrement = get(PropertyIdentifier.clientCovIncrement);
// Create the subscription
final ObjectIdentifier deviceIdentifier = monitored.getDeviceIdentifier();
final SubscribeCOVPropertyRequest localCovSubscription = new SubscribeCOVPropertyRequest(
new UnsignedInteger(getLocalDevice().getNextProcessId()), monitored.getObjectIdentifier(),
Boolean.TRUE, new UnsignedInteger(resubscribeSeconds * 2),
new PropertyReference(monitored.getPropertyIdentifier(), monitored.getPropertyArrayIndex()),
clientCovIncrement.isRealIncrement() ? clientCovIncrement.getRealIncrement() : null);
covSubscription = localCovSubscription;
// Create the listener that will catch the COV notifications.
covListener = new DeviceEventAdapter() {
@Override
public void covNotificationReceived(final UnsignedInteger subscriberProcessIdentifier,
final ObjectIdentifier initiatingDeviceIdentifier,
final ObjectIdentifier monitoredObjectIdentifier, final UnsignedInteger timeRemaining,
final SequenceOf<PropertyValue> listOfValues) {
LOG.debug("Received COV notification");
// Handle the COV subscription. Check if it matches the subscription.
if (localCovSubscription.getSubscriberProcessIdentifier().equals(subscriberProcessIdentifier) //
&& deviceIdentifier.equals(initiatingDeviceIdentifier) //
&& localCovSubscription.getMonitoredObjectIdentifier().equals(monitoredObjectIdentifier)) {
// Looks like this is for us.
Encodable value = null;
StatusFlags statusFlags = null;
for (final PropertyValue pv : listOfValues) {
if (pv.getPropertyIdentifier().equals(monitored.getPropertyIdentifier())) {
value = pv.getValue();
} else if (pv.getPropertyIdentifier().equals(PropertyIdentifier.statusFlags)) {
statusFlags = (StatusFlags) pv.getValue();
}
}
if (value == null) {
LOG.warn("Requested property not found in COV notification: {}", listOfValues);
updateConfigurationError(true);
} else {
LOG.debug("COV update: " + value);
addLogRecord(LogRecord.createFromMonitoredValue(getNow(), value, statusFlags));
}
}
}
};
getLocalDevice().getEventHandler().addListener(covListener);
// Check if we're monitoring locally.
if (monitored.getDeviceIdentifier().getInstanceNumber() == getLocalDevice().getInstanceNumber()) {
// Subscribe, and resubscribe.
resubscriptionFuture = getLocalDevice().scheduleAtFixedRate(() -> {
try {
covSubscription.handle(getLocalDevice(), getLocalDevice().getLoopbackAddress());
LOG.debug("COV subscription successful");
} catch (final BACnetException e) {
LOG.warn("COV subscription failed", e);
updateConfigurationError(true);
return;
}
}, 0, resubscribeSeconds, TimeUnit.SECONDS);
} else {
// Get the remote device.
RemoteDevice rd;
try {
rd = getLocalDevice().getRemoteDeviceBlocking(monitored.getDeviceIdentifier().getInstanceNumber());
} catch (final BACnetException e) {
LOG.warn("Failed to find remote device to which to send unsubscribe", e);
updateConfigurationError(true);
return;
}
// Subscribe, and resubscribe.
resubscriptionFuture = getLocalDevice().scheduleAtFixedRate(() -> {
try {
getLocalDevice().send(rd, covSubscription).get();
LOG.debug("COV subscription successful");
} catch (final BACnetException e) {
LOG.warn("COV subscription failed", e);
updateConfigurationError(true);
return;
}
}, 0, resubscribeSeconds, TimeUnit.SECONDS);
}
} else if (loggingType.equals(LoggingType.triggered)) {
set(PropertyIdentifier.logInterval, UnsignedInteger.ZERO);
}
updateConfigurationError(false);
}
private void doTrigger() {
// Perform the trigger asynchronously
getLocalDevice().execute(() -> {
try {
// Do the poll.
doPoll();
LOG.debug("Trigger complete");
} finally {
// Set the trigger value back to false.
writePropertyInternal(PropertyIdentifier.trigger, Boolean.FALSE);
}
});
}
private synchronized void doPoll() {
// The spec says that no *logging* should occur if the log is disabled, but there doesn't seem to be much
// point in polling at all if this is the case, so we check here and abort accordingly.
if (logDisabled)
return;
// Get the time before the poll, so that alignment looks right.
final DateTime now = getNow();
// Call the delegate to perform the poll.
final DeviceObjectPropertyValues result = pollingDelegate.doPoll();
// Check the result.
final DeviceObjectPropertyReference monitored = get(PropertyIdentifier.logDeviceObjectProperty);
final PropertyValues values = result.getPropertyValues(monitored.getDeviceIdentifier().getInstanceNumber());
final Encodable value = values.getNoErrorCheck(monitored.getObjectIdentifier(),
new PropertyReference(monitored.getPropertyIdentifier(), monitored.getPropertyArrayIndex()));
LogRecord record;
boolean error = false;
if (value instanceof ErrorClassAndCode) {
record = LogRecord.createFromMonitoredValue(now, value, null);
error = true;
LOG.warn("Error returned for value from poll: {}", value);
} else {
// Get the status flags
final Encodable statusFlags = values.getNoErrorCheck(monitored.getObjectIdentifier(),
PropertyIdentifier.statusFlags);
if (statusFlags instanceof ErrorClassAndCode) {
error = true;
LOG.warn("Error returned for statusFlags from poll: {}", value);
record = LogRecord.createFromMonitoredValue(now, value, null);
} else {
record = LogRecord.createFromMonitoredValue(now, value, (StatusFlags) statusFlags);
}
}
updateConfigurationError(error);
addLogRecord(record);
}
private void updateConfigurationError(final boolean error) {
if (configurationError != error) {
configurationError = error;
if (error) {
writePropertyInternal(PropertyIdentifier.reliability, Reliability.configurationError);
} else {
writePropertyInternal(PropertyIdentifier.reliability, Reliability.noFaultDetected);
}
}
}
private synchronized void addLogRecord(final LogRecord record) {
// Check if logging is allowed.
if (logDisabled)
return;
// Add the new record.
addLogRecordImpl(record);
fullCheck();
}
private void fullCheck() {
final Boolean stopWhenFull = get(PropertyIdentifier.stopWhenFull);
final UnsignedInteger bufferSize = get(PropertyIdentifier.bufferSize);
if (stopWhenFull.booleanValue() && buffer.size() == bufferSize.intValue() - 1) {
// There is only one spot left in the buffer, and StopWhenFull is true. Set Enable to false.
writePropertyInternal(PropertyIdentifier.enable, Boolean.FALSE);
}
}
private void addLogRecordImpl(final LogRecord record) {
final UnsignedInteger bufferSize = get(PropertyIdentifier.bufferSize);
synchronized (buffer) {
// Don't add more to the buffer than capacity.
if (buffer.size() == bufferSize.intValue()) {
// Buffer is already full. Drop the oldest record.
buffer.remove();
}
buffer.add(record);
}
updateRecordCount();
final UnsignedInteger recordsSinceNotification = get(PropertyIdentifier.recordsSinceNotification);
if (recordsSinceNotification != null) {
writePropertyInternal(PropertyIdentifier.recordsSinceNotification, recordsSinceNotification.increment32());
}
// The total record count must be written last because it is the monitored property for intrinsic reporting.
UnsignedInteger totalRecordCount = get(PropertyIdentifier.totalRecordCount);
totalRecordCount = totalRecordCount.increment32();
if (totalRecordCount.longValue() == 0)
// Value overflowed. As per 12.25.16 set to 1.
totalRecordCount = new UnsignedInteger(1);
record.setSequenceNumber(totalRecordCount.longValue());
writePropertyInternal(PropertyIdentifier.totalRecordCount, totalRecordCount);
}
/**
* Determines whether logging should be performed based upon Enable, StartTime, and StopTime.
*/
private boolean allowLogging(final DateTime now) {
final Boolean enabled = get(PropertyIdentifier.enable);
if (!enabled.booleanValue())
return false;
final DateTime start = get(PropertyIdentifier.startTime);
final DateTime stop = get(PropertyIdentifier.stopTime);
if (!start.equals(DateTime.UNSPECIFIED)) {
LOG.debug("Checking start time");
if (now.compareTo(start) < 0)
return false;
}
if (!stop.equals(DateTime.UNSPECIFIED)) {
LOG.debug("Checking stop time, now={}, stop={}", now, stop);
if (now.compareTo(stop) >= 0)
return false;
}
return true;
}
private void updateRecordCount() {
writePropertyInternal(PropertyIdentifier.recordCount, new UnsignedInteger(buffer.size()));
}
private void evaluateLogDisabled() {
// Don't evaluate until instantiation is complete.
if (buffer != null) {
final DateTime now = getNow();
final boolean newValue = !allowLogging(now);
if (logDisabled != newValue) {
logDisabled = newValue;
if (logDisabled)
// Only write a log status if the log is disabled.
addLogRecordImpl(new LogRecord(now, new LogStatus(logDisabled, false, false), null));
}
}
}
private DateTime getNow() {
return new DateTime(getLocalDevice().getClock().millis());
}
}
| gpl-3.0 |
ska/myels | Finestra_bck.py | 7314 | #!/usr/bin/python
import socket
import time
from Tkinter import *
class Finestra:
__f=''
__s=''
__StatusBar=''
__ButtonAccendi=''
__ButtonSpegni=''
__Slider=''
__APl='21'
__active=FALSE
__Ip='192.168.1.35'
__Porta=20000
__version= '0.2b'
__sliderStatus= 0
def __init__(self):
self.creaFinestra()
self.connetti()
self.primaLetturaStato()
self.setSlider()
self.disconnetti()
self.__f.mainloop()
def creaFinestra(self):
self.__f = Tk()
self.__f.title("MyEls " + self.__version)
self.__f.resizable(FALSE, FALSE)
#self.__f.wm_iconbitmap("icon.png")
self.frameR0 = Frame(self.__f)
self.frameR1C0 = Frame(self.__f)
self.frameR1C1 = Frame(self.__f)
self.frameR1C2 = Frame(self.__f)
self.frameR2C0 = Frame(self.__f)
self.frameR2C1 = Frame(self.__f)
self.frameR2C2 = Frame(self.__f)
self.frameR3 = Frame(self.__f)
self.frameR0.configure( width="300", height="25")
self.frameR1C0.configure( width="100", height="50")
self.frameR1C1.configure( width="100", height="50")
self.frameR1C2.configure( width="100", height="50")
self.frameR2C0.configure( width="100", height="150")
self.frameR2C1.configure( width="100", height="150")
self.frameR2C2.configure( width="100", height="150")
self.frameR3.configure( width="200", height="30", bd=1, relief=GROOVE)
self.frameR0.grid(row=0, column=0, columnspan=3)
self.frameR1C0.grid(row=1, column=0)
self.frameR1C1.grid(row=1, column=1)
self.frameR1C2.grid(row=1, column=2)
self.frameR2C0.grid(row=2, column=0)
self.frameR2C1.grid(row=2, column=1)
self.frameR2C2.grid(row=2, column=2)
self.frameR3.grid(row=3, column=0, columnspan=3)
menubar = Menu(self.frameR0)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Preferenze")
filemenu.add_separator()
filemenu.add_command(label="Esci")
menubar.add_cascade(label="File", menu=filemenu)
self.__f.config(menu=menubar)
self.__StatusBar = Label(self.frameR3, text="Connessione in corso..")
self.__StatusBar.pack()
self.__ButtonAction = Button(self.frameR1C0, text="Accendi" )
self.__ButtonAction.pack({"side":"top", "padx":1, "pady":0})
self.__ButtonAction['command'] = self.ButtonClickAction
#self.__ButtonAccendi = Button(self.frameR1C0, text="Accendi" )
#self.__ButtonAccendi.pack({"side":"top", "padx":1, "pady":0})
#self.__ButtonAccendi['command'] = self.ButtonClickAccendi
#self.__ButtonSpegni = Button(self.frameR1C2, text="Spegni")
#self.__ButtonSpegni.pack({"side":"top", "padx":2, "pady":20})
#self.__ButtonSpegni['command'] = self.ButtonClickSpegni
self.__ButtonPiu = Button(self.frameR2C2, text="+")
self.__ButtonPiu.pack({"side":"top", "padx":2, "pady":2})
self.__ButtonPiu['command'] = self.ButtonClickPiu
self.__ButtonMeno = Button(self.frameR2C0, text="-")
self.__ButtonMeno.pack({"side":"top", "padx":2, "pady":2})
self.__ButtonMeno['command'] = self.ButtonClickMeno
self.__Slider = Scale(self.frameR2C1, from_=0, to=10, resolution=1, label='Dimmer', command = self.SliderChange, orient=HORIZONTAL)
self.__active=FALSE
self.__Slider.pack()
def connetti(self):
try:
self.__s=socket.socket( socket.AF_INET, socket.SOCK_STREAM)
self.__s.connect((self.__Ip, self.__Porta))
ack = self.__s.recv(6)
if(ack != "*#*1##"):
print "Non connesso 0"
self.__StatusBar["text"] = "Non connesso"
else:
self.__StatusBar["text"] = "Connesso a " + self.__Ip
except socket.error, msg:
print "Non connesso 1"
self.__StatusBar["text"] = "Non connesso"
def primaLetturaStato(self):
try:
self.__s.send("*#1*"+ self.__APl +"##")
status = self.__s.recv(128)
print "status 1:" + status
status = status[3:5]
if status[1] == "*":
status = status[0]
print "Val prima lettura: " + status
self.__active = TRUE
if status == '0':
print "spento"
self.__ButtonAction["text"] = "Accendi"
else:
print "Acceso"
self.__ButtonAction["text"] = "Spegni"
print "esco con val: " + status
self.__sliderStatus = status
except:
print "Non connesso 3"
self.__StatusBar["text"] = "Non connesso"
def leggiStato(self):
try:
self.__s.send("*#1*"+ self.__APl +"##")
status = self.__s.recv(128)
#status = status[3]
print "status 1:" + status
status = self.__s.recv(128)
print "status 2:" + status
val = status[3:5]
if val[1] == "*" or val[1] == "#":
val = val[0]
print "esco con val2: " + val
self.__sliderStatus = val
except:
print "Non connesso 4"
self.__StatusBar["text"] = "Non connesso"
def setSlider(self):
#print "SliderStatus: " + self.__sliderStatus
self.__Slider.set(self.__sliderStatus)
def SliderChange(self, x):
if self.__active == TRUE:
self.connetti()
self.__s.send("*1*"+ x +"*"+ self.__APl +"##")
self.disconnetti()
def ButtonClickAction(self):
self.connetti()
self.leggiStato()
if self.__sliderStatus != 0:
print "action spegni: " + self.__sliderStatus
self.__s.send("*1*0*"+ self.__APl +"##")
else:
print "actioni accendi: " + self.__sliderStatus
self.__s.send("*1*1*"+ self.__APl +"##")
self.leggiStato()
self.disconnetti()
def ButtonClickAccendi(self):
self.connetti()
self.__s.send("*1*1*"+ self.__APl +"##")
self.leggiStato()
self.disconnetti()
def ButtonClickSpegni(self):
self.connetti()
self.__s.send("*1*0*"+ self.__APl +"##")
self.leggiStato()
self.disconnetti()
def ButtonClickPiu(self):
self.connetti()
self.__s.send("*1*30*"+ self.__APl +"##")
self.leggiStato()
self.setSlider()
self.disconnetti()
def ButtonClickMeno(self):
self.connetti()
self.__s.send("*1*31*"+ self.__APl +"##")
self.leggiStato()
self.setSlider()
self.disconnetti()
def disconnetti(self):
self.__s.close()
if __name__ == '__main__':
finestra = Finestra()
| gpl-3.0 |
warnp/runner_game | src/engine/vertex.rs | 259 |
#[derive(Copy, Clone, Debug)]
pub struct Vertex {
pub position: [f32; 3],
pub normal: [f32; 3],
pub color: [f32; 4],
pub tex_coords: [f32; 2],
pub i_tex_id: u32,
}
implement_vertex!(Vertex, position, normal,color, tex_coords,i_tex_id);
| gpl-3.0 |
PlaneaSoluciones/MiniRealtime-Asterisk | panel/controller.cdr.php | 959 | <?php
switch ($view) {
default: // List
showlist();
break;
}
function showlist(){
global $db, $module;
// Getting element list
$query="SELECT calldate, src, dst, duration, billsec, disposition FROM cdr order by calldate desc limit 30";
$dbdata = db::getInstance()->query($query);
// Showing HTML table list
if (isset ($dbdata)){
?>
<table>
<tr>
<th>Fecha</th>
<th>Origen</th>
<th>Destino</th>
<th>Duracion</th>
<th>Tiempo Fac.</th>
<th>Estado</th>
</tr>
<?php
foreach ($dbdata as $data) {
echo '<tr>';
echo '<td>'.$data['calldate'].'</td>';
echo '<td>'.$data['src'].'</td>';
echo '<td>'.$data['dst'].'</td>';
echo '<td>'.$data['duration'].'</td>';
echo '<td>'.$data['billsec'].'</td>';
echo '<td>'.$data['disposition'].'</td>';
echo '</tr>';
}
?>
</table>
<?php
}
}
?>
| gpl-3.0 |
tsyw/cppprimer5eAnswers | ch9/9_8.cc | 58 | // list<string>::const_iterator
// list<string>::iterator
| gpl-3.0 |
iamii/MySSH | books/keepalived/installkeepalived.lua | 562 | require ("books/common")
InstallEPEL()
Cmd{ "yum install keepalived ipvsadm -y && iptables -F && iptables -Z", }
local info = PLAYLISTINFO
if type(info.priority) == "table" then
for k, v in pairs(info.priority) do
if HOST.Name == k then
info.ct["vrrp_instance VI_1"].state= v.state
info.ct["vrrp_instance VI_1"].priority= v.priority
info.ct.global_defs.router_id = k
end
end
end
Cmd{
[[echo ']]..Table2conf(info.ct)..[[' > /etc/keepalived/keepalived.conf]],
"service keepalived restart"
}
| gpl-3.0 |
danielbonetto/twig_MVC | lang/th/block_totara_alerts.php | 2100 | <?php
/*
* This file is part of Totara LMS
*
* Copyright (C) 2010-2012 Totara Learning Solutions LTD
*
* 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/>.
*
* Strings for component 'block_totara_alerts', language 'th', branch 'totara-2.2'
* @package totara
* @subpackage block_totara_alerts
*/
$string['alerts'] = 'การแจ้งเตือน';
$string['clickformoreinfo'] = 'คลิกที่นี่เพื่อข้อมูลเพิ่มเติม';
$string['context'] = 'เชื่อมโยง';
$string['dismiss'] = 'ยกเลิกข้อความ';
$string['from'] = 'จาก';
$string['noalerts'] = 'คุณยังมีไม่มีการแจ้งเตือน';
$string['normal'] = 'ธรรมดา';
$string['of'] = 'ของ';
$string['reviewitems'] = 'รายการคิดเห็น (s)';
$string['showingxofx'] = 'แสดง {$a->count} จาก {$a->total}';
$string['statement'] = 'คำชี้แจง';
$string['status'] = 'สถานะ';
$string['statusnotok'] = 'สถานะไม่โอเค';
$string['statusok'] = 'สถานะโอเค';
$string['statusundecided'] = 'สถานะลังเล';
$string['type'] = 'ประเภท';
$string['urgency'] = 'ความเร่งด่วน';
$string['urgent'] = 'ด่วน';
$string['viewall'] = 'ดูทั้งหมด';
$string['viewallnot'] = 'ดูการแจ้งเตือนทั้งหมด';
| gpl-3.0 |
snessygee/cheshire-cup | playoff-generator/PlayoffTree.php | 2897 | <?php
/*
* This file is part of the PHP Sports Generators (https://bitbucket.org/zdenekdrahos/php-sports-generators)
* Copyright (c) 2012, 2013 Zdenek Drahos (https://bitbucket.org/zdenekdrahos)
* PHP Sports Generators is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License 3, or any later version
* For the full license information view the file license.txt, or <http://www.gnu.org/licenses/>.
*/
final class PlayoffTree {
/** @var array */
private $teams;
/** @var BinaryTree */
private $btree;
/** @param PlayoffGenerator $playoff */
public function __construct($playoff) {
if (!($playoff instanceof PlayoffGenerator)) {
throw new PlayoffException(PlayoffException::EXC4);
}
$this->teams = $playoff->get_teams();
$this->build_tree();
}
/** @return array */
public function get_array() {
$items = $this->btree->get_items();
$result = array();
$result['team_count'] = count($this->teams);
$result['round_count'] = log(count($this->teams), 2);
$result['rounds'] = array();
for ($i = $result['round_count']; $i >= 1; $i--) {
$round = array();
$start = pow(2, $i);
for ($j = 0; $j < pow(2, $i); $j+=2) {
$round[] = array(
'home' => $items[$start + $j],
'away' => $items[$start + $j + 1]
);
}
$result['rounds'][$i] = $round;
}
return $result;
}
private function build_tree() {
$this->btree = new BinaryTree();
$this->btree->insert_root($this->teams[1]);
for ($j = 1; $j <= count($this->teams) / 2; $j++) {
$this->btree->access_root();
$this->btree->access_first($this->teams[$j]);
foreach ($this->find_opponents($j) as $opponent) {
if ($j % 2 == 1) {
$this->btree->insert_left_son($this->teams[$j]);
$this->btree->insert_right_son($opponent);
$this->btree->access_left_son();
} else {
$this->btree->insert_left_son($opponent);
$this->btree->insert_right_son($this->teams[$j]);
$this->btree->access_right_son();
}
}
}
}
private function find_opponents($team_index) {
$opponents = array();
for ($i = 2; $i <= count($this->teams); $i *= 2) {
$opponent = $i - $team_index + 1;
if ($opponent > $team_index) {
$opponents[] = $this->teams[$opponent];
}
}
return $opponents;
}
}
?>
| gpl-3.0 |
richrr/scripts | bash/bbtools/bbmap/current/stream/SiteScoreR.java | 8335 | package stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import shared.Shared;
/**
* @author Brian Bushnell
* @date Jul 16, 2012
*
*/
public final class SiteScoreR implements Comparable<SiteScoreR>{
public SiteScoreR(SiteScore ss, int readlen_, long numericID_, byte pairnum_){
this(ss.chrom, ss.strand, ss.start, ss.stop, readlen_, numericID_, pairnum_, ss.score, ss.pairedScore, ss.perfect, ss.semiperfect);
}
public SiteScoreR(int chrom_, byte strand_, int start_, int stop_, int readlen_, long numericID_, byte pairnum_, int score_, int pscore_, boolean perfect_, boolean semiperfect_){
chrom=chrom_;
strand=strand_;
start=start_;
stop=stop_;
readlen=readlen_;
numericID=numericID_;
pairnum=pairnum_;
score=score_;
pairedScore=pscore_;
perfect=perfect_;
semiperfect=semiperfect_|perfect_;
assert(start_<=stop_) : this.toText();
}
@Override
public int compareTo(SiteScoreR other) {
int x=other.score-score;
if(x!=0){return x;}
x=other.pairedScore-pairedScore;
if(x!=0){return x;}
x=chrom-other.chrom;
if(x!=0){return x;}
x=strand-other.strand;
if(x!=0){return x;}
x=start-other.start;
return x;
}
public boolean equals(Object other){
return compareTo((SiteScoreR)other)==0;
}
public boolean equals(SiteScore other){
if(other.start!=start){return false;}
if(other.stop!=stop){return false;}
if(other.chrom!=chrom){return false;}
if(other.strand!=strand){return false;}
return true;
}
public boolean equals(SiteScoreR other){
return compareTo(other)==0;
}
public String toString(){
// StringBuilder sb=new StringBuilder();
// sb.append('\t');
// sb.append(start);
// int spaces=10-sb.length();
// for(int i=0; i<spaces; i++){
// sb.append(" ");
// }
// sb.append('\t');
// sb.append(quickScore);
// sb.append('\t');
// sb.append(score);
//
// return "chr"+chrom+"\t"+Gene.strandCodes[strand]+sb;
return toText().toString();
}
// 9+2+1+9+9+1+1+4+4+4+4+gaps
public StringBuilder toText(){
StringBuilder sb=new StringBuilder(50);
if(correct){sb.append('*');}
sb.append(chrom);
sb.append(',');
sb.append(strand);
sb.append(',');
sb.append(start);
sb.append(',');
sb.append(stop);
sb.append(',');
sb.append(readlen);
sb.append(',');
sb.append(numericID);
sb.append(',');
sb.append(pairnum);
sb.append(',');
sb.append((semiperfect ? 1 : 0));
sb.append((perfect ? 1 : 0));
sb.append(',');
sb.append(pairedScore);
sb.append(',');
sb.append(score);
// sb.append(',');
// sb.append((long)normalizedScore);
return sb;
// chrom+","+strand+","+start+","+stop+","+(rescued ? 1 : 0)+","+
// (perfect ? 1 : 0)+","+quickScore+","+slowScore+","+pairedScore+","+score;
}
public final boolean overlaps(SiteScoreR ss){
return chrom==ss.chrom && strand==ss.strand && overlap(start, stop, ss.start, ss.stop);
}
private static boolean overlap(int a1, int b1, int a2, int b2){
assert(a1<=b1 && a2<=b2) : a1+", "+b1+", "+a2+", "+b2;
return a2<=b1 && b2>=a1;
}
public static String header() {
return "chrom,strand,start,stop,readlen,numericID,pairnum,semiperfect+perfect,quickScore,slowScore,pairedScore,score";
}
public static SiteScoreR fromText(String s){
// System.err.println("Trying to make a SS from "+s);
String line[]=s.split(",");
SiteScoreR ss;
assert(line.length==10 || line.length==11) : "\n"+line.length+"\n"+s+"\n"+Arrays.toString(line)+"\n";
boolean correct=false;
if(line[0].charAt(0)=='*'){
correct=true;
line[0]=line[0].substring(1);
}
int chrom=Byte.parseByte(line[0]);
byte strand=Byte.parseByte(line[1]);
int start=Integer.parseInt(line[2]);
int stop=Integer.parseInt(line[3]);
int readlen=Integer.parseInt(line[4]);
long numericID=Long.parseLong(line[5]);
byte pairnum=Byte.parseByte(line[6]);
int p=Integer.parseInt(line[7], 2);
boolean perfect=(p&1)==1;
boolean semiperfect=(p&2)==2;
int pairedScore=Integer.parseInt(line[8]);
int score=Integer.parseInt(line[9]);
ss=new SiteScoreR(chrom, strand, start, stop, readlen, numericID, pairnum, score, pairedScore, perfect, semiperfect);
ss.correct=correct;
return ss;
}
public static SiteScoreR[] fromTextArray(String s){
String[] split=s.split("\t");
SiteScoreR[] out=new SiteScoreR[split.length];
for(int i=0; i<split.length; i++){out[i]=fromText(split[i]);}
return out;
}
public boolean positionalMatch(SiteScoreR b){
// return chrom==b.chrom && strand==b.strand && start==b.start && stop==b.stop;
if(chrom!=b.chrom || strand!=b.strand || start!=b.start || stop!=b.stop){
return false;
}
return true;
}
public static class PositionComparator implements Comparator<SiteScoreR>{
private PositionComparator(){}
@Override
public int compare(SiteScoreR a, SiteScoreR b) {
if(a.chrom!=b.chrom){return a.chrom-b.chrom;}
if(a.start!=b.start){return a.start-b.start;}
if(a.stop!=b.stop){return a.stop-b.stop;}
if(a.strand!=b.strand){return a.strand-b.strand;}
if(a.score!=b.score){return b.score-a.score;}
if(a.perfect!=b.perfect){return a.perfect ? -1 : 1;}
return 0;
}
public void sort(List<SiteScoreR> list){
if(list==null || list.size()<2){return;}
Collections.sort(list, this);
}
public void sort(SiteScoreR[] list){
if(list==null || list.length<2){return;}
Arrays.sort(list, this);
}
}
public static class NormalizedComparator implements Comparator<SiteScoreR>{
private NormalizedComparator(){}
@Override
public int compare(SiteScoreR a, SiteScoreR b) {
if((int)a.normalizedScore!=(int)b.normalizedScore){return (int)b.normalizedScore-(int)a.normalizedScore;}
if(a.score!=b.score){return b.score-a.score;}
if(a.pairedScore!=b.pairedScore){return b.pairedScore-a.pairedScore;}
if(a.retainVotes!=b.retainVotes){return b.retainVotes-a.retainVotes;}
if(a.perfect!=b.perfect){return a.perfect ? -1 : 1;}
if(a.chrom!=b.chrom){return a.chrom-b.chrom;}
if(a.start!=b.start){return a.start-b.start;}
if(a.stop!=b.stop){return a.stop-b.stop;}
if(a.strand!=b.strand){return a.strand-b.strand;}
return 0;
}
public void sort(List<SiteScoreR> list){
if(list==null || list.size()<2){return;}
Collections.sort(list, this);
}
public void sort(SiteScoreR[] list){
if(list==null || list.length<2){return;}
Arrays.sort(list, this);
}
}
public static class IDComparator implements Comparator<SiteScoreR>{
private IDComparator(){}
@Override
public int compare(SiteScoreR a, SiteScoreR b) {
if(a.numericID!=b.numericID){return a.numericID>b.numericID ? 1 : -1;}
if(a.pairnum!=b.pairnum){return a.pairnum-b.pairnum;}
if(a.chrom!=b.chrom){return a.chrom-b.chrom;}
if(a.start!=b.start){return a.start-b.start;}
if(a.stop!=b.stop){return a.stop-b.stop;}
if(a.strand!=b.strand){return a.strand-b.strand;}
if(a.score!=b.score){return b.score-a.score;}
if(a.perfect!=b.perfect){return a.perfect ? -1 : 1;}
return 0;
}
public void sort(ArrayList<SiteScoreR> list){
if(list==null || list.size()<2){return;}
Shared.sort(list, this);
}
public void sort(SiteScoreR[] list){
if(list==null || list.length<2){return;}
Arrays.sort(list, this);
}
}
public static final PositionComparator PCOMP=new PositionComparator();
public static final NormalizedComparator NCOMP=new NormalizedComparator();
public static final IDComparator IDCOMP=new IDComparator();
public int reflen(){return stop-start+1;}
public int start;
public int stop;
public int readlen;
public int score;
public int pairedScore;
public final int chrom;
public final byte strand;
public boolean perfect;
public boolean semiperfect;
public final long numericID;
public final byte pairnum;
public float normalizedScore;
// public int weight=0; //Temp variable, for calculating normalized score
public boolean correct=false;
public int retainVotes=0;
}
| gpl-3.0 |
david-alan/wealthbot | system/Model/Pas/Transaction.php | 4596 | <?php
namespace Model\Pas;
class Transaction extends Base
{
const TRANSACTION_CODE_BUY = 'BUY';
const TRANSACTION_CODE_SELL = 'SELL';
const TRANSACTION_CODE_MFEE = 'MFEE';
const TRANSACTION_CODE_MF = 'IDA12';
const CLOSING_METHOD_NAME = 'None';
protected $lotId;
protected $accountId;
protected $securityId;
protected $closingMethodId;
protected $transactionTypeId;
protected $netAmount;
protected $grossAmount;
protected $qty;
protected $txDate;
protected $settleDate;
protected $accruedInterest;
protected $notes;
protected $cancelStatus;
protected $status;
protected $transactionCode;
public function __construct()
{
$this->status = 'verified';
}
public function isCreateLot()
{
return ($this->transactionCode == self::TRANSACTION_CODE_BUY || $this->transactionCode == self::TRANSACTION_CODE_SELL);
}
public function isMFEE()
{
return $this->transactionCode == self::TRANSACTION_CODE_MFEE;
}
/**
* @param string $transactionCode
* @return $this
*/
public function setTransactionCode($transactionCode)
{
$this->transactionCode = $transactionCode;
return $this;
}
/**
* @return float
*/
public function getTransactionCode()
{
return $this->transactionCode;
}
public function setStatus($status)
{
$this->status = $status;
return $this;
}
public function getStatus()
{
return $this->status;
}
public function setCancelStatus($cancelStatus)
{
$this->cancelStatus = $cancelStatus;
return $this;
}
public function getCancelStatus()
{
return $this->cancelStatus;
}
public function setNotes($notes)
{
$this->notes = $notes;
return $this;
}
public function getNotes()
{
return $this->notes;
}
public function setAccruedInterest($accruedInterest)
{
$this->accruedInterest = $accruedInterest;
return $this;
}
public function getAccruedInterest()
{
return $this->accruedInterest;
}
public function setSettleDate($settleDate)
{
$this->settleDate = $settleDate;
return $this;
}
public function getSettleDate()
{
return $this->settleDate;
}
public function setTxDate($txDate)
{
$this->txDate = $txDate;
return $this;
}
public function getTxDate()
{
return $this->txDate;
}
public function getTxDateAsDateTime()
{
return new \DateTime($this->txDate);
}
public function setQty($qty)
{
$this->qty = $qty;
return $this;
}
public function getQty()
{
return $this->qty;
}
public function setGrossAmount($grossAmount)
{
$this->grossAmount = $grossAmount;
return $this;
}
public function getGrossAmount()
{
return $this->grossAmount;
}
public function setNetAmount($netAmount)
{
$this->netAmount = $netAmount;
return $this;
}
public function getNetAmount()
{
return (float) $this->netAmount;
}
public function setLotId($lotId)
{
$this->lotId = $lotId;
return $this;
}
public function getLotId()
{
return $this->lotId;
}
public function setAccountId($accountId)
{
$this->accountId = $accountId;
return $this;
}
public function getAccountId()
{
return $this->accountId;
}
public function setSecurityId($securityId)
{
$this->securityId = $securityId;
return $this;
}
public function getSecurityId()
{
return $this->securityId;
}
public function setClosingMethodId($closingMethodId)
{
$this->closingMethodId = $closingMethodId;
return $this;
}
public function getClosingMethodId()
{
return $this->closingMethodId;
}
public function setTransactionTypeId($transactionTypeId)
{
$this->transactionTypeId = $transactionTypeId;
return $this;
}
public function getTransactionTypeId()
{
return $this->transactionTypeId;
}
} | gpl-3.0 |
Neticle/lumina-php-framework | framework/system/web/session/Session.php | 7332 | <?php
// =============================================================================
//
// Copyright 2013 Neticle
// http://lumina.neticle.com
//
// This file is part of "Lumina/PHP Framework", hereafter referred to as
// "Lumina".
//
// Lumina 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.
//
// Lumina 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 theGNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// "Lumina". If not, see <http://www.gnu.org/licenses/>.
//
// =============================================================================
namespace system\web\session;
use \system\base\Component;
use \system\core\exception\RuntimeException;
use \system\web\session\ISessionSaveHandler;
/**
* The session component allows you to keep track of the user state
* persistently across multiple requests.
*
* @author Lumina Framework <lumina@incubator.neticle.com>
* @since 0.2.0
*/
abstract class Session extends Component
{
/**
* The total number of initialized session handlers.
*
* @type int
*/
private static $instanceCount = 0;
/**
* The session name.
*
* @type string
*/
private $name = 'LPSESSID';
/**
* When set to TRUE this session component will be registered as the
* global PHP session handler and session will be automatically started
* during it's initialization.
*
* @type bool
*/
private $register = true;
/**
* When set to TRUE along with 'register', the session will be started
* during the component initialization.
*
* @type bool
*/
private $start = true;
/**
* Extends the base behavior by optionally define this component as
* the global PHP session handler.
*
* If this component implements the \SessionHandlerInterface it will be
* registered as PHP's session handler and, as such, you should never
* create multiple instances of this component unless you set the
* 'register' property to FALSE.
*
* @return bool
* Returns TRUE to continue the event, FALSE otherwise.
*/
protected function onInitialize()
{
if (parent::onInitialize())
{
if (self::$instanceCount > 0)
{
throw new RuntimeException('Another session component has already been initialized.');
}
++self::$instanceCount;
if ($this instanceof ISessionSaveHandler)
{
session_set_save_handler
(
[ $this, 'openSessionStore' ],
[ $this, 'closeSessionStore' ],
[ $this, 'readSessionData' ],
[ $this, 'writeSessionData' ],
[ $this, 'destroySessionData' ],
[ $this, 'purgeSessionData' ]
);
}
if ($this->start)
{
$this->start();
}
return true;
}
return false;
}
/**
* Returns the session name, which is used in cookies and query string
* parameters to identify the session.
*
* @return string
* The session name.
*/
public function getName()
{
return $this->name;
}
/**
* Defines the session name, which is used in cookies and query string
* parameters to identify the session.
*
* @param string $name
* The session name.
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Starts the current session.
*
* @throws RuntimeException
* Thrown if the session fails to start.
*/
public function start()
{
session_name($this->name);
session_start();
}
/**
* Regenerates the current session.
*
* @param bool $reset
* When set to TRUE the current session data will be removed during
* the regeneration process.
*/
public function regenerate($reset = false)
{
if ($reset)
{
$_SESSION = [];
}
if (!session_regenerate_id(true))
{
throw new RuntimeException('Unable to regenerate the current session.');
}
}
/**
* Destroys any data that belongs to the current session.
*
* @throws RuntimeException
* Thrown when the session fails to be destroyed.
*/
public function destroy()
{
if (!session_destroy())
{
throw new RuntimeException('Unable to destroy the current session.');
}
}
/**
* Flushes and closes the current session.
*
* @throws RuntimeException
* Thrown when the session fails to be closed.
*/
public function close()
{
session_write_close();
}
/**
* Checks wether or not the current session is closed.
*
* @return bool
* Returns TRUE if the session is closed, FALSE otherwise.
*/
public function isClosed()
{
return session_status() !== PHP_SESSION_ACTIVE;
}
/**
* Reads a value from persistent storage.
*
* @param string $key
* The unique value identifier.
*
* @param mixed $default
* A value to be returned by default, when the specified
* key is not definined within the persistent storage.
*
* @return mixed
* The stored value if available, or '$default' otherwise.
*/
public function read($key, $default = null)
{
return isset($_SESSION[$key]) ?
$_SESSION[$key] : $default;
}
/**
* Write a value to persistent storage.
*
* @param string $key
* The unique identifier of the value to define or update.
*
* @param mixed $value
* The value to define the given key with.
*/
public function write($key, $value)
{
$_SESSION[$key] = $value;
}
/**
* Pushes a value to an array stored in session, by key.
*
* @param string $key
* The unique identifier of the value being modified.
*
* @param mixed $value
* The value to push.
*/
public function push($key, $value)
{
if (isset($_SESSION[$key]) && !is_array($_SESSION[$key]))
{
throw new RuntimeException('The specified key "' . $key . '" is not defined as an array.');
}
$_SESSION[$key][] = $value;
}
/**
* Checks wether or not the specified key is defined.
*
* @param string $key
* The key to be verified.
*
* @return bool
* Returns TRUE if the key is defined, FALSE otherwise.
*/
public function contains($key)
{
return isset($_SESSION[$key]);
}
/**
* Clears a session attribute.
*
* @param string $key
* The key to clear from the session.
*/
public function clear($key)
{
unset($_SESSION[$key]);
}
/**
* Returns an key value from the session.
*
* @param string $key
* The key name.
*
* @return mixed
* The key value, or NULL if it's not defined.
*/
public function __get($key)
{
return $this->read($key);
}
/**
* Defines a session key value.
*
* @param string $key
* The key name.
*
* @param mixed $value
* The value to define.
*/
public function __set($key, $value)
{
$this->write($key, $value);
}
/**
* Checks wether or not the specified key is defined.
*
* @param string $key
* The key to be verified.
*
* @return bool
* Returns TRUE if the key is defined, FALSE otherwise.
*/
public function __isset($key)
{
return $this->contains($key);
}
/**
* Clears a session attribute.
*
* @param string $key
* The key to be cleared from the session.
*/
public function __unset($key)
{
return $this->clear($key);
}
}
| gpl-3.0 |
tranleduy2000/javaide | aosp/gradle/src/main/java/com/android/build/gradle/internal/dependency/LibraryDependencyImpl.java | 5033 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.dependency;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.annotations.concurrency.Immutable;
import com.android.builder.dependency.LibraryBundle;
import com.android.builder.dependency.LibraryDependency;
import com.android.builder.dependency.ManifestDependency;
import com.android.builder.model.AndroidLibrary;
import com.android.builder.model.MavenCoordinates;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.io.File;
import java.util.Collections;
import java.util.List;
@Immutable
public class LibraryDependencyImpl extends LibraryBundle {
@NonNull
private final List<LibraryDependency> dependencies;
@Nullable
private final String variantName;
@Nullable
private final MavenCoordinates requestedCoordinates;
@Nullable
private final MavenCoordinates resolvedCoordinates;
private final boolean isOptional;
public LibraryDependencyImpl(
@NonNull File bundle,
@NonNull File explodedBundle,
@NonNull List<LibraryDependency> dependencies,
@Nullable String name,
@Nullable String variantName,
@Nullable String projectPath,
@Nullable MavenCoordinates requestedCoordinates,
@Nullable MavenCoordinates resolvedCoordinates,
boolean isOptional) {
super(bundle, explodedBundle, name, projectPath);
this.dependencies = dependencies;
this.variantName = variantName;
this.requestedCoordinates = requestedCoordinates;
this.resolvedCoordinates = resolvedCoordinates;
this.isOptional = isOptional;
}
@NonNull
@Override
public List<? extends AndroidLibrary> getLibraryDependencies() {
return dependencies;
}
@Override
@NonNull
public List<LibraryDependency> getDependencies() {
return dependencies;
}
@Override
@NonNull
public List<? extends ManifestDependency> getManifestDependencies() {
return dependencies;
}
@Nullable
@Override
public String getProjectVariant() {
return variantName;
}
@Nullable
@Override
public MavenCoordinates getRequestedCoordinates() {
return requestedCoordinates;
}
@Nullable
@Override
public MavenCoordinates getResolvedCoordinates() {
return resolvedCoordinates;
}
@Override
public boolean isOptional() {
return isOptional;
}
/**
* Returns a version of the library dependency with the dependencies removed.
*/
@NonNull
public LibraryDependencyImpl getNonTransitiveRepresentation() {
return new LibraryDependencyImpl(
getBundle(),
getBundleFolder(),
Collections.<LibraryDependency>emptyList(),
getName(),
variantName,
getProject(),
requestedCoordinates,
resolvedCoordinates,
isOptional);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
LibraryDependencyImpl that = (LibraryDependencyImpl) o;
return Objects.equal(dependencies, that.dependencies) &&
Objects.equal(variantName, that.variantName) &&
Objects.equal(resolvedCoordinates, that.resolvedCoordinates) &&
Objects.equal(isOptional, that.isOptional());
}
@Override
public int hashCode() {
return Objects.hashCode(
super.hashCode(),
dependencies,
variantName,
resolvedCoordinates,
isOptional);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("dependencies", dependencies)
.add("variantName", variantName)
.add("requestedCoordinates", requestedCoordinates)
.add("resolvedCoordinates", resolvedCoordinates)
.add("isOptional", isOptional)
.add("super", super.toString())
.toString();
}
}
| gpl-3.0 |
RickyNotaro/CakePOS | tests/TestCase/Controller/TransactionsControllerTest.php | 1363 | <?php
namespace App\Test\TestCase\Controller;
use App\Controller\TransactionsController;
use Cake\TestSuite\IntegrationTestCase;
/**
* App\Controller\TransactionsController Test Case
*/
class TransactionsControllerTest extends IntegrationTestCase
{
/**
* Fixtures
*
* @var array
*/
public $fixtures = [
'app.transactions',
'app.customers',
'app.sales_outlets',
'app.staffs',
'app.products',
'app.products_transactions'
];
/**
* Test index method
*
* @return void
*/
public function testIndex()
{
$this->markTestIncomplete('Not implemented yet.');
}
/**
* Test view method
*
* @return void
*/
public function testView()
{
$this->markTestIncomplete('Not implemented yet.');
}
/**
* Test add method
*
* @return void
*/
public function testAdd()
{
$this->markTestIncomplete('Not implemented yet.');
}
/**
* Test edit method
*
* @return void
*/
public function testEdit()
{
$this->markTestIncomplete('Not implemented yet.');
}
/**
* Test delete method
*
* @return void
*/
public function testDelete()
{
$this->markTestIncomplete('Not implemented yet.');
}
}
| gpl-3.0 |
lancelothk/BSPAT | BSPAT/test/edu/cwru/cbc/BSPAT/DataType/SequenceTest.java | 3442 | package edu.cwru.cbc.BSPAT.DataType;
import java.lang.reflect.InvocationTargetException;
import static org.testng.AssertJUnit.assertEquals;
public class SequenceTest {
@org.junit.Test
public void testProcessSequence() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String ref = "AAACATCTCTAATGAGGGAGGAGGCCCGAGGATGGCTGGGTTTGATTTATGACTGGAGGAGAAGGTCCACTTCCCACTGCGAAGCAGGCGACCTGCTC";
Sequence seq1 = new Sequence("1", "TOP", "test", 0,
"AAATATTTTTAATGAGGGAGGAGGTTTGAGGATGGTTGGGTTTGATTTATGATTGGAGGAGAAGGCTTATTTTTTATTGAGAAGTAGGCGATTTGTTC");
Sequence seq2 = new Sequence("2", "TOP", "test", 0,
"AAATATTTTTAATGAGGGAGGAGGTTTGAGGATGGTTGGGTTTGATTTATGATTGGAGGAGAAGGTCTATTTTTTATTGTGAAGTAGGTAATTTGTTT");
Sequence seq3 = new Sequence("3", "BOTTOM", "test", 0,
"AAACATCTCTAATAAAAAAAAAAACCCGAAAATAACTAAATTTAATTTATAACTAAAAAAACAAATCCACTTCCCACTACGAAACAAACGACCTGCTC");
seq1.addCpG(new CpGSite(26, false));
seq1.addCpG(new CpGSite(79, true));
seq1.addCpG(new CpGSite(88, false));
seq1.processSequence(ref);
seq2.addCpG(new CpGSite(26, false));
seq2.addCpG(new CpGSite(79, true));
seq2.addCpG(new CpGSite(88, true));
seq2.processSequence(ref);
seq3.addCpG(new CpGSite(26, true));
seq3.addCpG(new CpGSite(79, false));
seq3.addCpG(new CpGSite(88, true));
seq3.processSequence(ref);
assertEquals("sequence identity not equal for seq 1!", 0.978, seq1.getSequenceIdentity(), 0.001);
assertEquals("sequence identity not equal for seq 2!", 0.989, seq2.getSequenceIdentity(), 0.001);
assertEquals("sequence identity not equal for seq 3!", 0.989, seq3.getSequenceIdentity(), 0.001);
assertEquals("bisulfite conversion rate not equal for seq 1!", 0.947, seq1.getBisulConversionRate(),
0.001);
assertEquals("bisulfite conversion rate not equal for seq 2!", 0.947, seq2.getBisulConversionRate(),
0.001);
assertEquals("bisulfite conversion rate not equal for seq 3!", 0.965, seq3.getBisulConversionRate(),
0.001);
assertEquals(
"--------------------------**---------------------------------------------------@@-------**--------",
seq1.getMethylationString());
assertEquals(
"--------------------------**---------------------------------------------------@@-------@@--------",
seq2.getMethylationString());
assertEquals(
"--------------------------@@---------------------------------------------------**-------@@--------",
seq3.getMethylationString());
String beginningPartialCpGRef = "CGAAG";
Sequence seqBPTop = new Sequence("1", "TOP", "test", 1, "GAAG");
Sequence seqBPBottom = new Sequence("1", "BOTTOM", "test", 1, "GAAG");
seqBPTop.addCpG(new CpGSite(0, true));
seqBPBottom.addCpG(new CpGSite(0, false));
seqBPTop.processSequence(beginningPartialCpGRef);
seqBPBottom.processSequence(beginningPartialCpGRef);
assertEquals("@---", seqBPTop.getMethylationString());
assertEquals("*---", seqBPBottom.getMethylationString());
String endPartialCpGRef = "GGAACG";
Sequence seqEPTop = new Sequence("1", "TOP", "test", 0, "GGAAC");
Sequence seqEPBottom = new Sequence("1", "BOTTOM", "test", 0, "AAAAC");
seqEPTop.addCpG(new CpGSite(4, true));
seqEPBottom.addCpG(new CpGSite(4, false));
seqEPTop.processSequence(endPartialCpGRef);
seqEPBottom.processSequence(endPartialCpGRef);
assertEquals("----@", seqEPTop.getMethylationString());
assertEquals("----*", seqEPBottom.getMethylationString());
}
} | gpl-3.0 |
Nebo15/gandalf.api | app/Listeners/EventListener.php | 1982 | <?php
/**
* Author: Paul Bardack paul.bardack@gmail.com http://paulbardack.com
* Date: 08.11.15
* Time: 12:15
*/
namespace App\Listeners;
use App\Events\Users;
use App\Events\Decisions;
use App\Services\Intercom;
use App\Services\Mixpanel;
use Nebo15\LumenApplicationable\Models\Application;
class EventListener
{
private $intercom;
private $mixpanel;
public function __construct(Intercom $intercom, Mixpanel $mixpanel)
{
$this->intercom = $intercom;
$this->mixpanel = $mixpanel;
}
public function decisionMake(Decisions\Make $event)
{
$apps = Application::where('_id', $event->decision->application)
->where('users.role', 'admin')
->get(['users.user_id', 'users.role']);
$userIds = [];
foreach ($apps as $app) {
foreach ($app->users as $user) {
if ($user->role == 'admin') {
$userIds[] = strval($user->user_id);
}
}
}
$this->intercom->decisionMake($event->decision, $userIds);
$this->mixpanel->decisionMake($event->decision, $userIds);
}
public function userCreate(Users\Create $event)
{
$this->mixpanel->userCreate($event->user);
$this->intercom->userCreateOrUpdate($event->user);
}
public function userUpdate(Users\Update $event)
{
$this->mixpanel->userUpdate($event->user);
$this->intercom->userCreateOrUpdate($event->user);
}
/**
* Register the listeners for the subscriber.
*
* @param \Illuminate\Events\Dispatcher $events
* @return array
*/
public function subscribe($events)
{
$events->listen('App\Events\Decisions\Make', 'App\Listeners\EventListener@decisionMake');
$events->listen('App\Events\Users\Create', 'App\Listeners\EventListener@userCreate');
$events->listen('App\Events\Users\Update', 'App\Listeners\EventListener@userUpdate');
}
}
| gpl-3.0 |
dreamer-dead/falltergeist | src/VM/Handlers/Opcode8044Handler.cpp | 1618 | /*
* Copyright 2012-2015 Falltergeist Developers.
*
* This file is part of Falltergeist.
*
* Falltergeist 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.
*
* Falltergeist 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 Falltergeist. If not, see <http://www.gnu.org/licenses/>.
*/
// C++ standard includes
// Falltergeist includes
#include "../../Logger.h"
#include "../../VM/Handlers/Opcode8044Handler.h"
#include "../../VM/VM.h"
#include "../../VM/VMStackValue.h"
// Third party includes
namespace Falltergeist
{
Opcode8044Handler::Opcode8044Handler(VM* vm) : OpcodeHandler(vm)
{
}
void Opcode8044Handler::_run()
{
Logger::debug("SCRIPT") << "[8044] [*] op_floor" << std::endl;
auto value = _vm->dataStack()->pop();
int result = 0;
if (value.type() == VMStackValue::TYPE_FLOAT)
{
result = (int)value.floatValue(); // this is how "floor" originally worked..
}
else if (value.type() == VMStackValue::TYPE_INTEGER)
{
result = value.integerValue();
}
else
{
_error(std::string("op_floor: invalid argument type: ") + value.typeName());
}
_vm->dataStack()->push(result);
}
}
| gpl-3.0 |
Ensembles/ert | python/tests/core/ecl/test_rft_statoil.py | 4639 | #!/usr/bin/env python
# Copyright (C) 2011 Statoil ASA, Norway.
#
# The file 'test_rft_statoil.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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.
#
# ERT 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.
from __future__ import print_function
import datetime
from ert.ecl import EclRFTFile, EclRFTCell, EclPLTCell
from ert.ecl.rft import WellTrajectory
from ert.test import ExtendedTestCase
class RFTTest(ExtendedTestCase):
def setUp(self):
self.RFT_file = self.createTestPath("Statoil/ECLIPSE/Gurbat/ECLIPSE.RFT")
self.PLT_file = self.createTestPath("Statoil/ECLIPSE/RFT/TEST1_1A.RFT")
def test_RFT_load( self ):
rftFile = EclRFTFile(self.RFT_file)
rft = rftFile[0]
cell = rft.ijkget((32, 53, 0))
self.assertIsInstance(cell, EclRFTCell)
self.assertEqual(2, rftFile.size())
self.assertEqual(0, rftFile.size(well="OP*"))
self.assertEqual(0, rftFile.size(well="XXX"))
self.assertEqual(1, rftFile.size(date=datetime.date(2000, 6, 1)))
self.assertEqual(0, rftFile.size(date=datetime.date(2000, 6, 17)))
cell = rft.ijkget((30, 20, 1880))
self.assertIsNone(cell)
for rft in rftFile:
self.assertTrue(rft.is_RFT())
self.assertFalse(rft.is_SEGMENT())
self.assertFalse(rft.is_PLT())
self.assertFalse(rft.is_MSW())
for cell in rft:
self.assertIsInstance(cell, EclRFTCell)
cell0 = rft.iget_sorted(0)
self.assertIsInstance(cell, EclRFTCell)
rft.sort()
for h in rftFile.getHeaders():
print(h)
self.assertIsInstance( h[1] , datetime.date )
def test_PLT_load( self ):
pltFile = EclRFTFile(self.PLT_file)
plt = pltFile[11]
self.assertTrue(plt.is_PLT())
self.assertFalse(plt.is_SEGMENT())
self.assertFalse(plt.is_RFT())
self.assertFalse(plt.is_MSW())
for cell in plt:
self.assertIsInstance(cell, EclPLTCell)
def test_exceptions( self ):
with self.assertRaises(IndexError):
rftFile = EclRFTFile(self.RFT_file)
rft = rftFile[100]
def test_trajectory(self):
with self.assertRaises(IOError):
WellTrajectory("/does/no/exist")
with self.assertRaises(UserWarning):
WellTrajectory( self.createTestPath("Statoil/ert-statoil/spotfire/gendata_rft_zone/invalid_float.txt") )
with self.assertRaises(UserWarning):
WellTrajectory( self.createTestPath("Statoil/ert-statoil/spotfire/gendata_rft_zone/missing_item.txt") )
wt = WellTrajectory( self.createTestPath("Statoil/ert-statoil/spotfire/gendata_rft_zone/E-3H.txt") )
self.assertEqual( len(wt) , 38)
with self.assertRaises(IndexError):
p = wt[38]
p0 = wt[0]
self.assertEqual( p0.utm_x , 458920.671 )
self.assertEqual( p0.utm_y , 7324939.077 )
self.assertEqual( p0.measured_depth , 2707.5000 )
pm1 = wt[-1]
p37 = wt[37]
self.assertEqual( p37 , pm1)
def test_PLT(self):
rft_file = EclRFTFile( self.createTestPath("Statoil/ECLIPSE/Heidrun/RFT/2C3_MR61.RFT"))
rft0 = rft_file[0]
rft1 = rft_file[1]
rft2 = rft_file[2]
rft3 = rft_file[3]
self.assertTrue( rft0.is_RFT() )
self.assertTrue( rft1.is_RFT() )
self.assertTrue( rft2.is_PLT() )
self.assertTrue( rft3.is_PLT() )
self.assertEqual( len(rft0) , 42 )
self.assertEqual( len(rft1) , 37 )
self.assertEqual( len(rft2) , 42 )
self.assertEqual( len(rft3) , 37 )
self.assertFloatEqual( rft0[0].pressure , 0.22919502E+03 )
self.assertFloatEqual( rft0[0].depth , 0.21383721E+04)
self.assertFloatEqual( rft1[0].pressure , 0.22977950E+03 )
self.assertFloatEqual( rft1[0].depth , 0.21384775E+04 )
self.assertFloatEqual( rft2[0].pressure , 0.19142435E+03 )
self.assertFloatEqual( rft2[0].depth , 0.21383721E+04 )
| gpl-3.0 |
patilswapnilv/shortcodely | tests/phpunit/tests/image/editor_imagick.php | 14562 | <?php
/**
* Test the WP_Image_Editor_Imagick class
*
* @group image
* @group media
* @group wp-image-editor-imagick
*/
require_once dirname(__FILE__) . '/base.php';
class Tests_Image_Editor_Imagick extends WP_Image_UnitTestCase
{
public $editor_engine = 'WP_Image_Editor_Imagick';
public function setUp()
{
include_once ABSPATH . WPINC . '/class-wp-image-editor.php';
include_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
parent::setUp();
}
public function tearDown()
{
$folder = DIR_TESTDATA . '/images/waffles-*.jpg';
foreach ( glob($folder) as $file ) {
unlink($file);
}
$this->remove_added_uploads();
parent::tearDown();
}
/**
* Check support for ImageMagick compatible mime types.
*/
public function test_supports_mime_type()
{
$imagick_image_editor = new WP_Image_Editor_Imagick(null);
$this->assertTrue($imagick_image_editor->supports_mime_type('image/jpeg'), 'Does not support image/jpeg');
$this->assertTrue($imagick_image_editor->supports_mime_type('image/png'), 'Does not support image/png');
$this->assertTrue($imagick_image_editor->supports_mime_type('image/gif'), 'Does not support image/gif');
}
/**
* Test resizing an image, not using crop
*/
public function test_resize()
{
$file = DIR_TESTDATA . '/images/waffles.jpg';
$imagick_image_editor = new WP_Image_Editor_Imagick($file);
$imagick_image_editor->load();
$imagick_image_editor->resize(100, 50);
$this->assertEquals(
array(
'width' => 75,
'height' => 50,
),
$imagick_image_editor->get_size()
);
}
/**
* Test multi_resize with single image resize and no crop
*/
public function test_single_multi_resize()
{
$file = DIR_TESTDATA . '/images/waffles.jpg';
$imagick_image_editor = new WP_Image_Editor_Imagick($file);
$imagick_image_editor->load();
$sizes_array = array(
array(
'width' => 50,
'height' => 50,
),
);
$resized = $imagick_image_editor->multi_resize($sizes_array);
// First, check to see if returned array is as expected
$expected_array = array(
array(
'file' => 'waffles-50x33.jpg',
'width' => 50,
'height' => 33,
'mime-type' => 'image/jpeg',
),
);
$this->assertEquals($expected_array, $resized);
// Now, verify real dimensions are as expected
$image_path = DIR_TESTDATA . '/images/'. $resized[0]['file'];
$this->assertImageDimensions(
$image_path,
$expected_array[0]['width'],
$expected_array[0]['height']
);
}
/**
* Ensure multi_resize doesn't create an image when
* both height and weight are missing, null, or 0.
*
* ticket 26823
*/
public function test_multi_resize_does_not_create()
{
$file = DIR_TESTDATA . '/images/waffles.jpg';
$imagick_image_editor = new WP_Image_Editor_Imagick($file);
$imagick_image_editor->load();
$sizes_array = array(
array(
'width' => 0,
'height' => 0,
),
array(
'width' => 0,
'height' => 0,
'crop' => true,
),
array(
'width' => null,
'height' => null,
),
array(
'width' => null,
'height' => null,
'crop' => true,
),
array(
'width' => '',
'height' => '',
),
array(
'width' => '',
'height' => '',
'crop' => true,
),
array(
'width' => 0,
),
array(
'width' => 0,
'crop' => true,
),
array(
'width' => null,
),
array(
'width' => null,
'crop' => true,
),
array(
'width' => '',
),
array(
'width' => '',
'crop' => true,
),
);
$resized = $imagick_image_editor->multi_resize($sizes_array);
// If no images are generated, the returned array is empty.
$this->assertEmpty($resized);
}
/**
* Test multi_resize with multiple sizes
*
* ticket 26823
*/
public function test_multi_resize()
{
$file = DIR_TESTDATA . '/images/waffles.jpg';
$imagick_image_editor = new WP_Image_Editor_Imagick($file);
$imagick_image_editor->load();
$sizes_array = array(
/**
* #0 - 10x10 resize, no cropping.
* By aspect, should be 10x6 output.
*/
array(
'width' => 10,
'height' => 10,
'crop' => false,
),
/**
* #1 - 75x50 resize, with cropping.
* Output dimensions should be 75x50
*/
array(
'width' => 75,
'height' => 50,
'crop' => true,
),
/**
* #2 - 20 pixel max height, no cropping.
* By aspect, should be 30x20 output.
*/
array(
'width' => 9999, // Arbitrary High Value
'height' => 20,
'crop' => false,
),
/**
* #3 - 45 pixel max height, with cropping.
* By aspect, should be 45x400 output.
*/
array(
'width' => 45,
'height' => 9999, // Arbitrary High Value
'crop' => true,
),
/**
* #4 - 50 pixel max width, no cropping.
* By aspect, should be 50x33 output.
*/
array(
'width' => 50,
),
/**
* #5 - 55 pixel max width, no cropping, null height
* By aspect, should be 55x36 output.
*/
array(
'width' => 55,
'height' => null,
),
/**
* #6 - 55 pixel max height, no cropping, no width specified.
* By aspect, should be 82x55 output.
*/
array(
'height' => 55,
),
/**
* #7 - 60 pixel max height, no cropping, null width.
* By aspect, should be 90x60 output.
*/
array(
'width' => null,
'height' => 60,
),
/**
* #8 - 70 pixel max height, no cropping, negative width.
* By aspect, should be 105x70 output.
*/
array(
'width' => -9999, // Arbitrary Negative Value
'height' => 70,
),
/**
* #9 - 200 pixel max width, no cropping, negative height.
* By aspect, should be 200x133 output.
*/
array(
'width' => 200,
'height' => -9999, // Arbitrary Negative Value
),
);
$resized = $imagick_image_editor->multi_resize($sizes_array);
$expected_array = array(
// #0
array(
'file' => 'waffles-10x7.jpg',
'width' => 10,
'height' => 7,
'mime-type' => 'image/jpeg',
),
// #1
array(
'file' => 'waffles-75x50.jpg',
'width' => 75,
'height' => 50,
'mime-type' => 'image/jpeg',
),
// #2
array(
'file' => 'waffles-30x20.jpg',
'width' => 30,
'height' => 20,
'mime-type' => 'image/jpeg',
),
// #3
array(
'file' => 'waffles-45x400.jpg',
'width' => 45,
'height' => 400,
'mime-type' => 'image/jpeg',
),
// #4
array(
'file' => 'waffles-50x33.jpg',
'width' => 50,
'height' => 33,
'mime-type' => 'image/jpeg',
),
// #5
array(
'file' => 'waffles-55x37.jpg',
'width' => 55,
'height' => 37,
'mime-type' => 'image/jpeg',
),
// #6
array(
'file' => 'waffles-83x55.jpg',
'width' => 83,
'height' => 55,
'mime-type' => 'image/jpeg',
),
// #7
array(
'file' => 'waffles-90x60.jpg',
'width' => 90,
'height' => 60,
'mime-type' => 'image/jpeg',
),
// #8
array(
'file' => 'waffles-105x70.jpg',
'width' => 105,
'height' => 70,
'mime-type' => 'image/jpeg',
),
// #9
array(
'file' => 'waffles-200x133.jpg',
'width' => 200,
'height' => 133,
'mime-type' => 'image/jpeg',
),
);
$this->assertNotNull($resized);
$this->assertEquals($expected_array, $resized);
foreach( $resized as $key => $image_data ){
$image_path = DIR_TESTDATA . '/images/' . $image_data['file'];
// Now, verify real dimensions are as expected
$this->assertImageDimensions(
$image_path,
$expected_array[$key]['width'],
$expected_array[$key]['height']
);
}
}
/**
* Test resizing an image with cropping
*/
public function test_resize_and_crop()
{
$file = DIR_TESTDATA . '/images/waffles.jpg';
$imagick_image_editor = new WP_Image_Editor_Imagick($file);
$imagick_image_editor->load();
$imagick_image_editor->resize(100, 50, true);
$this->assertEquals(
array(
'width' => 100,
'height' => 50,
),
$imagick_image_editor->get_size()
);
}
/**
* Test cropping an image
*/
public function test_crop()
{
$file = DIR_TESTDATA . '/images/gradient-square.jpg';
$imagick_image_editor = new WP_Image_Editor_Imagick($file);
$imagick_image_editor->load();
$imagick_image_editor->crop(0, 0, 50, 50);
$this->assertEquals(
array(
'width' => 50,
'height' => 50,
),
$imagick_image_editor->get_size()
);
}
/**
* Test rotating an image 180 deg
*/
public function test_rotate()
{
$file = DIR_TESTDATA . '/images/gradient-square.jpg';
$imagick_image_editor = new WP_Image_Editor_Imagick($file);
$imagick_image_editor->load();
$property = new ReflectionProperty($imagick_image_editor, 'image');
$property->setAccessible(true);
$color_top_left = $property->getValue($imagick_image_editor)->getImagePixelColor(1, 1)->getColor();
$imagick_image_editor->rotate(180);
$this->assertEquals($color_top_left, $property->getValue($imagick_image_editor)->getImagePixelColor(99, 99)->getColor());
}
/**
* Test flipping an image
*/
public function test_flip()
{
$file = DIR_TESTDATA . '/images/gradient-square.jpg';
$imagick_image_editor = new WP_Image_Editor_Imagick($file);
$imagick_image_editor->load();
$property = new ReflectionProperty($imagick_image_editor, 'image');
$property->setAccessible(true);
$color_top_left = $property->getValue($imagick_image_editor)->getImagePixelColor(1, 1)->getColor();
$imagick_image_editor->flip(true, false);
$this->assertEquals($color_top_left, $property->getValue($imagick_image_editor)->getImagePixelColor(0, 99)->getColor());
}
/**
* Test the image created with WP_Image_Editor_Imagick preserves alpha when resizing
*
* @ticket 24871
*/
public function test_image_preserves_alpha_on_resize()
{
$file = DIR_TESTDATA . '/images/transparent.png';
$editor = new WP_Image_Editor_Imagick($file);
$this->assertNotInstanceOf('WP_Error', $editor);
$editor->load();
$editor->resize(5, 5);
$save_to_file = tempnam(get_temp_dir(), '') . '.png';
$editor->save($save_to_file);
$im = new Imagick($save_to_file);
$pixel = $im->getImagePixelColor(0, 0);
$expected = $pixel->getColorValue(imagick::COLOR_ALPHA);
$this->assertImageAlphaAtPointImagick($save_to_file, array( 0,0 ), $expected);
unlink($save_to_file);
}
/**
* Test the image created with WP_Image_Editor_Imagick preserves alpha with no resizing etc
*
* @ticket 24871
*/
public function test_image_preserves_alpha()
{
$file = DIR_TESTDATA . '/images/transparent.png';
$editor = new WP_Image_Editor_Imagick($file);
$this->assertNotInstanceOf('WP_Error', $editor);
$editor->load();
$save_to_file = tempnam(get_temp_dir(), '') . '.png';
$editor->save($save_to_file);
$im = new Imagick($save_to_file);
$pixel = $im->getImagePixelColor(0, 0);
$expected = $pixel->getColorValue(imagick::COLOR_ALPHA);
$this->assertImageAlphaAtPointImagick($save_to_file, array( 0,0 ), $expected);
unlink($save_to_file);
}
/**
*
* @ticket 30596
*/
public function test_image_preserves_alpha_on_rotate()
{
$file = DIR_TESTDATA . '/images/transparent.png';
$pre_rotate_editor = new Imagick($file);
$pre_rotate_pixel = $pre_rotate_editor->getImagePixelColor(0, 0);
$pre_rotate_alpha = $pre_rotate_pixel->getColorValue(imagick::COLOR_ALPHA);
$save_to_file = tempnam(get_temp_dir(), '') . '.png';
$pre_rotate_editor->writeImage($save_to_file);
$pre_rotate_editor->destroy();
$image_editor = new WP_Image_Editor_Imagick($save_to_file);
$image_editor->load();
$this->assertNotInstanceOf('WP_Error', $image_editor);
$image_editor->rotate(180);
$image_editor->save($save_to_file);
$this->assertImageAlphaAtPointImagick($save_to_file, array( 0, 0 ), $pre_rotate_alpha);
unlink($save_to_file);
}
}
| gpl-3.0 |
Landric/PANFeed | panfeed/forms.py | 802 | from django.forms import ModelForm, RadioSelect, ChoiceField
from models import Feed, FeedItem, SpecialIssue
class FeedForm(ModelForm):
displayAll = ChoiceField(label='Publishing options', widget=RadioSelect(), choices=[['1','Show all - show all published items and Special Issues'],['0','Show latest - only show the latest published item or Special Issue']], help_text='Don\'t worry, you can change this later if you change your mind')
class Meta:
model = Feed
exclude = ('owner')
fields = ('title', 'description', 'displayAll')
class SpecialIssueForm(ModelForm):
class Meta:
model = SpecialIssue
class FeedItemForm(ModelForm):
class Meta:
model = FeedItem
exclude = ('date', 'feed', 'special_issue', 'issue_position')
| gpl-3.0 |
username1366/growOS | grow.py | 1229 | #!/usr/bin/env python
from functions import *
grow_day_duration = 2
grow_night_duration = 1
chronon = 60
debug = 1
init_time = init()
relay_init()
disable_led()
disable_cool()
disable_pump()
if debug:
diff = 0
while True:
temp, hum = readDHT22()
sqlite_insert_into_sensors(str(temp), str(hum))
print sqlite_retrieve_sensors_last_data()
hour_of_cycle = int(int(time.time() - init_time) / 3600)
print "Current hour is:" + str(hour_of_cycle)
#if mode == 'auto':
# pass
#elif mode == 'manual':
# pass
#else
# mode = 'auto'
if hour_of_cycle >= 0 and hour_of_cycle < grow_day_duration: # DAY
print "Day!"
sqlite_insert_into_log("Day!")
enable_led()
print "LED: enabled"
print hour_of_cycle
elif hour_of_cycle >= grow_day_duration and hour_of_cycle < (grow_day_duration + grow_night_duration):
print "Night!"
sqlite_insert_into_log("Night!")
disable_led()
print "LED: disabled"
print hour_of_cycle
else:
print "New day!"
print hour_of_cycle
sqlite_insert_into_log("New day!")
diff = 0
inc_day_of_grow()
init_time = init(reset = 1)
enable_pump()
print "PUMP: enabled"
time.sleep(2)
disable_pump()
print "PUMP: disabled"
#if debug:
#break
#time.sleep(chronon) | gpl-3.0 |
wookietreiber/arpgt | src/main/scala/Character.scala | 1083 | package rpg
/** Base class for characters.
*
* @tparam A the used attribute type (default attributes of skills)
* @tparam S the used skill type
* @tparam C the character type itself
*/
abstract class Character[A <: Attribute,S <: Skill[A],C <: Character[A,S,C]] {
self: C with Attributes[A] with Skills[A,S] ⇒
/** Returns this characters name. */
def name: String
/** Returns `name`. */
override def toString: String = name
/** Returns the result of a check of a certain aspect of the character.
*
* @tparam X the type aspect that is checked
*
* @param x the aspect of the character to check
* @param C the instance that performs the check
*/
def check[X](x: X)(implicit C: CharacterCheck[X,C]): Result =
C.check(this, x)
/** Returns a value of a certain aspect of the character.
*
* @tparam X the type aspect
*
* @param x the aspect of the character to get
* @param G the instance that performs the get
*/
def get[X](x: X)(implicit G: CharacterGetter[X,C]): Option[Int] =
G.get(this, x)
}
| gpl-3.0 |
mbarcia/drupsible-org | sites/default/files/php/twig/1#c2#1c#8a32167a12229a674921fa3b5f9c3aafdc6ed97cab7e91a92761978bf560/4bcb6d0b78b6b616d62da0f876541fdd1c0627f9eb0540d635da69d36456e0e8.php | 13631 | <?php
/* core/themes/classy/templates/dataset/table.html.twig */
class __TwigTemplate_c21c8a32167a12229a674921fa3b5f9c3aafdc6ed97cab7e91a92761978bf560 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 42
echo "<table";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["attributes"]) ? $context["attributes"] : null), "html", null, true);
echo ">
";
// line 43
if ((isset($context["caption"]) ? $context["caption"] : null)) {
// line 44
echo " <caption>";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["caption"]) ? $context["caption"] : null), "html", null, true);
echo "</caption>
";
}
// line 46
echo "
";
// line 47
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["colgroups"]) ? $context["colgroups"] : null));
foreach ($context['_seq'] as $context["_key"] => $context["colgroup"]) {
// line 48
echo " ";
if ($this->getAttribute($context["colgroup"], "cols", array())) {
// line 49
echo " <colgroup";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["colgroup"], "attributes", array()), "html", null, true);
echo ">
";
// line 50
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["colgroup"], "cols", array()));
foreach ($context['_seq'] as $context["_key"] => $context["col"]) {
// line 51
echo " <col";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["col"], "attributes", array()), "html", null, true);
echo " />
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['col'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 53
echo " </colgroup>
";
} else {
// line 55
echo " <colgroup";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["colgroup"], "attributes", array()), "html", null, true);
echo " />
";
}
// line 57
echo " ";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['colgroup'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 58
echo "
";
// line 59
if ((isset($context["header"]) ? $context["header"] : null)) {
// line 60
echo " <thead>
<tr>
";
// line 62
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["header"]) ? $context["header"] : null));
foreach ($context['_seq'] as $context["_key"] => $context["cell"]) {
// line 63
echo " ";
// line 64
$context["cell_classes"] = array(0 => (($this->getAttribute( // line 65
$context["cell"], "active_table_sort", array())) ? ("is-active") : ("")));
// line 68
echo " <";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "tag", array()), "html", null, true);
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["cell"], "attributes", array()), "addClass", array(0 => (isset($context["cell_classes"]) ? $context["cell_classes"] : null)), "method"), "html", null, true);
echo ">";
// line 69
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "content", array()), "html", null, true);
// line 70
echo "</";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "tag", array()), "html", null, true);
echo ">
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['cell'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 72
echo " </tr>
</thead>
";
}
// line 75
echo "
";
// line 76
if ((isset($context["rows"]) ? $context["rows"] : null)) {
// line 77
echo " <tbody>
";
// line 78
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["rows"]) ? $context["rows"] : null));
$context['loop'] = array(
'parent' => $context['_parent'],
'index0' => 0,
'index' => 1,
'first' => true,
);
if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) {
$length = count($context['_seq']);
$context['loop']['revindex0'] = $length - 1;
$context['loop']['revindex'] = $length;
$context['loop']['length'] = $length;
$context['loop']['last'] = 1 === $length;
}
foreach ($context['_seq'] as $context["_key"] => $context["row"]) {
// line 79
echo " ";
// line 80
$context["row_classes"] = array(0 => (( ! // line 81
(isset($context["no_striping"]) ? $context["no_striping"] : null)) ? (twig_cycle(array(0 => "odd", 1 => "even"), $this->getAttribute($context["loop"], "index0", array()))) : ("")));
// line 84
echo " <tr";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($this->getAttribute($context["row"], "attributes", array()), "addClass", array(0 => (isset($context["row_classes"]) ? $context["row_classes"] : null)), "method"), "html", null, true);
echo ">
";
// line 85
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["row"], "cells", array()));
foreach ($context['_seq'] as $context["_key"] => $context["cell"]) {
// line 86
echo " <";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "tag", array()), "html", null, true);
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "attributes", array()), "html", null, true);
echo ">";
// line 87
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "content", array()), "html", null, true);
// line 88
echo "</";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "tag", array()), "html", null, true);
echo ">
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['cell'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 90
echo " </tr>
";
++$context['loop']['index0'];
++$context['loop']['index'];
$context['loop']['first'] = false;
if (isset($context['loop']['length'])) {
--$context['loop']['revindex0'];
--$context['loop']['revindex'];
$context['loop']['last'] = 0 === $context['loop']['revindex0'];
}
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 92
echo " </tbody>
";
} elseif ( // line 93
(isset($context["empty"]) ? $context["empty"] : null)) {
// line 94
echo " <tbody>
<tr class=\"odd\">
<td colspan=\"";
// line 96
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["header_columns"]) ? $context["header_columns"] : null), "html", null, true);
echo "\" class=\"empty message\">";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["empty"]) ? $context["empty"] : null), "html", null, true);
echo "</td>
</tr>
</tbody>
";
}
// line 100
echo " ";
if ((isset($context["footer"]) ? $context["footer"] : null)) {
// line 101
echo " <tfoot>
";
// line 102
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["footer"]) ? $context["footer"] : null));
foreach ($context['_seq'] as $context["_key"] => $context["row"]) {
// line 103
echo " <tr";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["row"], "attributes", array()), "html", null, true);
echo ">
";
// line 104
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($context["row"], "cells", array()));
foreach ($context['_seq'] as $context["_key"] => $context["cell"]) {
// line 105
echo " <";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "tag", array()), "html", null, true);
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "attributes", array()), "html", null, true);
echo ">";
// line 106
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "content", array()), "html", null, true);
// line 107
echo "</";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["cell"], "tag", array()), "html", null, true);
echo ">
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['cell'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 109
echo " </tr>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['row'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 111
echo " </tfoot>
";
}
// line 113
echo "</table>
";
}
public function getTemplateName()
{
return "core/themes/classy/templates/dataset/table.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 249 => 113, 245 => 111, 238 => 109, 229 => 107, 227 => 106, 222 => 105, 218 => 104, 213 => 103, 209 => 102, 206 => 101, 203 => 100, 194 => 96, 190 => 94, 188 => 93, 185 => 92, 170 => 90, 161 => 88, 159 => 87, 154 => 86, 150 => 85, 145 => 84, 143 => 81, 142 => 80, 140 => 79, 123 => 78, 120 => 77, 118 => 76, 115 => 75, 110 => 72, 101 => 70, 99 => 69, 94 => 68, 92 => 65, 91 => 64, 89 => 63, 85 => 62, 81 => 60, 79 => 59, 76 => 58, 70 => 57, 64 => 55, 60 => 53, 51 => 51, 47 => 50, 42 => 49, 39 => 48, 35 => 47, 32 => 46, 26 => 44, 24 => 43, 19 => 42,);
}
}
| gpl-3.0 |
Brazelton-Lab/bio_utils | bio_utils/verifiers/fastq.py | 4694 | #! /usr/bin/env python3
from __future__ import print_function
"""Verifies a FASTQ file
Usage:
fastq_verifier <FASTQ File> [--quiet]
Copyright:
fastq.py verify validity of a FASTQ file
Copyright (C) 2015 William Brazelton, Alex Hyer
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 argparse
from bio_utils.iterators import fastq_iter
from bio_utils.verifiers import entry_verifier
from bio_utils.verifiers import FormatError
import os
import sys
__author__ = 'Alex Hyer'
__email__ = 'theonehyer@gmail.com'
__license__ = 'GPLv3'
__maintainer__ = 'Alex Hyer'
__status__ = 'Production'
__version__ = '2.0.2'
# noinspection PyTypeChecker
def fastq_verifier(entries, ambiguous=False):
"""Raises error if invalid FASTQ format detected
Args:
entries (list): A list of FastqEntry instances
ambiguous (bool): Permit ambiguous bases, i.e. permit non-ACGTU bases
Raises:
FormatError: Error when FASTQ format incorrect with descriptive message
Example:
>>> from bio_utils.iterators import fastq_iter
>>> import os
>>> entries = r'@entry1{0}AAGGATTCG{0}+{0}112234432{0}' \
... r'@entry{0}AGGTCCCCCG{0}+{0}4229888884{0}' \
... r'@entry3{0}GCCTAGC{0}9ddsa5n'.format(os.linesep)
>>> fastq_entries = fastq_iter(iter(entries.split(os.linesep)))
>>> fastq_verifier(fastq_entries)
"""
if ambiguous:
regex = r'^@.+{0}[ACGTURYKMSWBDHVNX]+{0}' \
r'\+.*{0}[!"#$%&\'()*+,-./0123456' \
r'789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
r'[\]^_`abcdefghijklmnopqrstuvwxyz' \
r'{{|}}~]+{0}$'.format(os.linesep)
else:
regex = r'^@.+{0}[ACGTU]+{0}' \
r'\+.*{0}[!-~]+{0}$'.format(os.linesep)
delimiter = r'{0}'.format(os.linesep)
for entry in entries:
if len(entry.sequence) != len(entry.quality):
msg = 'The number of bases in {0} does not match the number ' \
'of quality scores'.format(entry.id)
raise FormatError(message=msg)
try:
entry_verifier([entry.write()], regex, delimiter)
except FormatError as error:
if error.part == 0:
msg = 'Unknown Header Error with {0}'.format(entry.id)
raise FormatError(message=msg)
elif error.part == 1 and ambiguous:
msg = '{0} contains a base not in ' \
'[ACGTURYKMSWBDHVNX]'.format(entry.id)
raise FormatError(message=msg)
elif error.part == 1 and not ambiguous:
msg = '{0} contains a base not in ' \
'[ACGTU]'.format(entry.id)
raise FormatError(message=msg)
elif error.part == 2:
msg = 'Unknown error with line 3 of {0}'.format(entry.id)
raise FormatError(message=msg)
elif error.part == 3:
msg = r'{0} contains a quality score not in ' \
r'[!-~]'.format(entry.id)
raise FormatError(message=msg)
else:
msg = '{0}: Unknown Error: Likely a Bug'.format(entry.id)
raise FormatError(message=msg)
def main():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.
RawDescriptionHelpFormatter)
parser.add_argument('fastq',
help='FASTQ file to verify [Default: STDIN]',
type=argparse.FileType('rU'),
default=sys.stdin)
parser.add_argument('-q', '--quiet',
help='Suppresses message when file is good',
action='store_false')
args = parser.parse_args()
for entry in fastq_iter(args.fastq):
fastq_verifier([entry])
if not args.quiet:
print('{0} is valid'.format(args.fastq.name)) # Prints if no error
if __name__ == '__main__':
main()
sys.exit(0)
| gpl-3.0 |
chandraknight/YatriNepal | resources/views/frontend/layouts/ProductDetails/SimilarArea.blade.php | 2711 | <!--Similar Area Start-->
<div class="similar-area section-grey section-padding">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-title text-center">
<div class="title-border">
<h1>Similar <span>Trips</span></h1>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque dolor turpis, pulvinar varius dui<br> id, convallis iaculis eros. Praesent porta lacinia elementum.</p>
</div>
</div>
</div>
<div class="row">
@foreach( $similar_itinerary as $similar_itinerary)
<div class="col-md-4 col-sm-6">
<div class="single-adventure no-margin">
<a href="{{ route('details', ['slug' => $similar_itinerary->slug]) }}"><img alt="" src="../img/adventure-list/8.jpg"></a>
<div class="adventure-text effect-bottom">
<div class="transparent-overlay">
<h4><a href="{{ route('details', ['slug' => $similar_itinerary->slug]) }}">{{ $similar_itinerary->title }} | <span>{{ $similar_itinerary->country->title }}</span></a></h4>
<span class="trip-time"><i class="fa fa-clock-o"></i>{{ $similar_itinerary->trip_duration }}Trip</span>
<span class="trip-level"><i class="fa fa-send-o"></i>Level: {{ $similar_itinerary->trekking_grade }}</span>
{{--<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ornare ut est in molestie. Vestibulum convallis congue velit, et facilisis lorem efficitur et. Morbi vitae pellentesque nulla. </p>--}}
</div>
<div class="adventure-price-link">
<span class="trip-price">${{ $similar_itinerary->cost }}</span>
<span class="trip-person"> Per Person</span>
<div class="adventure-link">
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-google-plus"></i></a>
<a href="#"><i class="fa fa-linkedin"></i></a>
<a href="#"><i class="fa fa-rss"></i></a>
</div>
</div>
</div>
</div>
</div>
@endforeach
</div>
</div>
</div>
<!--End of Similar Area--> | gpl-3.0 |
Graylog2/graylog2-server | full-backend-tests/src/test/java/org/graylog/elasticsearch/e2e/ElasticsearchE2EES6.java | 1352 | /*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
package org.graylog.elasticsearch.e2e;
import io.restassured.specification.RequestSpecification;
import org.graylog.storage.elasticsearch6.ElasticsearchInstanceES6Factory;
import org.graylog.testing.completebackend.ApiIntegrationTest;
import org.graylog.testing.completebackend.GraylogBackend;
import static org.graylog.testing.completebackend.Lifecycle.CLASS;
@ApiIntegrationTest(serverLifecycle = CLASS, extraPorts = {ElasticsearchE2E.GELF_HTTP_PORT}, elasticsearchFactory = ElasticsearchInstanceES6Factory.class)
public class ElasticsearchE2EES6 extends ElasticsearchE2E {
public ElasticsearchE2EES6(GraylogBackend sut, RequestSpecification requestSpec) {
super(sut, requestSpec);
}
}
| gpl-3.0 |
erudit/zenon | eruditorg/erudit/test/solr.py | 12135 | from collections import Counter
from itertools import chain
from operator import attrgetter
from typing import Dict, List, Tuple
from luqum.tree import (
AndOperation,
BaseOperation,
FieldGroup,
Group,
OrOperation,
Plus,
SearchField,
UnknownOperation,
)
from luqum.parser import parser
from erudit.solr.models import Article
# This fake solr client doesn't try to re-implement solr query parser. It expects a very specific
# list of queries and return results according to its very basic database.
SOLR2DOC = {
'ID': 'id',
'NumeroID': 'issue_localidentifier',
'RevueID': 'journal_code',
'AuteurNP_fac': 'authors',
'Auteur_tri': 'authors',
'Titre_fr': 'title',
'TexteComplet': 'title',
'Corpus_fac': 'type',
'TypeArticle_fac': 'article_type',
'TitreCollection_fac': 'collection',
'RevueAbr': 'journal_code',
'AnneePublication': 'year',
'DateAjoutErudit': 'date_added',
'Fonds_fac': 'collection',
'Editeur': 'collection',
'Annee': 'year',
'Langue': 'language',
}
class SolrDocument:
def __init__(self, id, title, type, authors, solr_attrs=None, **kwargs):
self.id = id
self.title = title
self.type = type
self.authors = authors
# values that are returned as-is in as_result
self.solr_attrs = solr_attrs
OPTIONAL_ARGS = [
'article_type', 'journal_code', 'collection', 'year', 'date_added', 'repository',
'issue_localidentifier', 'language']
for attr in OPTIONAL_ARGS:
val = kwargs.get(attr)
if isinstance(val, int):
val = str(val)
setattr(self, attr, val)
@staticmethod
def from_article(article, authors=None, solr_attrs=None):
assert article.pid is not None
erudit_article = article.get_erudit_object()
if not authors:
if erudit_article:
authors = erudit_article.get_authors()
authors = [a.format_name() for a in authors]
authors = authors or []
article_type = erudit_article.article_type
if article_type == 'compterendu':
article_type = 'Compte rendu'
journal = article.issue.journal
title = erudit_article.get_formatted_title()
return SolrDocument(
id=article.solr_id,
journal_code=journal.code,
issue_localidentifier=article.issue.localidentifier,
title=title,
type='Article' if article.issue.journal.is_scientific() else 'Culturel',
article_type=article_type,
authors=authors,
year=str(article.issue.year),
collection=journal.collection.name,
solr_attrs=solr_attrs)
def as_result(self):
result = {}
for solr, attrname in SOLR2DOC.items():
val = getattr(self, attrname)
if val is not None:
result[solr] = val
if self.solr_attrs:
result.update(self.solr_attrs)
return result
class FakeSolrResults:
def __init__(self, docs=None, facet_fields=None, rows=None):
if docs is None:
docs = []
if facet_fields is None:
facet_fields = {}
self.hits = len(docs)
if rows:
docs = list(docs)[:int(rows)]
self.docs = [d.as_result() for d in docs]
self.facets = {
'facet_fields': facet_fields,
}
def unescape(s):
if s.startswith('"') and s.endswith('"'):
s = s[1:-1]
return s.replace('\\-', '-')
def normalize_pq(pq):
# We also check for known malformed queries
if isinstance(pq, (Group, FieldGroup)):
return normalize_pq(pq.children[0])
elif isinstance(pq, (AndOperation, OrOperation, UnknownOperation)):
children = map(normalize_pq, pq.children)
normalised_class = type(pq)
if isinstance(pq, UnknownOperation):
normalised_class = AndOperation
return normalised_class(*children)
elif isinstance(pq, SearchField):
if isinstance(pq.children[0], Plus):
# Operators such as + are supposed to be properly escaped in search fields. We aren't
# supposed to have one here.
raise ValueError("Illegal unescaped operator in SearchField: {}".format(pq))
return SearchField(pq.name, normalize_pq(pq.children[0]))
return pq
# example pattern: (SearchField, {'name': 'RevueAbr'}, [])
def matches_pattern(pq, pattern):
pclass, pattrs, pchildren = pattern
if not isinstance(pq, pclass):
return False
for k, v in pattrs.items():
if k != 'flags' and getattr(pq, k) != v:
return False
if pchildren:
# Order doesn't matter for children matching
for c1 in pq.children:
for c2 in list(pchildren):
if matches_pattern(c1, c2):
pchildren.remove(c2)
break
else:
return False
for child in pchildren:
child_attrs = child[1]
if 'optional' not in child_attrs.get('flags', set()):
return False
return True
else:
return True
def extract_pq_searchvals(pq):
result = {}
for child in pq.children:
result.update(extract_pq_searchvals(child))
if isinstance(pq, SearchField) and not isinstance(pq.expr, BaseOperation):
result[pq.name] = unescape(pq.expr.value)
return result
class FakeSolrClient:
def __init__(self, *args, **kwargs):
self.authors = {}
self.by_id = {}
def add_document(self, doc):
for author in doc.authors:
docs = self.authors.setdefault(author, [])
docs.append(doc)
self.by_id[doc.id] = doc
def add_article(self, article, authors=None):
self.add_document(SolrDocument.from_article(article, authors=authors))
def search(self, *args, **kwargs):
def get_facet(elems):
try:
counter = Counter(elems)
except TypeError:
# elems are lists
counter = Counter(chain(*elems))
result = []
for k, v in counter.items():
result += [k, v]
return result
def apply_filters(docs, searchvals):
def val_matches(docval, searchval):
if searchval.endswith('*'):
if docval.startswith(searchval[:-1]):
return True
elif docval == searchval:
return True
return False
def matches(doc):
for k, v in searchvals.items():
docval = getattr(doc, SOLR2DOC[k])
if not isinstance(docval, list):
docval = [docval]
if not any(val_matches(subval, v) for subval in docval):
return False
return True
return list(filter(matches, docs))
def create_results(docs, facets=[]):
# Add facets
facet_fields = {}
for facet in facets:
facet_fields[facet] = get_facet([getattr(d, SOLR2DOC[facet]) for d in docs])
# apply sorting
sort_args = kwargs.get('sort')
if sort_args:
if isinstance(sort_args, str):
sort_args = [sort_args]
for sort_arg in reversed(sort_args):
field_name, order = sort_arg.split()
if field_name == 'score':
# we don't support that, skip
continue
reverse = order == 'desc'
sortattr = SOLR2DOC[field_name]
docs = sorted(docs, key=attrgetter(sortattr), reverse=reverse)
return FakeSolrResults(docs=docs, facet_fields=facet_fields, rows=kwargs.get('rows'))
q = kwargs.get('q') or args[0]
fq = kwargs.get('fq')
if fq:
q = '{} AND {}'.format(q, fq)
q = q.replace('\\', '')
pq = normalize_pq(parser.parse(q))
my_pattern = (SearchField, {'name': 'ID'}, [])
if matches_pattern(pq, my_pattern):
searchvals = extract_pq_searchvals(pq)
solr_id = searchvals['ID']
try:
return create_results(docs=[self.by_id[solr_id]])
except KeyError:
return FakeSolrResults()
my_pattern1 = (SearchField, {'name': 'RevueAbr'}, [])
my_pattern2 = (AndOperation, {}, [
(SearchField, {'name': 'RevueAbr'}, []),
(SearchField, {'name': 'TypeArticle_fac'}, []),
])
if matches_pattern(pq, my_pattern1) or matches_pattern(pq, my_pattern2):
# letter list or article types, return facets
searchvals = extract_pq_searchvals(pq)
journal_code = searchvals['RevueAbr']
result = []
for author, docs in self.authors.items():
docs = apply_filters(docs, searchvals)
result += [doc for doc in docs if doc.journal_code == journal_code]
return create_results(result, facets=['AuteurNP_fac', 'TypeArticle_fac'])
my_pattern = (AndOperation, {}, [
(SearchField, {'name': 'RevueAbr'}, []),
(SearchField, {'name': 'AuteurNP_fac'}, []),
(SearchField, {'name': 'TypeArticle_fac', 'flags': {'optional'}}, []),
])
if matches_pattern(pq, my_pattern):
# query for articles with matching author names
searchvals = extract_pq_searchvals(pq)
journal_code = searchvals['RevueAbr']
first_letter = searchvals['AuteurNP_fac'][:1]
result = []
for author, docs in self.authors.items():
if author.startswith(first_letter):
docs = apply_filters(docs, searchvals)
for doc in docs:
result.append(doc)
return create_results(docs=result)
my_pattern1 = (SearchField, {'name': 'TexteComplet'}, [])
my_pattern2 = (AndOperation, {}, [
(SearchField, {'name': 'TexteComplet'}, []),
(SearchField, {'name': 'TypeArticle_fac', 'flags': {'optional'}}, []),
])
if matches_pattern(pq, my_pattern1) or matches_pattern(pq, my_pattern2):
# free-text query. For now, we perform a very simple search on title
searchvals = extract_pq_searchvals(pq)
searched_words = set(searchvals['TexteComplet'].lower().split())
del searchvals['TexteComplet']
result = []
docs = self.by_id.values()
docs = apply_filters(docs, searchvals)
for doc in docs:
words = set(doc.title.lower().split())
if searched_words & words:
result.append(doc)
return create_results(docs=result)
searchvals = extract_pq_searchvals(pq)
if all(key in SOLR2DOC for key in searchvals):
# generic search
result = []
docs = self.by_id.values()
docs = apply_filters(docs, searchvals)
facets = kwargs.get('facet.field', ['AnneePublication', 'AuteurNP_fac'])
return create_results(docs=docs, facets=facets)
print("Unexpected query {} {}".format(q, repr(pq)))
return FakeSolrResults()
class FakeSolrData:
"""
Let's keep these methods empty and override them in tests when needed.
"""
# noinspection PyMethodMayBeStatic,PyUnusedLocal
def get_journal_related_articles(
self, journal_code: str, current_article_localidentifier: str
) -> List[Article]:
return []
# noinspection PyMethodMayBeStatic,PyUnusedLocal
def get_search_form_facets(self) -> Dict[str, List[Tuple[str, str]]]:
return {
'disciplines': [],
'languages': [],
'journals': [],
}
| gpl-3.0 |
IliaAnastassov/ProgrammingInCSharp | ProgrammingInCSharp/Chapter1_Objective2/Properties/AssemblyInfo.cs | 1414 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Chapter1_Objective2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Chapter1_Objective2")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("74b94f36-c2ce-41ed-a185-6e0f55e14001")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| gpl-3.0 |
javan-it-services/internal | app/tests/cases/models/worklog.test.php | 1225 | <?php
/* SVN FILE: $Id$ */
/* Worklog Test cases generated on: 2009-04-07 10:04:37 : 1239075937*/
App::import('Model', 'Worklog');
class WorklogTestCase extends CakeTestCase {
var $Worklog = null;
var $fixtures = array('app.worklog', 'app.user');
function startTest() {
$this->Worklog =& ClassRegistry::init('Worklog');
}
function testWorklogInstance() {
$this->assertTrue(is_a($this->Worklog, 'Worklog'));
}
function testWorklogFind() {
$this->Worklog->recursive = -1;
$results = $this->Worklog->find('first');
$this->assertTrue(!empty($results));
$expected = array('Worklog' => array(
'id' => 1,
'user_id' => 1,
'start' => '2009-04-07 10:45:37',
'end' => '2009-04-07 10:45:37',
'log' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida,phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam,vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit,feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
'created' => '2009-04-07 10:45:37',
'updated' => '2009-04-07 10:45:37'
));
$this->assertEqual($results, $expected);
}
}
?> | gpl-3.0 |
gohdan/DFC | known_files/hashes/libraries/fof/table/relations.php | 144 | Joomla 3.3.3 = 9df39f8c2734059138c8fa8761c20577
Joomla 3.6.4 = 81a2082bc78a86c6ebab5f29c3a7455b
Joomla 3.6.2 = 4d3046b42f7ae205f1986aec2ef6e74a
| gpl-3.0 |
Rodriwp/pfat | src/Practica_1/java/Parser/AST/SentSimp2.java | 142 | package AST;
public class SentSimp2 implements Sentencia {
public final Cond cond;
public SentSimp2(Cond cond) {
this.cond = cond;
}
}
| gpl-3.0 |
mandrakey/GradeCalc | model/worksheet.cpp | 2629 | /* Copyright (C) 2013 Maurice Bleuel (mandrakey@lavabit.com)
*
* This file is part of GradeCalc.
*
* GradeCalc 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.
*
* GradeCalc 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 GradeCalc. If not, see <http://www.gnu.org/licenses/>.
*/
#include "worksheet.h"
Worksheet::Worksheet() :
mInstitutionId(-1), mStudyCourseId(-1), mGrades()
{
}
Worksheet::Worksheet(const QString &sourceFile) throw (IllegalArgumentException) :
Worksheet()
{
QFile f(sourceFile);
if (!f.exists() || !f.open(QIODevice::ReadOnly))
throw IllegalArgumentException(QString("File %1 can not be opened").arg(sourceFile));
QDataStream stream(&f);
stream >> mInstitutionId >> mStudyCourseId;
while (!stream.atEnd()) {
int id = 0;
double grade = 0;
stream >> id >> grade;
mGrades.insert(id, grade);
}
f.close();
}
Worksheet::Worksheet(int institutionId, const StudyCourse *studyCourse) :
mInstitutionId(institutionId), mStudyCourseId(studyCourse->getId()),
mGrades()
{
QList<Course *> courses = studyCourse->getCourses();
int i = 0;
foreach (Course *c, courses)
mGrades.insert(i++, c->getGrade());
}
int Worksheet::institutionId() const
{
return mInstitutionId;
}
int Worksheet::studyCourseId() const
{
return mStudyCourseId;
}
QHash<int,double> Worksheet::grades() const
{
return QHash<int,double>(mGrades);
}
void Worksheet::setInstitutionId(int institutionId)
{
mInstitutionId = institutionId;
}
void Worksheet::setStudyCourseId(int studyCourseId)
{
mStudyCourseId = studyCourseId;
}
void Worksheet::setGrade(int key, double value)
{
mGrades.insert(key, value);
}
void Worksheet::toFile(const QString &targetFile) const
{
QFile f(targetFile);
if (!f.open(QIODevice::WriteOnly))
throw IllegalArgumentException(
QString("File %1 can not be opened").arg(targetFile));
QDataStream stream(&f);
stream << quint32(mInstitutionId) << quint32(mStudyCourseId);
foreach (int k, mGrades.keys()) {
stream << quint32(k) << qreal(mGrades.value(k));
}
f.close();
}
| gpl-3.0 |
GeorgH93/Bukkit_MarriageMaster | MarriageMaster/src/at/pcgamingfreaks/MarriageMaster/Bungee/Database/Database.java | 3375 | /*
* Copyright (C) 2020 GeorgH93
*
* 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 at.pcgamingfreaks.MarriageMaster.Bungee.Database;
import at.pcgamingfreaks.Bungee.Database.Cache.UnCacheStrategies.UnCacheStrategyMaker;
import at.pcgamingfreaks.Database.Cache.BaseUnCacheStrategy;
import at.pcgamingfreaks.MarriageMaster.API.Home;
import at.pcgamingfreaks.MarriageMaster.Bungee.MarriageMaster;
import at.pcgamingfreaks.MarriageMaster.Database.BaseDatabase;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import java.util.UUID;
public class Database extends BaseDatabase<MarriageMaster, MarriagePlayerData, MarriageData, Home> implements Listener
{
private final BaseUnCacheStrategy unCacheStrategy;
public Database(MarriageMaster plugin)
{
super(plugin, plugin.getLogger(), new PlatformSpecific(plugin), plugin.getConfig(), plugin.getDescription().getName(), plugin.getDataFolder(), true, true);
if(available())
{
unCacheStrategy = UnCacheStrategyMaker.make(plugin, cache, plugin.getConfig());
plugin.getProxy().getPluginManager().registerListener(plugin, this);
loadRunnable.run();
}
else unCacheStrategy = null;
}
@Override
public void close()
{
plugin.getProxy().getPluginManager().unregisterListener(this);
unCacheStrategy.close(); // Killing the uncache strategie
super.close();
}
@Override
public MarriagePlayerData getPlayer(UUID uuid)
{
MarriagePlayerData player = cache.getPlayer(uuid);
if(player == null)
{
// We cache all our married players on startup, we also load unmarried players on join. If there is no data for him in the cache we return a new player.
// It's very likely that he was only requested in order to show a info about his marriage status. When someone change the player the database will fix him anyway.
ProxiedPlayer pPlayer = plugin.getProxy().getPlayer(uuid);
player = new MarriagePlayerData(uuid, pPlayer != null ? pPlayer.getName() : "Unknown");
cache.cache(player); // Let's put the new player into the cache
}
load(player); // Load the player and update the database
return player;
}
@EventHandler(priority = Byte.MIN_VALUE) // We want to start the loading of the player as soon as he connects, so he probably is ready as soon as someone requests the player.
public void onPlayerLoginEvent(PostLoginEvent event)
{
getPlayer(event.getPlayer().getUniqueId()); // This will load the player if he isn't loaded yet
}
@Override
protected void loadOnlinePlayers()
{
for(ProxiedPlayer proxiedPlayer : plugin.getProxy().getPlayers())
{
getPlayer(proxiedPlayer.getUniqueId());
}
}
} | gpl-3.0 |
GNOME/glom | glom/utility_widgets/filechooserdialog_saveextras.cc | 8437 | /* Glom
*
* Copyright (C) 2006 Murray Cumming
*
* 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.
*/
#include "config.h"
#include <glom/utility_widgets/filechooserdialog_saveextras.h>
#include <glom/utils_ui.h>
#include <gtkmm/alignment.h>
#include <libglom/utils.h> //For bold_message()).
#include <glibmm/i18n.h>
namespace Glom
{
FileChooserDialog_SaveExtras::FileChooserDialog_SaveExtras(const Glib::ustring& title, Gtk::FileChooserAction action)
: Gtk::FileChooserDialog(title, action),
m_extra_widget(Gtk::ORIENTATION_VERTICAL)
{
create_child_widgets();
}
FileChooserDialog_SaveExtras::FileChooserDialog_SaveExtras(Gtk::Window& parent, const Glib::ustring& title, Gtk::FileChooserAction action)
: Gtk::FileChooserDialog(parent, title, action),
m_extra_widget(Gtk::ORIENTATION_VERTICAL)
{
create_child_widgets();
}
void FileChooserDialog_SaveExtras::set_extra_message(const Glib::ustring& message)
{
m_label_extra_message.set_text(message);
if(!message.empty()) {
m_label_extra_message.show();
} else {
m_label_extra_message.hide();
}
}
void FileChooserDialog_SaveExtras::create_child_widgets()
{
//m_extra_widget.pack_start(m_label_extra_message);
m_label_extra_message.set_halign(Gtk::ALIGN_START);
m_label_extra_message.set_valign(Gtk::ALIGN_CENTER);
auto frame = Gtk::manage(new Gtk::Frame());
auto frame_label = Gtk::manage(new Gtk::Label());
frame_label->set_markup(UiUtils::bold_message(_("New Database")));
frame_label->show();
frame->set_label_widget(*frame_label);
frame->set_shadow_type(Gtk::SHADOW_NONE);
frame->show();
auto vbox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL, Utils::to_utype(UiUtils::DefaultSpacings::SMALL)));
vbox->set_margin_start(Utils::to_utype(UiUtils::DefaultSpacings::LARGE));
vbox->set_margin_top(Utils::to_utype(UiUtils::DefaultSpacings::SMALL));
frame->add(*vbox);
vbox->show();
vbox->pack_start(m_label_extra_message); /* For instance, an extra hint when saving from an example, saying that a new file must be saved. */
auto label_newdb = Gtk::manage(new Gtk::Label(_("Please choose a human-readable title for the new database. You can change this later in the database properties. It may contain any characters.")));
vbox->pack_start(*label_newdb);
label_newdb->set_halign(Gtk::ALIGN_START);
label_newdb->set_valign(Gtk::ALIGN_CENTER);
label_newdb->show();
auto box_label = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, Utils::to_utype(UiUtils::DefaultSpacings::LARGE)));
auto label_title = Gtk::manage(new Gtk::Label(_("_Title:"), true));
box_label->pack_start(*label_title, Gtk::PACK_SHRINK);
label_title->show();
box_label->pack_start(m_entry_title);
m_entry_title.get_accessible()->set_name(_("Title"));
m_entry_title.show();
box_label->show();
vbox->pack_start(*box_label);
#ifndef GLOM_ENABLE_CLIENT_ONLY
#ifdef GLOM_ENABLE_POSTGRESQL
#if defined(GLOM_ENABLE_SQLITE) || defined(GLOM_ENABLE_MYSQL)
//Use titles that show the distinction between PostgreSQL and the alternatives:
const auto postgresql_selfhost_label = _("Create PostgreSQL database in its own folder, to be hosted by this computer.");
const auto postgresql_central_label = _("Create database on an external PostgreSQL database server, to be specified in the next step.");
#else
const auto postgresql_selfhost_label = _("Create database in its own folder, to be hosted by this computer.");
const auto postgresql_central_label = _("Create database on an external database server, to be specified in the next step.");
#endif
m_radiobutton_server_postgres_selfhosted.set_label(postgresql_selfhost_label);
vbox->pack_start(m_radiobutton_server_postgres_selfhosted);
m_radiobutton_server_postgres_selfhosted.show();
m_radiobutton_server_postgres_central.set_label(postgresql_central_label);
Gtk::RadioButton::Group group = m_radiobutton_server_postgres_selfhosted.get_group();
m_radiobutton_server_postgres_central.set_group(group);
vbox->pack_start(m_radiobutton_server_postgres_central);
m_radiobutton_server_postgres_central.show();
m_radiobutton_server_postgres_selfhosted.set_active(true); // Default
#endif
#ifdef GLOM_ENABLE_SQLITE
m_radiobutton_server_sqlite.set_label(_("Create SQLite database in its own folder, to be hosted by this computer."));
m_radiobutton_server_sqlite.set_tooltip_text(_("SQLite does not support authentication or remote access but is suitable for embedded devices."));
m_radiobutton_server_sqlite.set_group(group);
vbox->pack_start(m_radiobutton_server_sqlite);
m_radiobutton_server_sqlite.show();
#endif
#ifdef GLOM_ENABLE_MYSQL
m_radiobutton_server_mysql_selfhosted.set_label(_("Create MySQL database in its own folder, to be hosted by this computer."));
m_radiobutton_server_mysql_selfhosted.set_tooltip_text(_("MySQL support in Glom is experimental and unlikely to work properly."));
m_radiobutton_server_mysql_selfhosted.set_group(group);
vbox->pack_start(m_radiobutton_server_mysql_selfhosted);
m_radiobutton_server_mysql_selfhosted.show();
m_radiobutton_server_mysql_central.set_label(_("Create database on an external MySQL database server, to be specified in the next step."));
m_radiobutton_server_mysql_central.set_tooltip_text(_("MySQL support in Glom is experimental and unlikely to work properly."));
m_radiobutton_server_mysql_central.set_group(group);
vbox->pack_start(m_radiobutton_server_mysql_central);
m_radiobutton_server_mysql_central.show();
#endif
#endif // !GLOM_ENABLE_CLIENT_ONLY
m_extra_widget.pack_start(*frame);
set_extra_widget(m_extra_widget);
m_extra_widget.show();
}
void FileChooserDialog_SaveExtras::set_extra_newdb_title(const Glib::ustring& title)
{
m_entry_title.set_text(title);
}
void FileChooserDialog_SaveExtras::set_extra_newdb_hosting_mode(Document::HostingMode mode)
{
switch(mode)
{
#ifdef GLOM_ENABLE_POSTGRESQL
case Document::HostingMode::POSTGRES_CENTRAL:
m_radiobutton_server_postgres_central.set_active();
break;
case Document::HostingMode::POSTGRES_SELF:
m_radiobutton_server_postgres_selfhosted.set_active();
break;
#endif //GLOM_ENABLE_POSTGRESQL
#ifdef GLOM_ENABLE_SQLITE
case Document::HostingMode::SQLITE:
m_radiobutton_server_sqlite.set_active();
break;
#endif //GLOM_ENABLE_SQLITE
#ifdef GLOM_ENABLE_MYSQL
case Document::HostingMode::MYSQL_CENTRAL:
m_radiobutton_server_mysql_central.set_active();
break;
case Document::HostingMode::MYSQL_SELF:
m_radiobutton_server_mysql_selfhosted.set_active();
break;
#endif //GLOM_ENABLE_SQLITE
default:
g_assert_not_reached();
break;
}
}
Glib::ustring FileChooserDialog_SaveExtras::get_extra_newdb_title() const
{
return m_entry_title.get_text();
}
Document::HostingMode FileChooserDialog_SaveExtras::get_extra_newdb_hosting_mode() const
{
#ifdef GLOM_ENABLE_POSTGRESQL
if(m_radiobutton_server_postgres_central.get_active())
return Document::HostingMode::POSTGRES_CENTRAL;
else if(m_radiobutton_server_postgres_selfhosted.get_active())
return Document::HostingMode::POSTGRES_SELF;
#endif //GLOM_ENABLE_POSTGRESQL
#ifdef GLOM_ENABLE_SQLITE
if(m_radiobutton_server_sqlite.get_active())
return Document::HostingMode::SQLITE;
#endif //GLOM_ENABLE_SQLITE
#ifdef GLOM_ENABLE_MYSQL
if(m_radiobutton_server_mysql_central.get_active())
return Document::HostingMode::MYSQL_CENTRAL;
else if(m_radiobutton_server_mysql_selfhosted.get_active())
return Document::HostingMode::MYSQL_SELF;
#endif //GLOM_ENABLE_MYSQL
g_assert_not_reached();
#ifdef GLOM_ENABLE_SQLITE
return Document::HostingMode::SQLITE; //Arbitrary
#else
return Document::HostingMode::POSTGRES_SELF; //Arbitrary.
#endif //GLOM_ENABLE_SQLITE
}
} //namespace Glom
| gpl-3.0 |