code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is the "OGC Service Framework". The Initial Developer of the Original Code is Spotimage S.A. Portions created by the Initial Developer are Copyright (C) 2007 the Initial Developer. All Rights Reserved. Contributor(s): Philippe Merigot <philippe.merigot@spotimage.fr> ******************************* END LICENSE BLOCK ***************************/ package org.vast.ows.sps; import org.w3c.dom.Element; import org.vast.ogc.OGCRegistry; import org.vast.ows.OWSException; import org.vast.ows.swe.SWERequestWriter; import org.vast.xml.DOMHelper; /** * <p> * Provides methods to generate an XML SPS Confirm * request based on values contained in a ConfirmRequest object * for version 2.0 * </p> * * @author Alexandre Robin <alexandre.robin@spotimage.fr> * @date Feb, 258 2008 **/ public class ConfirmRequestWriterV20 extends SWERequestWriter<ConfirmRequest> { /** * KVP Request */ @Override public String buildURLQuery(ConfirmRequest request) throws OWSException { throw new SPSException(noKVP + "SPS 2.0 " + request.getOperation()); } /** * XML Request */ @Override public Element buildXMLQuery(DOMHelper dom, ConfirmRequest request) throws OWSException { dom.addUserPrefix("sps", OGCRegistry.getNamespaceURI(SPSUtils.SPS, request.getVersion())); // root element Element rootElt = dom.createElement("sps:" + request.getOperation()); addCommonXML(dom, rootElt, request); // taskID dom.setElementValue(rootElt, "sps:task", request.getTaskID()); return rootElt; } }
sensiasoft/lib-ows
ogc-services-sps/src/main/java/org/vast/ows/sps/ConfirmRequestWriterV20.java
Java
mpl-2.0
2,147
namespace WindowsFormsFlashControlLibrary { partial class UserControl1 { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 组件设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UserControl1)); this.axShockwaveFlash1 = new AxShockwaveFlashObjects.AxShockwaveFlash(); ((System.ComponentModel.ISupportInitialize)(this.axShockwaveFlash1)).BeginInit(); this.SuspendLayout(); // // axShockwaveFlash1 // this.axShockwaveFlash1.Enabled = true; this.axShockwaveFlash1.Location = new System.Drawing.Point(0, 3); this.axShockwaveFlash1.Name = "axShockwaveFlash1"; this.axShockwaveFlash1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axShockwaveFlash1.OcxState"))); this.axShockwaveFlash1.Size = new System.Drawing.Size(561, 337); this.axShockwaveFlash1.TabIndex = 0; // // UserControl1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.axShockwaveFlash1); this.Name = "UserControl1"; this.Size = new System.Drawing.Size(564, 340); ((System.ComponentModel.ISupportInitialize)(this.axShockwaveFlash1)).EndInit(); this.ResumeLayout(false); } #endregion private AxShockwaveFlashObjects.AxShockwaveFlash axShockwaveFlash1; } }
liangsenzhi/WPF
1.22WPF嵌入FlashPlayer(VS2010)/WindowsFormsFlashControlLibrary/UserControl1.Designer.cs
C#
mpl-2.0
2,411
package fyp.hkust.facet.util; /** * Created by ClementNg on 2/4/2017. */ import android.graphics.Paint; import android.graphics.Typeface; import android.text.TextPaint; import android.text.style.TypefaceSpan; public class CustomTypeFaceSpan extends TypefaceSpan { private final Typeface newType; public CustomTypeFaceSpan(String family, Typeface type) { super(family); newType = type; } @Override public void updateDrawState(TextPaint ds) { applyCustomTypeFace(ds, newType); } @Override public void updateMeasureState(TextPaint paint) { applyCustomTypeFace(paint, newType); } private static void applyCustomTypeFace(Paint paint, Typeface tf) { int oldStyle; Typeface old = paint.getTypeface(); if (old == null) { oldStyle = 0; } else { oldStyle = old.getStyle(); } int fake = oldStyle & ~tf.getStyle(); if ((fake & Typeface.BOLD) != 0) { paint.setFakeBoldText(true); } if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f); } paint.setTypeface(tf); } }
clementf2b/FaceT
app/src/main/java/fyp/hkust/facet/util/CustomTypeFaceSpan.java
Java
mpl-2.0
1,186
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Text; using Web.Units; using Models; namespace Web.Areas.BusinessManger.Controllers { public class FrameSetController : BusinessAreaBaseController { public ActionResult Login() { if (AliceDAL.Common.IsGet()) { ViewBag.LoginID = AliceDAL.Common.GetCookie("BusinessInfoLoginID"); return View(); } string LoginID = AliceDAL.Common.GetFormString("loginID"); string password = AliceDAL.Common.GetFormString("password"); string verifyCode = AliceDAL.Common.GetFormString("verifyCode"); string result, url = ""; if (String.IsNullOrEmpty(AliceDAL.Common.GetCookie("CheckCodeSum"))) { url = ""; result = "Cookies不能使用,无法使用本系统"; return AjaxResult(url, result); } if (String.Compare(AliceDAL.SecureHelper.AESDecrypt(AliceDAL.Common.GetCookie("CheckCodeSum"), "duoduo1"), verifyCode, true) != 0) { url = ""; result = "验证码错误!"; return AjaxResult(url, result); } BD_Business admin = DAL.BD_Business.Login(LoginID, AliceDAL.SecureHelper.MD5(password), out result); if (null != admin) { if (admin.BusinessState ==0) { url = ""; result = "商户已禁用!"; return AjaxResult(url, result); } AliceDAL.Common.SetCookie("BusinessInfoLoginID", admin.LoginID, 999999); HttpCookie cookie = new HttpCookie("BusinessUserInfo"); AliceDAL.Common.SetCookie("BusinessUserInfo", "ID", admin.ID.ToString(), 527040); AliceDAL.Common.SetCookie("BusinessUserInfo", "Password", AliceDAL.SecureHelper.MD5(admin.Password + admin.ID.ToString()), 527040); url = "/BusinessManger/UsersAdmin/"; result = "OK"; } return AjaxResult(url, result); } public ActionResult LoginOut() { AliceDAL.Common.DeleteCookie("BusinessUserInfo"); AliceDAL.Common.DeleteCookie("CheckCodeSum"); return RedirectToAction("Login"); } public ActionResult VerifyImage(int size = 17) { Units.SecurityCode seccode = new Units.SecurityCode(); seccode.Length = 4; seccode.FontSize = size; seccode.Chaos = true; seccode.BackgroundColor = seccode.BackgroundColor; seccode.ChaosColor = seccode.ChaosColor; seccode.Colors = seccode.Colors; seccode.Fonts = seccode.Fonts; seccode.Padding = seccode.Padding; string code = seccode.CreateVerifyCode(4);//取随机码 AliceDAL.Common.SetCookie("CheckCodeSum", AliceDAL.SecureHelper.AESEncrypt(code, "duoduo1")); return File(seccode.CreateImage(code), "image/png"); } public JsonResult AjaxResult(string url, string result) { return Json(new { url = url, msg = result }, JsonRequestBehavior.AllowGet); } } }
tst20170901/test2
Web/Areas/BusinessManger/Controllers/FrameSetController.cs
C#
mpl-2.0
3,389
/* 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/. */ package output import "reflect" // S3Grantee ... type S3Grantee struct { ID string `json:"id"` Type string `json:"type"` Permissions string `json:"permissions"` } // S3 represents an aws S3 bucket type S3 struct { ProviderType string `json:"_type"` DatacenterName string `json:"datacenter_name,omitempty"` DatacenterRegion string `json:"datacenter_region"` AccessKeyID string `json:"aws_access_key_id"` SecretAccessKey string `json:"aws_secret_access_key"` Name string `json:"name"` ACL string `json:"acl"` BucketLocation string `json:"bucket_location"` BucketURI string `json:"bucket_uri"` Grantees []S3Grantee `json:"grantees,omitempty"` Tags map[string]string `json:"tags"` Service string `json:"service"` Status string `json:"status"` Exists bool } // HasChanged diff's the two items and returns true if there have been any changes func (s *S3) HasChanged(os *S3) bool { if s.ACL != os.ACL { return true } if len(s.Grantees) < 1 && len(os.Grantees) < 1 { return false } return !reflect.DeepEqual(s.Grantees, os.Grantees) } // GetTags returns a components tags func (s S3) GetTags() map[string]string { return s.Tags } // ProviderID returns a components provider id func (s S3) ProviderID() string { return s.Name } // ComponentName returns a components name func (s S3) ComponentName() string { return s.Name }
ernestio/aws-definition-mapper
output/s3.go
GO
mpl-2.0
1,797
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker({ format: 'm/d/yyyy', autoclose: true }); initializeMap(); }; function initializeTypeahead() { $("#Experience_Name").typeahead({ name: 'title', prefetch: options.TitlesUrl, limit: 10 }); $("#Experience_Organization").typeahead({ name: 'orgs', prefetch: options.OrganizationsUrl, limit: 10 }); } function initializeImagePreview() { $("#cover-image").change(function () { var filesToUpload = this.files; if (filesToUpload.length !== 1) return; var file = filesToUpload[0]; if (!file.type.match(/image.*/)) { alert("only images, please"); } var img = document.getElementById("cover-preview"); img.src = window.URL.createObjectURL(file); img.onload = function(e) { window.URL.revokeObjectURL(this.src); }; //img.height = 500; }); } function initializeMap() { var davisLatLng = new google.maps.LatLng(38.5449065, -121.7405167); geocoder = new google.maps.Geocoder(); var mapOptions = { center: davisLatLng, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); marker = new google.maps.Marker({ map: map, position: davisLatLng }); $("#Experience_Location").blur(function () { var address = this.value; geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (marker) marker.setMap(null); //clear existing marker map.setCenter(results[0].geometry.location); marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }); } }(window.Badges = window.Badges || {}, jQuery));
ucdavis/Badges
Badges/Scripts/public/modifyexperience.js
JavaScript
mpl-2.0
2,851
/* * Copyright © 2013-2021, The SeedStack authors <http://seedstack.org> * * 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/. */ package org.seedstack.business.domain; import java.lang.reflect.Type; import javax.inject.Inject; import org.seedstack.business.internal.utils.BusinessUtils; import org.seedstack.business.specification.dsl.SpecificationBuilder; /** * An helper base class that can be extended to create an <strong>implementation</strong> of a * repository interface which, in turn, must extend {@link Repository}. * * <p> This class is mainly used as a common base for specialized technology-specific * implementations. Client code will often extend these more specialized classes instead of this * one. </p> * * @param <A> Type of the aggregate root. * @param <I> Type of the aggregate root identifier. * @see Repository * @see org.seedstack.business.util.inmemory.BaseInMemoryRepository */ public abstract class BaseRepository<A extends AggregateRoot<I>, I> implements Repository<A, I> { private static final int AGGREGATE_INDEX = 0; private static final int KEY_INDEX = 1; private final Class<A> aggregateRootClass; private final Class<I> idClass; @Inject private SpecificationBuilder specificationBuilder; /** * Creates a base domain repository. Actual classes managed by the repository are determined by * reflection. */ @SuppressWarnings("unchecked") protected BaseRepository() { Type[] generics = BusinessUtils.resolveGenerics(BaseRepository.class, getClass()); this.aggregateRootClass = (Class<A>) generics[AGGREGATE_INDEX]; this.idClass = (Class<I>) generics[KEY_INDEX]; } /** * Creates a base domain repository. Actual classes managed by the repository are specified * explicitly. This can be used to create a dynamic implementation of a repository. * * @param aggregateRootClass the aggregate root class. * @param idClass the aggregate root identifier class. */ protected BaseRepository(Class<A> aggregateRootClass, Class<I> idClass) { this.aggregateRootClass = aggregateRootClass; this.idClass = idClass; } @Override public Class<A> getAggregateRootClass() { return aggregateRootClass; } @Override public Class<I> getIdentifierClass() { return idClass; } @Override public SpecificationBuilder getSpecificationBuilder() { return specificationBuilder; } }
seedstack/business
core/src/main/java/org/seedstack/business/domain/BaseRepository.java
Java
mpl-2.0
2,661
export default (collection, clickable, text) => () => { return collection('.consul-auth-method-list [data-test-list-row]', { authMethod: clickable('a'), name: text('[data-test-auth-method]'), displayName: text('[data-test-display-name]'), type: text('[data-test-type]'), }); };
hashicorp/consul
ui/packages/consul-ui/app/components/consul/auth-method/list/pageobject.js
JavaScript
mpl-2.0
298
'use strict'; require('should'); describe('index.html', () => { beforeEach(() => { browser.url('/'); // browser.localStorage('DELETE') does not work in PhantomJS browser.execute(function() { delete window.localStorage; window.localStorage = {}; }); browser.url('/'); $('#default-username').waitForEnabled(); $('#default-username').setValue('test'); $('#shared-secret').setValue('test'); $('.save-settings').click(); $('#domain').waitForEnabled(); // wait for .modal-bg to be hidden browser.waitUntil(() => $('.modal-bg').getCssProperty('z-index').value == -1 ); }); it('should generate a password', () => { $('#domain').setValue('example.com'); browser.waitUntil(() => $('#password').getValue() == 'z<u9N_[c"R' ); }); it('should generate a password at a given index', () => { $('#index').selectByVisibleText('1'); $('#domain').setValue('example.com'); browser.waitUntil(() => $('#password').getValue() == 'g:3WGYj0}~' ); }); it('should generate a password of a given length', () => { $('#length').selectByVisibleText('8'); $('#domain').setValue('example.com'); browser.waitUntil(() => $('#password').getValue() == 'u9N_[c"R' ); }); it('should open settings menu', () => { $('#open-settings').click(); browser.waitUntil(() => $('#settings').getLocation('y') >= 0 ); }); it('should change the algorithm', () => { $('#open-settings').click(); $('#algorithm').waitForEnabled(); $('#algorithm').selectByVisibleText('SHA-512'); $('.save-settings').click(); $('#domain').waitForEnabled(); $('#domain').setValue('example.com'); browser.waitUntil(() => $('#password').getValue() == 'V{fvC^YRi(' ); }); });
chameleoid/telepathy-web
test/telepathy-web.js
JavaScript
mpl-2.0
1,829
class Attendance < ActiveRecord::Base belongs_to :student belongs_to :event validates_uniqueness_of :student_id, scope: :event_id validates_presence_of :student_id, :event_id YES = "Yes" NO = "No" MAYBE = "Maybe" def message case self.commitment_status when YES then "You signed up for #{event.name}" when MAYBE then "You are now watching #{event.name}" when NO then "You backed out of #{event.name}" end end def description case self.commitment_status when YES then "You are going to this event" when MAYBE then "You are watching this event" when NO then "You backed out of this event" end end def short_description case self.commitment_status when YES then "Going" when MAYBE then "Watching" when NO then "Backed out" end end end
MozillaHive/HiveCHI-rwm
app/models/attendance.rb
Ruby
mpl-2.0
824
export const up = async function(db: any): Promise<any> { return db.runSql( ` CREATE TABLE streaks ( id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, client_id CHAR(36) NOT NULL, locale_id INT NOT NULL, started_at DATETIME, last_activity_at DATETIME, FOREIGN KEY (client_id) REFERENCES user_clients (client_id) ON DELETE CASCADE, FOREIGN KEY (locale_id) REFERENCES locales (id) ON DELETE CASCADE, UNIQUE KEY (client_id, locale_id) ); CREATE TABLE reached_goals ( id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, type ENUM('streak', 'clips', 'votes') NOT NULL, count SMALLINT UNSIGNED NOT NULL, client_id CHAR(36) NOT NULL, locale_id INT NOT NULL, reached_at DATETIME NOT NULL, FOREIGN KEY (client_id) REFERENCES user_clients (client_id), FOREIGN KEY (locale_id) REFERENCES locales (id), UNIQUE(count, type, client_id, locale_id) ); ` ); }; export const down = function(): Promise<any> { return null; };
gozer/voice-web
server/src/lib/model/db/migrations/20190711074029-streaks-and-reached_goals.ts
TypeScript
mpl-2.0
1,087
<?php /** * Insert Class * * @author Mahsum UREBE <mahsumurebe@outlook.com> <github:mahsumurebe> * @file Insert.php * @copyright ©2017 Mahsum UREBE **/ namespace System\DB\QueryBuilder; use System\DB\QueryBuilder\Abstracts\TableAbstract; /** * Insert Class * * @package Referances\System\DB\QueryBuilder * @group Database */ class Insert extends TableAbstract { /** * INSERT .... SELECT olayı * * @var Select */ public $select; /** * Sütunlar * * @var string[] */ protected $columns = array(); /** * Değerler * * @var string[]|string[][] */ protected $values = array(); protected $statments = array(); /** * Insert sınıfı yapıcı methodu. * * @param string|string[] $tables * @param string|string[] $data * @param string[] $values */ public function __construct($tables = null, $data = null, $values = null) { $this->select = new Select(); $this->table($tables); if (!empty($data) && empty($values)) $this->setData($data); else if (!empty($data) && empty($values)) $this->setColumn($data) ->setValue($values); } /** * Verileri belirleyen method. * * @param string[]|string[][] $data Veriler * * @return $this */ public function setData($data) { if (is_array($data)) { if (is_array(current($data))) { // eğer birden fazla değer varsa $columns = array_keys(current($data)); $values = array_map('array_values', $data); } else { $columns = array_keys($data); $values = array_values($data); } $this->setValue($values); $this->setColumn($columns); } return $this; } /** * Değerleri belirleyen method. * * @param string[]|string[][] $values Değerler * * @return $this */ public function setValue($values) { if (!is_array(current($values))) $values = array($values); $this->values = array_merge($this->values, $values); return $this; } /** * Sütunları belirleyen method. * * @param string|string[] $column_name Sütun adı * * @return $this */ public function setColumn($column_name) { if (!is_array($column_name)) $column_name = array($column_name); $this->columns = array_merge($this->columns, Escape::escapeName($column_name)); return $this; } /** * Düşük öncelik * * @return Insert */ public function LOW_PRIORITY() { return $this->statement('LOW_PRIORITY', 0); } /** * Method kaydı. * * @param string $statment Method * @param int $level Seviye * * @return $this */ private function statement($statment, $level) { $this->statments[ $level ] = $statment; return $this; } /** * Yüksek öncelik * * @return Insert */ public function HIGH_PRIORITY() { return $this->statement('HIGH_PRIORITY', 0); } /** * Gecikmeli öncelik * * @return Insert */ public function DELAYED() { return $this->statement('DELAYED', 0); } /** * Yüksek öncelik * * @return Insert */ public function IGNORE() { return $this->statement('IGNORE', 1); } public function getQuery() { $statements = implode(' ', $this->statments); if (!empty($statements)) $statements .= ' '; $QueryPattern = 'INSERT ' . $statements . 'INTO '; $QueryPattern .= CRLF . implode(', ', $this->tables); $QueryPattern .= ' ' . sprintf('(%s)', implode(', ', $this->columns)); $QueryPattern .= (count($this->values) > 1) ? CRLF . ' VALUES' : ' VALUE'; $QueryPattern .= ' ' . $this->getValuesStr(); return $QueryPattern; } private function getValuesStr() { $out = array(); foreach ($this->values as $value) $out[] = sprintf('(%s)', implode(', ', Escape::escapeValue($value))); return implode(', ' . CRLF, $out); } }
mahsumurebe/QueryBuilder
QueryBuilder/Insert.php
PHP
mpl-2.0
5,264
#!/usr/bin/env python3 # # Copyright (C) 2017-2020 EOS di Manlio Morini. # # 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/ # # A python program that helps to set up a new version of Vita. # import argparse import datetime import os import re def version_str(args): return str(args.major) + "." + str(args.minor) + "." + str(args.maintenance) def file_process(name, rule, args): print("--- Processing " + os.path.basename(name)) with open(name) as source: data = rule(source.read(), args) if not data: return print("Writing " + name) with open(name) as dest: dest = open(name, "w") dest.write(data) def changelog_rule(data, args): new_version = version_str(args) regex = r"## \[Unreleased\]" subst = r"## [Unreleased]\n\n## [" + new_version + r"] - " + datetime.date.today().isoformat() result = re.subn(regex, subst, data) if result[1] != 1: return None regex = r"(\[Unreleased)(\]: https://github.com/morinim/vita/compare/v)(.+)(\.\.\.HEAD)" subst = r"\g<1>\g<2>" + new_version + r"\g<4>\n[" + new_version + r"\g<2>\g<3>...v" + new_version result = re.subn(regex, subst, result[0]) return result[0] if result[1] == 1 else None def doxygen_rule(data, args): regex = r"([\s]+)(\*[\s]+\\mainpage VITA v)([\d]+)\.([\d]+)\.([\d]+)([\s]*)" subst = r"\g<1>\g<2>" + version_str(args) + r"\g<6>" result = re.subn(regex, subst, data) return result[0] if result[1] > 0 else None def get_cmd_line_options(): description = "Helps to set up a new version of Vita" parser = argparse.ArgumentParser(description = description) parser.add_argument("-v", "--verbose", action = "store_true", help = "Turn on verbose mode") # Now the positional arguments. parser.add_argument("major", type=int) parser.add_argument("minor", type=int) parser.add_argument("maintenance", type=int) return parser def main(): args = get_cmd_line_options().parse_args() print("Setting version to v" + str(args.major) + "." + str(args.minor) + "." + str(args.maintenance)) file_process("../NEWS.md", changelog_rule, args) file_process("../doc/doxygen/doxygen.h", doxygen_rule, args) print("\n\nRELEASE NOTE\n") print("1. Build. cmake -DCMAKE_BUILD_TYPE=Release -B build/ src/ ; cmake --build build/") print("2. Check. cd build/ ; ./tests") print('3. Commit. git commit -am "[DOC] Changed revision number to v' + version_str(args) + '"') print("4. Tag. git tag -a v" + version_str(args) + " -m \"tag message\"") print("\nRemember to 'git push' both code and tag. For the tag:\n") print(" git push origin [tagname]\n") if __name__ == "__main__": main()
morinim/vita
src/setversion.py
Python
mpl-2.0
2,950
"use strict"; var myTable = require("../data/myTables.json"); // Dictionaries to modify/extend the original dictionaries var devanagari_dict_mod = {}; var telugu_dict_mod = {}; var kannada_dict_mod = {}; var gujarati_dict_mod = {}; var tamil_dict_mod = {}; var bengali_dict_mod = {}; var gurmukhi_dict_mod = {}; var malayalam_dict_mod = {}; var oriya_dict_mod = {}; var english_dict_mod = {}; var devanagari_dict_rev = {}; var telugu_dict_rev = {}; var kannada_dict_rev = {}; var gujarati_dict_rev = {}; var tamil_dict_rev = {}; var bengali_dict_rev = {}; var gurmukhi_dict_rev = {}; var malayalam_dict_rev = {}; var oriya_dict_rev = {}; var english_dict_rev = {}; var katapayadi_dict = myTable.katapayadi_dict; function init() { // new modified/extended dictionaries devanagari_dict_mod = extend(myTable.devanagari_dict); telugu_dict_mod = extend(myTable.telugu_dict); kannada_dict_mod = extend(myTable.kannada_dict); gujarati_dict_mod = extend(myTable.gujarati_dict); tamil_dict_mod = extend(myTable.tamil_dict); bengali_dict_mod = extend(myTable.bengali_dict); gurmukhi_dict_mod = extend(myTable.gurmukhi_dict); malayalam_dict_mod = extend(myTable.malayalam_dict); oriya_dict_mod = extend(myTable.oriya_dict); english_dict_mod = extend(myTable.english_dict); // reverse dictionaries devanagari_dict_rev = reverse(myTable.devanagari_dict); telugu_dict_rev = reverse(myTable.telugu_dict); kannada_dict_rev = reverse(myTable.kannada_dict); gujarati_dict_rev = reverse(myTable.gujarati_dict); tamil_dict_rev = reverse(myTable.tamil_dict); bengali_dict_rev = reverse(myTable.bengali_dict); gurmukhi_dict_rev = reverse(myTable.gurmukhi_dict); malayalam_dict_rev = reverse(myTable.malayalam_dict); oriya_dict_rev = reverse(myTable.oriya_dict); english_dict_rev = reverse(myTable.english_dict); } function detectLanguage(inp_txt){ var indx; var chr; for (indx = 0; indx < inp_txt.length; indx++){ chr = inp_txt.charAt(indx); if(chr == "\u0950") { // skip Devanagari 'AUM', since it is used across all Indian languages continue; } else if((array_key_exists(chr, devanagari_dict_rev["Independent_vowels"])) || (array_key_exists(chr, devanagari_dict_rev["Consonants"]))) { return "Devanagari"; } else if((array_key_exists(chr, telugu_dict_rev["Independent_vowels"])) || (array_key_exists(chr, telugu_dict_rev["Consonants"]))) { return "Telugu"; } else if((array_key_exists(chr, kannada_dict_rev["Independent_vowels"])) || (array_key_exists(chr, kannada_dict_rev["Consonants"]))) { return "Kannada"; } else if((array_key_exists(chr, gujarati_dict_rev["Independent_vowels"])) || (array_key_exists(chr, gujarati_dict_rev["Consonants"]))) { return "Gujarati"; } else if((array_key_exists(chr, tamil_dict_rev["Independent_vowels"])) || (array_key_exists(chr, tamil_dict_rev["Consonants"]))) { return "Tamil"; } else if((array_key_exists(chr, bengali_dict_rev["Independent_vowels"])) || (array_key_exists(chr, bengali_dict_rev["Consonants"]))) { return "Bengali"; } else if((array_key_exists(chr, gurmukhi_dict_rev["Independent_vowels"])) || (array_key_exists(chr, gurmukhi_dict_rev["Consonants"]))) { return "Gurmukhi"; } else if((array_key_exists(chr, malayalam_dict_rev["Independent_vowels"])) || (array_key_exists(chr, malayalam_dict_rev["Consonants"]))) { return "Malayalam"; } else if((array_key_exists(chr, oriya_dict_rev["Independent_vowels"])) || (array_key_exists(chr, oriya_dict_rev["Consonants"]))) { return "Oriya"; } } return "English"; // default } function convert2IndicScript(inp_txt, encoding_type, indicScript, modeStrict, reverse, preferASCIIDigits) { var indx=0; var out = ""; var vovel_needed_p = false; var word_start_p = true; var prev_Type = "NoMatch"; var insideTag_p = false; var blk, blkLen, Type; // Assigning the dictionary var lang_dict; if(reverse){ if(indicScript == "Devanagari"){lang_dict = devanagari_dict_rev;} else if(indicScript == "Telugu"){lang_dict = telugu_dict_rev;} else if(indicScript == "Kannada"){lang_dict = kannada_dict_rev;} else if(indicScript == "Gujarati"){lang_dict = gujarati_dict_rev;} else if(indicScript == "Tamil"){lang_dict = tamil_dict_rev;} else if(indicScript == "Bengali"){lang_dict = bengali_dict_rev;} else if(indicScript == "Gurmukhi"){lang_dict = gurmukhi_dict_rev;} else if(indicScript == "Malayalam"){lang_dict = malayalam_dict_rev;} else if(indicScript == "Oriya"){lang_dict = oriya_dict_rev;} else {lang_dict = english_dict_rev;} } else if(modeStrict){ // orignal dictionaries if modeStrict if(indicScript == "Devanagari"){lang_dict = myTable.devanagari_dict;} else if(indicScript == "Telugu"){lang_dict = myTable.telugu_dict;} else if(indicScript == "Kannada"){lang_dict = myTable.kannada_dict;} else if(indicScript == "Gujarati"){lang_dict = myTable.gujarati_dict;} else if(indicScript == "Tamil"){lang_dict = myTable.tamil_dict;} else if(indicScript == "Bengali"){lang_dict = myTable.bengali_dict;} else if(indicScript == "Gurmukhi"){lang_dict = myTable.gurmukhi_dict;} else if(indicScript == "Malayalam"){lang_dict = myTable.malayalam_dict;} else if(indicScript == "Oriya"){lang_dict = myTable.oriya_dict;} else {lang_dict = myTable.english_dict;} } else { // modified/extended dictionaries if not modeStrict if(indicScript == "Devanagari"){lang_dict = devanagari_dict_mod;} else if(indicScript == "Telugu"){lang_dict = telugu_dict_mod;} else if(indicScript == "Kannada"){lang_dict = kannada_dict_mod;} else if(indicScript == "Gujarati"){lang_dict = gujarati_dict_mod;} else if(indicScript == "Tamil"){lang_dict = tamil_dict_mod;} else if(indicScript == "Bengali"){lang_dict = bengali_dict_mod;} else if(indicScript == "Gurmukhi"){lang_dict = gurmukhi_dict_mod;} else if(indicScript == "Malayalam"){lang_dict = malayalam_dict_mod;} else if(indicScript == "Oriya"){lang_dict = oriya_dict_mod;} else {lang_dict = english_dict_mod;} } // convert to ITRANS if((!reverse) && ((encoding_type == "ISO") || (encoding_type == "IAST"))) { inp_txt = convert2ITRANS(inp_txt, encoding_type); } while (indx < inp_txt.length){ // skip space charecter "&nbsp;" if(inp_txt.substring(indx,indx+6) == "&nbsp;"){ if(vovel_needed_p){ out += lang_dict["VIRAMA"]; } out += "&nbsp;"; indx += 6; word_start_p = true; vovel_needed_p=0; continue; } [blk, blkLen, Type, vovel_needed_p, insideTag_p] = getNxtIndicChr(lang_dict, inp_txt.substring(indx), modeStrict, word_start_p, vovel_needed_p, insideTag_p, reverse, preferASCIIDigits); out += blk; if(Type == "NoMatch"){ //document.write( inp_txt.substring(indx, indx+blkLen)+": ***** NoMatch (blkLen)<br>"); indx += 1; word_start_p = true; } else{ //document.write( inp_txt.substring(indx, indx+blkLen)+": "+blk+" Match (blkLen)<br>"); indx += blkLen; word_start_p = false; } } if(vovel_needed_p){ out += lang_dict["VIRAMA"]; } vovel_needed_p=0; //document.getElementById("out_txt").value=out; return out; } function convert2ITRANS(inp_txt, encoding_type) { var insideTag_p = false; var indx=0; var out = ""; var blk, blkLen, Type, insideTag_p; var decoding_dict; // selecting appropriate dict to convert to ITRANS if(encoding_type == "ISO") { decoding_dict = myTable.iso2itrans_dict; } else if(encoding_type == "IAST") { decoding_dict = myTable.iast2itrans_dict; } else { return inp_txt; } while (indx < inp_txt.length){ [blk, blkLen, Type, insideTag_p] = convertNextBlk2ITRANS(decoding_dict, inp_txt.substring(indx), insideTag_p); out += blk; if(Type == "NoMatch"){ indx += 1; } else{ indx += blkLen; } } return out; } function convertNextBlk2ITRANS(trans_dict, inp_txt, insideTag_p){ var MAX=2; // *** set this var debug=0; var insideTag = insideTag_p; var Type = "NoMatch"; //default var out = ""; var blk = ""; var blkLen=MAX; while(blkLen > 0){ //if(debug){document.write( inp_txt.substring(0, blkLen)+" <br>");} // selecting block, skip it its a TAG i.e., inside < > if( (!insideTag) && (inp_txt.charAt(0) == "<") ){ insideTag = true; break; } else if( (insideTag) && (inp_txt.charAt(0) == ">") ){ insideTag = false; break; } else if(insideTag){ break; } blk= inp_txt.substring(0, blkLen); //if(debug){document.write( "<br>blk...:"+blk+" "+word_start+" "+vovel_needed+"<br>");} if( array_key_exists(blk, trans_dict) ){ Type = "Match"; out += trans_dict[blk]; //if(debug){document.write( "5: "+"-"+blk+" "+trans_dict[blk]);} break; } // No match for the taken block else{ blkLen -= 1; } } if(Type == "NoMatch"){// no match found out += inp_txt[0]; } else{ //if(debug){document.write( "Match "+vovel_needed+"<br>");} } //if(debug){document.write( "<br>returning "+out+" "+blkLen+"<br>");} return [out, blkLen, Type, insideTag]; }; function getNxtIndicChr(lang_dict, inp_txt, modeStrict, word_start_p, vovel_needed_p, insideTag_p, reverse, preferASCIIDigits){ var MAX=4; // *** set this var debug=0; var out = ""; var Type = "NoMatch"; //default var vovel_needed = vovel_needed_p; var word_start = word_start_p; var insideTag = insideTag_p; var blk = ""; var blkLen=MAX; var iteration = 1; // first time // decoding charecter-by-charecter in reverse convertion if(reverse){ blkLen=1; } while(blkLen > 0){ //if(debug){document.write( inp_txt.substring(0, blkLen)+" <br>");} // selecting block, skip it its a TAG i.e., inside < > if( (!insideTag) && (inp_txt.charAt(0) == "<") ){ insideTag = true; break; } else if( (insideTag) && (inp_txt.charAt(0) == ">") ){ insideTag = false; break; } else if(insideTag){ break; } else if(inp_txt.length >= blkLen){ // string is longer than or equal to blkLen blk= inp_txt.substring(0, blkLen); } else if(inp_txt.length > 0){ // string is shorter than blkLen blk = inp_txt.substring(0); } else{ // string is of zero length break; } //if(debug){document.write( "<br>blk...:"+blk+" "+word_start+" "+vovel_needed+"<br>");} // if not modeStrict, convert the 1st letter of every word to lower-case if((!modeStrict) && (word_start == true)){ blk = blk.substring(0,1).toLowerCase() + blk.substring(1); } // 2nd iteration ==> working case-insensitive if((!modeStrict) && (iteration == 2)){ blk = blk.toLowerCase(); } // Accent marks : Do not change any flags for this case, except "Type" if(array_key_exists(blk, lang_dict["Accent_marks"])){ Type = "Accent"; out += lang_dict["Accent_marks"][blk]; //if(debug){document.write( "0: "+blk+" "+lang_dict["Accent_marks"][blk]+"<br>");} break; } // Independent vowels /*else if( (reverse || !vovel_needed) // for reverse convertion, vovel_needed condition is not required // *** This will be lossy translation *** // e.g., रई -> rii -> री */ else if( (vovel_needed == false) && (array_key_exists(blk, lang_dict["Independent_vowels"])) ){ Type = "Independent"; vovel_needed=0; out += lang_dict["Independent_vowels"][blk]; //if(debug){document.write( "5: "+"-"+blk+" "+lang_dict["Independent_vowels"][blk]);} break; } // Dependent vowels else if((vovel_needed) && (array_key_exists(blk, lang_dict["Dependent_vowel"])) ){ Type = "Vowel"; vovel_needed=0; out += lang_dict["Dependent_vowel"][blk]; //if(debug){document.write( "7: "+blk+" "+lang_dict["Dependent_vowel"][blk]);} break; } // Consonants else if(array_key_exists((blk), lang_dict["Consonants"])){ if(vovel_needed){ out += lang_dict["VIRAMA"]; } Type = "Consonants"; vovel_needed=1; out += lang_dict["Consonants"][blk]; //if(debug){document.write( "8: "+blk+" "+lang_dict["Consonants"][blk]);} break; } // Others [Do not convert ASCII Digits if option is selected] else if( !((isASCIIDigit(blk) == true) && (preferASCIIDigits == true)) && array_key_exists(blk, lang_dict["Others"])){ if(vovel_needed){ out += lang_dict["VIRAMA"]; } Type = "Other"; vovel_needed = 0; // nullify "a"+".h" in reverse conversion if(lang_dict["Others"][blk] == ".h"){ out = out.substring(0, out.length-1); } else { out += lang_dict["Others"][blk]; } //if(debug){document.write( "9: "+blk+" "+lang_dict["Others"][blk]+"<br>");} break; } // No match for the taken block else{ // 2nd iteration ==> repeat as case-insensitive if((!modeStrict) && (iteration == 1)){ iteration += 1; continue; } blkLen -= 1; } } if(Type == "NoMatch"){ // no match found if(vovel_needed){ out += lang_dict["VIRAMA"]; } //if(debug){document.write( "No match "+vovel_needed+"<br>");} out += inp_txt[0]; word_start = true; vovel_needed=0; } else{ //if(debug){document.write( "Match "+vovel_needed+"<br>");} word_start = false; } //if(debug){document.write( "<br>returning "+out+" "+blkLen+" "+Type+" "+vovel_needed+"<br>");} return [out, blkLen, Type, vovel_needed, insideTag]; }; function array_key_exists(key, dict) { if (key in dict) return true; else return false; } // to extend dictionaries function extend(org_dict) { var ext_dict = { "Independent_vowels" : { "ee" : org_dict['Independent_vowels']["E"] }, "Dependent_vowel" : { "ee" : org_dict['Dependent_vowel']["E"] }, "Consonants" : { "c" : org_dict['Consonants']["k"], "f" : org_dict['Consonants']["ph"], "z" : org_dict['Consonants']["j"], // Modifications eto IAST/ITRANS "t" : org_dict['Consonants']["T"], "tt" : org_dict['Consonants']["Th"], "th" : org_dict['Consonants']["t"], "tth" : org_dict['Consonants']["th"], "d" : org_dict['Consonants']["D"], "dd" : org_dict['Consonants']["Dh"], "dh" : org_dict['Consonants']["d"], "ddh" : org_dict['Consonants']["dh"] } }; var new_dict = cloneDict(org_dict); for (var property in ext_dict) { for(var key in ext_dict[property]){ if (ext_dict[property][key]) { new_dict[property][key] = ext_dict[property][key]; } } } return new_dict; }; // clone dictionaries function cloneDict(dict) { if(typeof(dict) != 'object') return dict; if(dict == null) return dict; var new_dict = new Object(); for(var property in dict){ new_dict[property] = cloneDict(dict[property]); } return new_dict; } // to extend dictionaries function reverse(org_dict) { var new_dict = new Object(); for (var property in org_dict) { new_dict[property] = cloneRevDict(org_dict[property]); } // nullify the adding of "VIRAMA" new_dict["VIRAMA"] = "a"; return new_dict; }; // clone dictionaries function cloneRevDict(dict) { if(typeof(dict) != 'object') return dict; if(dict == null) return dict; var new_dict = new Object(); for(var property in dict){ new_dict[dict[property]] = property; } return new_dict; } function isASCIIDigit(n) { return ((n>=0) && (n<=9)); } function convert2Katapayadi(inp_txt) { var indx=0, dict_indx; var out = ""; var insideTag = false; while (indx < inp_txt.length){ // skip space charecter "&nbsp;" if(inp_txt.substring(indx,indx+6) == "&nbsp;"){ out += "&nbsp;"; indx += 6; continue; } else if( (!insideTag) && (inp_txt.charAt(indx) == "<") ){ insideTag = true; out += inp_txt.charAt(indx); ++indx; } else if( (insideTag) && (inp_txt.charAt(indx) == ">") ){ insideTag = false; out += inp_txt.charAt(indx); ++indx; } else if(insideTag){ out += inp_txt.charAt(indx); ++indx; } else{ for(dict_indx=0; dict_indx<=9; ++dict_indx) { // if next charecter is VIRAMA, this char should be neglected if((katapayadi_dict[dict_indx].indexOf(inp_txt.charAt(indx)) >= 0) && (katapayadi_dict[10].indexOf(inp_txt.charAt(indx+1)) == -1)){ out += dict_indx.toString(); break; } } ++indx; } } return out; } exports.init = init; exports.detectLanguage = detectLanguage; exports.convert2IndicScript = convert2IndicScript; exports.convert2Katapayadi = convert2Katapayadi;
mohancloudworld/Parivartan
src/lib/myModule.js
JavaScript
mpl-2.0
18,889
#include "plastiqmethod.h" #include "plastiqqcolormap.h" #include <QColormap> #include <QColor> QHash<QByteArray, PlastiQMethod> PlastiQQColormap::plastiqConstructors = { { "QColormap(QColormap&)", { "QColormap", "QColormap&", "QColormap*", 0, PlastiQMethod::Public, PlastiQMethod::Constructor } }, }; QHash<QByteArray, PlastiQMethod> PlastiQQColormap::plastiqMethods = { { "colorAt(long)", { "colorAt", "uint", "const QColor", 0, PlastiQMethod::Public, PlastiQMethod::Method } }, { "depth()", { "depth", "", "int", 1, PlastiQMethod::Public, PlastiQMethod::Method } }, { "mode()", { "mode", "", "Mode", 2, PlastiQMethod::Public, PlastiQMethod::Method } }, { "pixel(QColor&)", { "pixel", "QColor&", "uint", 3, PlastiQMethod::Public, PlastiQMethod::Method } }, { "size()", { "size", "", "int", 4, PlastiQMethod::Public, PlastiQMethod::Method } }, { "instance()", { "instance", "", "QColormap", 5, PlastiQMethod::StaticPublic, PlastiQMethod::Method } }, { "instance(int)", { "instance", "int", "QColormap", 6, PlastiQMethod::StaticPublic, PlastiQMethod::Method } }, }; QHash<QByteArray, PlastiQMethod> PlastiQQColormap::plastiqSignals = { }; QHash<QByteArray, PlastiQProperty> PlastiQQColormap::plastiqProperties = { }; QHash<QByteArray, long> PlastiQQColormap::plastiqConstants = { /* QColormap::Mode */ { "Direct", QColormap::Direct }, { "Indexed", QColormap::Indexed }, { "Gray", QColormap::Gray }, }; QVector<PlastiQMetaObject*> PlastiQQColormap::plastiqInherits = { }; const PlastiQ::ObjectType PlastiQQColormap::plastiq_static_objectType = PlastiQ::IsQtObject; PlastiQMetaObject PlastiQQColormap::plastiq_static_metaObject = { { Q_NULLPTR, &plastiqInherits, "QColormap", &plastiq_static_objectType, &plastiqConstructors, &plastiqMethods, &plastiqSignals, &plastiqProperties, &plastiqConstants, plastiq_static_metacall } }; const PlastiQMetaObject *PlastiQQColormap::plastiq_metaObject() const { return &plastiq_static_metaObject; } void PlastiQQColormap::plastiq_static_metacall(PlastiQObject *object, PlastiQMetaObject::Call call, int id, const PMOGStack &stack) { if(call == PlastiQMetaObject::CreateInstance) { QColormap *o = Q_NULLPTR; switch(id) { case 0: o = new QColormap((*reinterpret_cast< QColormap(*) >(stack[1].s_voidp))); break; default: ; } /*%UPDATEWRAPPER%*/ PlastiQQColormap *p = new PlastiQQColormap(); p->plastiq_setData(reinterpret_cast<void*>(o), p); PlastiQObject *po = static_cast<PlastiQObject*>(p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = po; } else if(call == PlastiQMetaObject::CreateDataInstance) { PlastiQQColormap *p = new PlastiQQColormap(); p->plastiq_setData(stack[1].s_voidp, p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = p; } else if(call == PlastiQMetaObject::InvokeMethod || call == PlastiQMetaObject::InvokeStaticMember) { if(id >= 7) { id -= 7; return; } bool sc = call == PlastiQMetaObject::InvokeStaticMember; bool isWrapper = sc ? false : object->isWrapper(); QColormap *o = sc ? Q_NULLPTR : reinterpret_cast<QColormap*>(object->plastiq_data()); switch(id) { case 0: { /* COPY OBJECT */ QColor *_r = new QColor(o->colorAt(stack[1].s_long)); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QColor"; stack[0].type = PlastiQ::QtObject; } break; case 1: { int _r = o->depth(); stack[0].s_int = _r; stack[0].type = PlastiQ::Int; } break; case 2: { qint64 _r = o->mode(); // HACK for Mode stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break; case 3: { long _r = o->pixel((*reinterpret_cast< QColor(*) >(stack[1].s_voidp))); stack[0].s_long = _r; stack[0].type = PlastiQ::Long; } break; case 4: { int _r = o->size(); stack[0].s_int = _r; stack[0].type = PlastiQ::Int; } break; case 5: { /* COPY OBJECT */ QColormap *_r = sc ? new QColormap(QColormap::instance()) : new QColormap(o->instance()); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QColormap"; stack[0].type = PlastiQ::QtObject; } break; case 6: { /* COPY OBJECT */ QColormap *_r = sc ? new QColormap(QColormap::instance(stack[1].s_int)) : new QColormap(o->instance(stack[1].s_int)); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QColormap"; stack[0].type = PlastiQ::QtObject; } break; default: ; } } else if(call == PlastiQMetaObject::ToQObject) { } else if(call == PlastiQMetaObject::HaveParent) { stack[0].s_bool = false; } else if(call == PlastiQMetaObject::DownCast) { QByteArray className = stack[1].s_bytearray; QColormap *o = reinterpret_cast<QColormap*>(object->plastiq_data()); stack[0].s_voidp = Q_NULLPTR; stack[0].name = "Q_NULLPTR"; } } PlastiQQColormap::~PlastiQQColormap() { QColormap* o = reinterpret_cast<QColormap*>(plastiq_data()); if(o != Q_NULLPTR) { delete o; } o = Q_NULLPTR; plastiq_setData(Q_NULLPTR, Q_NULLPTR); }
ArtMares/PQStudio
Builder/plastiq/include/widgets/PlastiQQColormap/plastiqqcolormap.cpp
C++
mpl-2.0
5,448
/* * !++ * QDS - Quick Data Signalling Library * !- * Copyright (C) 2002 - 2021 Devexperts LLC * !- * 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/. * !__ */ package com.devexperts.util; import java.util.IdentityHashMap; import java.util.Map; /** * Typed thread-safe key-value map where different values have different types and are distinguished * by globally-unique keys that are instances of {@link TypedKey}. */ @SuppressWarnings({"unchecked"}) public class TypedMap { private final Map<TypedKey<?>, Object> values = new IdentityHashMap<>(); /** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. */ public synchronized <T> T get(TypedKey<T> key) { return (T) values.get(key); } /** * Changes the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old value is replaced by the specified value. */ public synchronized <T> void set(TypedKey<T> key, T value) { values.put(key, value); } @Override public String toString() { return values.toString(); } }
Devexperts/QD
dxlib/src/main/java/com/devexperts/util/TypedMap.java
Java
mpl-2.0
1,349
/* * Copyright (c) 1998-2014 by Richard A. Wilkes. All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public License, * version 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 Source Code Form is "Incompatible With Secondary Licenses", as defined * by the Mozilla Public License, version 2.0. */ package com.trollworks.gcs.character; import com.trollworks.toolkit.ui.GraphicsUtilities; import com.trollworks.toolkit.ui.UIUtilities; import com.trollworks.toolkit.ui.print.PrintManager; import com.trollworks.toolkit.utility.units.LengthUnits; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; /** A printer page. */ public class Page extends JPanel { private PageOwner mOwner; /** * Creates a new page. * * @param owner The page owner. */ public Page(PageOwner owner) { super(new BorderLayout()); mOwner = owner; setOpaque(true); setBackground(Color.white); PrintManager pageSettings = mOwner.getPageSettings(); Insets insets = mOwner.getPageAdornmentsInsets(this); double[] size = pageSettings != null ? pageSettings.getPageSize(LengthUnits.POINTS) : new double[] { 8.5 * 72.0, 11.0 * 72.0 }; double[] margins = pageSettings != null ? pageSettings.getPageMargins(LengthUnits.POINTS) : new double[] { 36.0, 36.0, 36.0, 36.0 }; setBorder(new EmptyBorder(insets.top + (int) margins[0], insets.left + (int) margins[1], insets.bottom + (int) margins[2], insets.right + (int) margins[3])); Dimension pageSize = new Dimension((int) size[0], (int) size[1]); UIUtilities.setOnlySize(this, pageSize); setSize(pageSize); } @Override protected void paintComponent(Graphics gc) { super.paintComponent(GraphicsUtilities.prepare(gc)); mOwner.drawPageAdornments(this, gc); } }
smithkm/gcs
src/com/trollworks/gcs/character/Page.java
Java
mpl-2.0
1,978
import json import mock from django.test import TestCase from django.core.urlresolvers import reverse class TestAPI(TestCase): @mock.patch('ldap.initialize') def test_exists(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:exists') response = self.client.get(url) self.assertEqual(response.status_code, 400) # check that 400 Bad Request errors are proper JSON self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual( json.loads(response.content), {'error': "missing key 'mail'"} ) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'}, } def search_s(base, scope, filterstr, *args, **kwargs): if 'peter@example.com' in filterstr: # if 'hgaccountenabled=TRUE' in filterstr: # return [] return result.items() return [] connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': 'peter@example.com'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': 'never@heard.of.com'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False) # response = self.client.get(url, {'mail': 'peter@example.com', # 'hgaccountenabled': ''}) # self.assertEqual(response.status_code, 200) # self.assertEqual(json.loads(response.content), False) response = self.client.get(url, {'mail': 'peter@example.com', 'gender': 'male'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), True) @mock.patch('ldap.initialize') def test_employee(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:employee') response = self.client.get(url) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': 'peter@mozilla.com', 'sn': u'B\xe3ngtsson'}, } def search_s(base, scope, filterstr, *args, **kwargs): if 'peter@example.com' in filterstr: return result.items() return [] connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': 'peter@example.com'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': 'never@heard.of.com'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), False) @mock.patch('ldap.initialize') def test_ingroup(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:in-group') response = self.client.get(url) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': 'peter@example.com'}) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': 'peter@example.com', 'cn': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'}, } def search_s(base, scope, filterstr, *args, **kwargs): if 'ou=groups' in base: if ( 'peter@example.com' in filterstr and 'cn=CrashStats' in filterstr ): return result.items() else: # basic lookup if 'peter@example.com' in filterstr: return result.items() return [] connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': 'not@head.of.com', 'cn': 'CrashStats'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False) response = self.client.get(url, {'mail': 'peter@example.com', 'cn': 'CrashStats'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': 'peter@example.com', 'cn': 'NotInGroup'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False)
mozilla/medlem
medlem/api/tests.py
Python
mpl-2.0
5,529
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MWLite.Core; namespace MWLite.GUI.Helpers { internal static class PluginHelper { public static void Init(IMapApp app) { ShapeEditor.Editor.Init(app); } } }
MapWindow/MapWinGIS
demo/MWLite.GUI/Helpers/PluginHelper.cs
C#
mpl-2.0
316
# 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/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch()
digidotcom/transport_examples
WR31/doormon.py
Python
mpl-2.0
3,979
// 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/. package biglog import ( "errors" "fmt" "io" "sync" "sync/atomic" "time" ) // ErrInvalidIndexReader is returned on read with nil pointers var ErrInvalidIndexReader = errors.New("biglog: invalid reader - use NewIndexReader") // ErrNeedMoreBytes is returned by in the index reader when a single entry does not fit the requested byte limit // usually the client should double the size when possible and request again var ErrNeedMoreBytes = errors.New("biglog: maxBytes too low for any entry") // ErrNeedMoreOffsets is returned by in the index reader when a single entry does not fit the requested offset limit // usually the client should double the size when possible and request again var ErrNeedMoreOffsets = errors.New("biglog: maxOffsets too low for any entry") // IndexReader keeps the state among separate concurrent reads // IndexReaders handle segment transitions transparently type IndexReader struct { mu sync.Mutex iFO uint32 // file offset of the reader over the index bl *BigLog seg *segment } // IndexSection holds information about a set of entries of an index // this information is often used to "drive" a data reader, since this is more performant // than getting a set of entries. type IndexSection struct { // Offset where the section begins, corresponds with the offset of the first message Offset int64 // ODelta is the number of offsets held by the section ODelta int64 // EDelta is the number of index entries held by the section EDelta int64 // Size is the size of the data mapped by this index section Size int64 } // Entry n holds information about one single entry in the index type Entry struct { // Timestamp of the entry Timestamp time.Time // Offset corresponds with the offset of the first message Offset int64 // ODelta is the number of offsets held by this entry ODelta int // Size is the size of the data mapped by this entry Size int } // NewIndexReader returns an IndexReader that will start reading from a given offset func NewIndexReader(bl *BigLog, from int64) (r *IndexReader, ret int64, err error) { seg, RO, err := bl.locateOffset(from) if err != nil { return nil, 0, err } ret = from l, err := seg.Lookup(RO) if err == ErrEmbeddedOffset { ret = from - int64(RO-l.fRO) } else if err != nil { return nil, 0, err } r = &IndexReader{ iFO: l.iFO, bl: bl, } r.setSegment(seg) bl.addReader(r) return r, ret, err } // ReadEntries reads n entries from the index. This method is useful when scanning single entries one by one // for streaming use, ReadSection is recommended func (r *IndexReader) ReadEntries(n int) (entries []*Entry, err error) { r.mu.Lock() defer r.mu.Unlock() if r == nil || r.seg == nil { return nil, ErrInvalidIndexReader } entries = make([]*Entry, 0, n) for i := 0; i < n; i++ { err = r.jumpSeg() if err != nil { break } RO, TS, dFO := readEntry(r.seg.index[r.iFO:]) NRO, _, NdFO := readEntry(r.seg.index[r.iFO+iw:]) entries = append(entries, &Entry{ Timestamp: time.Unix(int64(TS), 0), Offset: absolute(RO, r.seg.baseOffset), ODelta: int(NRO - RO), Size: int(NdFO - dFO), }) // advance on index r.iFO += iw } return entries, err } // ReadSection reads the section of the index that contains a maximum of offsets or bytes // it's lower precision than ReadEntries but better suited for streaming since it does not need to allocate // an Entry struct for every entry read in the index. func (r *IndexReader) ReadSection(maxOffsets, maxBytes int64) (is *IndexSection, err error) { r.mu.Lock() defer r.mu.Unlock() if r == nil || r.seg == nil { return nil, ErrInvalidIndexReader } is = &IndexSection{} var firstIter = true for { err = r.jumpSeg() if err != nil { break } RO, _, dFO := readEntry(r.seg.index[r.iFO:]) NRO, _, NdFO := readEntry(r.seg.index[r.iFO+iw:]) // check offset limit if is.ODelta+int64(NRO-RO) > maxOffsets { if firstIter { return nil, ErrNeedMoreOffsets } break } // check byte limit if is.Size+NdFO-dFO > maxBytes { if firstIter { return nil, ErrNeedMoreBytes } break } if firstIter { firstIter = false is.Offset = absolute(RO, r.seg.baseOffset) } is.EDelta++ is.ODelta += int64(NRO - RO) is.Size += NdFO - dFO // advance on index r.iFO += iw } return is, err } // Jump segment if we are at the end of the current one func (r *IndexReader) jumpSeg() error { if r.iFO < atomic.LoadUint32(&r.seg.NiFO) { return nil } seg := r.nextSeg() if seg == nil { return io.EOF } r.setSegment(seg) r.iFO = 0 return nil } // we need to scan all segments again since the slice could have changed since the last read func (r *IndexReader) nextSeg() (seg *segment) { segs := r.bl.segments() i := indexOfSegment(segs, r.seg.baseOffset) if i < 0 || i == len(segs)-1 { return nil } return segs[i+1] } // Close frees up the segments and renders the reader unusable // returns nil error to satisfy io.Closer func (r *IndexReader) Close() error { r.bl.removeReader(r) atomic.AddInt32(r.seg.readers, -1) r = nil return nil } // Head returns the current offset position of the reader func (r *IndexReader) Head() int64 { r.mu.Lock() defer r.mu.Unlock() return r.head() } func (r *IndexReader) head() int64 { RO, _, _ := readEntry(r.seg.index[r.iFO:]) return absolute(RO, r.seg.baseOffset) } // Seek implements the io.Seeker interface for an index reader. func (r *IndexReader) Seek(offset int64, whence int) (ret int64, err error) { r.mu.Lock() defer r.mu.Unlock() switch whence { case 0: case 1: offset += r.head() case 2: offset += r.bl.Latest() default: panic(fmt.Sprintf("unsupported index reader whence = %d", whence)) } if r == nil || r.seg == nil { return -1, ErrInvalidReader } seg, RO, err := r.bl.locateOffset(offset) if err != nil { return -1, err } ret = offset l, err := seg.Lookup(RO) if err == ErrEmbeddedOffset { ret = offset - int64(RO-l.fRO) } else if err != nil { return -1, err } r.setSegment(seg) r.iFO = l.iFO return ret, err } func (r *IndexReader) setSegment(seg *segment) { if r.seg != nil { atomic.AddInt32(r.seg.readers, -1) } atomic.AddInt32(seg.readers, 1) r.seg = seg }
ninibe/netlog
biglog/index_reader.go
GO
mpl-2.0
6,459
/* 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/. */ package etomica.data.history; /** * History that records a data from a simulation. When existing space * is insufficient to hold new data, the array to hold the data is doubled * in length. * * @author Andrew Schultz */ public class HistoryComplete implements History { public HistoryComplete() {this(100);} public HistoryComplete(int n) { setHistoryLength(n); reset(); doCollapseOnReset = true; } /** * Sets the number of values kept in the history. */ public void setHistoryLength(int n) { int originalLength = history.length; if (n < cursor) { throw new IllegalArgumentException("decreasing history length would clobber data"); } if (n==originalLength) return; double[] temp = new double[n]; System.arraycopy(xValues,0,temp,0,cursor); xValues = temp; for (int i = cursor; i<n; i++) { xValues[i] = Double.NaN; } temp = new double[n]; System.arraycopy(history,0,temp,0,cursor); history = temp; for (int i = cursor; i<n; i++) { history[i] = Double.NaN; } } public int getHistoryLength() { return history.length; } public int getSampleCount() { return cursor; } /** * Removes entire history, setting all values to NaN. */ public void reset() { int nValues = getHistoryLength(); if (doCollapseOnReset && nValues > 100) { xValues = new double[100]; history = new double[100]; } for(int i=0; i<nValues; i++) { xValues[i] = Double.NaN; history[i] = Double.NaN; } cursor = 0; } public double[] getXValues() { return xValues; } public boolean addValue(double x, double y) { if (cursor == history.length) { int newLength = history.length*2; if (newLength == 0) { newLength = 1; } setHistoryLength(newLength); } xValues[cursor] = x; history[cursor] = y; cursor++; return true; } /** * Returns an the history */ public double[] getHistory() { return history; } /** * Sets a flag that determines if the history is collapsed (to 100 data * points) when reset is called. If the current history length is less * than 100, the history length is unchanged. */ public void setCollapseOnReset(boolean flag) { doCollapseOnReset = flag; } /** * Returns true if the history is collapsed (to 100 data points) when reset * is called. If the current history length is less than 100, the history * length is unchanged. */ public boolean isCollapseOnReset() { return doCollapseOnReset; } public boolean willDiscardNextData() { return false; } private double[] history = new double[0]; private double[] xValues = new double[0]; private int cursor; private boolean doCollapseOnReset; }
etomica/etomica
etomica-core/src/main/java/etomica/data/history/HistoryComplete.java
Java
mpl-2.0
3,360
/** * API for paddock information * * Copyright (c) 2015. Elec Research. * * 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/ * * Author: Tim Miller. * **/ var express = require('express'); var Paddock = agquire('ag/db/models-mongo/paddock'); var Reading = agquire('ag/db/models-mongo/reading'); var permissions = require('../../utils/permissions'); var responder = agquire('ag/routes/utils/responder'); var PaddockController = agquire('ag/db/controllers/PaddockController'); var router = express.Router(); /* Route HTTP Verb Description ===================================================== /api/paddocks GET Get paddocks. /api/paddocks/:object_id GET Get single paddock. /api/paddocks POST Create a paddock. /api/paddocks/:object_id PUT Update a paddock. /api/paddocks/:object_id DELETE Delete a paddock. */ /** * @api {post} /spatial/paddocks/ Create a Paddock * @apiName PostPaddocks * @apiGroup Paddocks * * @apiParam {String} name Name of new paddock. * @apiParam {Number} farm_id Id of farm that this paddock belongs to. * @apiParam {Object} loc contains coordinates of paddock. Must be a GeoJSON Polygon (see example). * @apiParam {String} [created] Timestamp of paddock creation time. * * * @apiParamExample {json} Request-Example: * { * "name": "Demo Paddock" * "farm_id": 1 * "loc": { * "coordinates":[ * [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] * ] * } * "created": "2015-04-19" * } * * @apiSuccessExample Success-Response * HTTP/1.1 200 OK * { * "paddock": * { * "_id": "primary_key_string", * "name": "Demo Paddock", * "farm_id": 1, * "created": "2015-04-19", * "updated": "2015-04-19", * "loc" { * "type": "Polygon", * "coordinates": [ * [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] * ] * } * } * } * * @apiError IncompleteRequest Request body is missing required fields. * @apiErrorExample IncompleteRequest * HTTP/1.1 422 Unprocessable Entity * { * error: "Missing field response message" * } */ router.post('/', function(req, res) { var paddockDetails = req.body; var access = {}; access.requiredPermissions = [permissions.kEditFarmPermissions]; access.farm = {id: paddockDetails.farm_id}; responder.authAndRespond(req, res, access, function() { return { paddock: PaddockController.createPaddock(paddockDetails) } }); }); /** * @api {put} /spatial/paddocks/:id Update a Paddock * @apiName PutPaddocks * @apiGroup Paddocks * * @apiParam {string} id Primary key of updated paddock. * @apiParam (paddock) {String} [name] Name of updated paddock. * @apiParam (paddock) {Object} [loc] Corners of updated paddock. Must be a GeoJSON Polygon (see example). * @apiParam (paddock) {Object} [updated] Timestamp of update time. * * @apiSuccessExample Success-Response * HTTP/1.1 200 OK * { * "paddock": * { * "_id": "primary_key_string", * "name": "Demo Paddock", * "farm_id": 1, * "created": "2015-04-19" * "loc" * { * "type": "Polygon", * "coordinates": * [ * [ * [0, 0], [0, 1], [1, 1], [1, 0], [0, 0] * ] * ] * } * } * } * * @apiError PaddockNotFound could find paddock with object_id parameter. * @apiErrorExample PaddockNotFound * HTTP/1.1 422 Unprocessable Entity * { * error: "Paddock Not Found" * } */ router.put('/:object_id', function(req, res) { var id = req.params.object_id; var paddockDetails = req.body; // get paddock first for purpose of checking farm permissions return PaddockController.getOnePaddock(id) .then(function(paddock) { var access = {}; access.requiredPermissions = [permissions.kEditFarmPermissions]; access.farm = {id: paddockDetails.farm_id}; responder.authAndRespond(req, res, access, function() { return { paddock: PaddockController.updatePaddock(id, paddockDetails) } }); }) .catch(function(err) { return res.status(422).send({error: err.message}); }); }); /** * Delete paddock */ /** * @api {delete} /spatial/paddocks/:id Delete a Paddock * @apiName DeletePaddocks * @apiGroup Paddocks * * @apiParam {string} id Primary key of paddock to delete. * * @apiError PaddockNotFound could find paddock with object_id parameter. * @apiErrorExample PaddockNotFound * HTTP/1.1 422 Unprocessable Entity * { * error: "Paddock Not Found" * } * * @apiError RemovePastureMeasurementError couldn't remove pasture measurements that belong to paddock. * @apiErrorExample RemovePastureMeasurementError * HTTP/1.1 422 Unprocessable Entity * { * error: "Couldn't remove pasture measurements, operation aborted" * } * * @apiSuccessExample * HTTP/1.1 200 OK * { * "result": 1 * } */ router.delete('/:object_id', function(req, res) { var id = req.params.object_id; // get paddock first for purpose of checking farm permissions return PaddockController.getOnePaddock(id) .then(function(paddock) { var access = {}; access.requiredPermissions = [permissions.kEditFarmPermissions]; access.farm = {id: paddock.farm_id}; responder.authAndRespond(req, res, access, function() { return { result: PaddockController.deletePaddock(id) } }); }) .catch(function(err) { return res.status(422).send({error: err.message}); }); /* return PaddockController.deletePaddock(id).then(function() { return res.send({message: 'Paddock Deleted'}); }) .catch(function(err){ return res.status(422).send({error: err.message}); }); */ }); /** * Get paddocks. */ /** * @api {get} /spatial/paddocks/ Get Paddocks * @apiName GetPaddocks * @apiGroup Paddocks * * @apiParam {Number} [include] List of objects to include in response (farm). * @apiParam {Number} [farm_id] Id of farm that contains requested paddocks. * @apiParam {Number} [limit] Maximum number of results that the query should return. The AgBase API cannot return more than 1000 results. * @apiParam {Number} [offset] The offset from the start of the query result. * @apiParam {String} [id] Id of paddock to return. * * @apiErrorExample Error-Response * HTTP/1.1 422 Unprocessable Entity * { * "error": "error message" * } * * @apiSuccessExample * HTTP/1.1 200 OK * { * "paddocks": * [ * { * "_id": "primary_key_string", * "name": "Demo Paddock", * "farm_id": 1, * "created": "2015-04-19" * "loc": * { * "type": "Polygon", * "coordinates": * [ * [ * [0, 0], [0, 1], [1, 1], [1, 0], [0, 0] * ] * ] * } * } * ] * } */ router.get('/', function(req, res) { var params = req.query; var access = {}; access.requiredPermissions = [permissions.kViewFarmPermissions]; if(params.id) { responder.authAndRespond(req, res, access, function() { return { paddock: PaddockController.getOnePaddock(params.id) } }); } else { var farms; var limit; var offset; var includeFarms = params.include === "farm"; if(params.farm_id) { farms = params.farm_id.split(','); access.farm = {id: farms}; } if(params.limit) { limit = params.limit; } if(params.offset) { offset = params.offset; } responder.authAndRespond(req, res, access, function() { return { paddocks: PaddockController.getPaddocks(includeFarms, farms, limit, offset) } }); } }); /** * countPaddocks(farms) * @api {get} /spatial/paddocks/count/ Get a count of Paddocks * @apiName CountPaddocks * @apiGroup Paddocks * * @apiParam {Number} [farm_id] Return paddocks that belong to farms defined by farm_id. * * @apiSuccessExample Success-Response * { * "count": <number of paddocks> * } */ router.get('/count/', function(req, res) { var params = req.query; var farms; if(params.farm_id) { farms = params.farm_id.split(','); } return PaddockController.countPaddocks(farms) .then(function(count) { return res.send({count: count}); }) .catch(function(err) { return res.status(422).send({error: err.message}); }); }); module.exports = router;
elec-otago/agbase
server/routes/api-authenticated/spatial/paddocks.js
JavaScript
mpl-2.0
9,912
using Anabi.Common.Enums; using Anabi.Features.Common.Models; namespace Anabi.Features.PrecautionaryMeasures { public class MeasuresDictionaryModel : DictionaryModel { public PrecautionaryMeasureType MeasureType { get; set; } } }
code4romania/anabi-gestiune-api
Anabi/Features/PrecautionaryMeasures/MeasuresDictionaryModel.cs
C#
mpl-2.0
254
import copy import logging import os import time from datetime import datetime from hashlib import sha1 import newrelic.agent from django.core.exceptions import ObjectDoesNotExist from django.db.utils import IntegrityError from past.builtins import long from treeherder.etl.artifact import (serialize_artifact_json_blobs, store_job_artifacts) from treeherder.etl.common import get_guid_root from treeherder.model.models import (BuildPlatform, FailureClassification, Job, JobGroup, JobLog, JobType, Machine, MachinePlatform, Option, OptionCollection, Product, Push, ReferenceDataSignatures, TaskclusterMetadata) logger = logging.getLogger(__name__) def _get_number(s): try: return long(s) except (ValueError, TypeError): return 0 def _remove_existing_jobs(data): """ Remove jobs from data where we already have them in the same state. 1. split the incoming jobs into pending, running and complete. 2. fetch the ``job_guids`` from the db that are in the same state as they are in ``data``. 3. build a new list of jobs in ``new_data`` that are not already in the db and pass that back. It could end up empty at that point. """ new_data = [] guids = [datum['job']['job_guid'] for datum in data] state_map = { guid: state for (guid, state) in Job.objects.filter( guid__in=guids).values_list('guid', 'state') } for datum in data: job = datum['job'] if not state_map.get(job['job_guid']): new_data.append(datum) else: # should not transition from running to pending, # or completed to any other state current_state = state_map[job['job_guid']] if current_state == 'completed' or ( job['state'] == 'pending' and current_state == 'running'): continue new_data.append(datum) return new_data def _load_job(repository, job_datum, push_id): """ Load a job into the treeherder database If the job is a ``retry`` the ``job_guid`` will have a special suffix on it. But the matching ``pending``/``running`` job will not. So we append the suffixed ``job_guid`` to ``retry_job_guids`` so that we can update the job_id_lookup later with the non-suffixed ``job_guid`` (root ``job_guid``). Then we can find the right ``pending``/``running`` job and update it with this ``retry`` job. """ build_platform, _ = BuildPlatform.objects.get_or_create( os_name=job_datum.get('build_platform', {}).get('os_name', 'unknown'), platform=job_datum.get('build_platform', {}).get('platform', 'unknown'), architecture=job_datum.get('build_platform', {}).get('architecture', 'unknown')) machine_platform, _ = MachinePlatform.objects.get_or_create( os_name=job_datum.get('machine_platform', {}).get('os_name', 'unknown'), platform=job_datum.get('machine_platform', {}).get('platform', 'unknown'), architecture=job_datum.get('machine_platform', {}).get('architecture', 'unknown')) option_names = job_datum.get('option_collection', []) option_collection_hash = OptionCollection.calculate_hash( option_names) if not OptionCollection.objects.filter( option_collection_hash=option_collection_hash).exists(): # in the unlikely event that we haven't seen this set of options # before, add the appropriate database rows options = [] for option_name in option_names: option, _ = Option.objects.get_or_create(name=option_name) options.append(option) for option in options: OptionCollection.objects.create( option_collection_hash=option_collection_hash, option=option) machine, _ = Machine.objects.get_or_create( name=job_datum.get('machine', 'unknown')) job_type, _ = JobType.objects.get_or_create( symbol=job_datum.get('job_symbol') or 'unknown', name=job_datum.get('name') or 'unknown') job_group, _ = JobGroup.objects.get_or_create( name=job_datum.get('group_name') or 'unknown', symbol=job_datum.get('group_symbol') or 'unknown') product_name = job_datum.get('product_name', 'unknown') if not product_name.strip(): product_name = 'unknown' product, _ = Product.objects.get_or_create(name=product_name) job_guid = job_datum['job_guid'] job_guid = job_guid[0:50] who = job_datum.get('who') or 'unknown' who = who[0:50] reason = job_datum.get('reason') or 'unknown' reason = reason[0:125] state = job_datum.get('state') or 'unknown' state = state[0:25] build_system_type = job_datum.get('build_system_type', 'buildbot') reference_data_name = job_datum.get('reference_data_name', None) default_failure_classification = FailureClassification.objects.get( name='not classified') sh = sha1() sh.update(''.join( map(str, [build_system_type, repository.name, build_platform.os_name, build_platform.platform, build_platform.architecture, machine_platform.os_name, machine_platform.platform, machine_platform.architecture, job_group.name, job_group.symbol, job_type.name, job_type.symbol, option_collection_hash, reference_data_name])).encode('utf-8')) signature_hash = sh.hexdigest() # Should be the buildername in the case of buildbot (if not provided # default to using the signature hash) if not reference_data_name: reference_data_name = signature_hash signature, _ = ReferenceDataSignatures.objects.get_or_create( name=reference_data_name, signature=signature_hash, build_system_type=build_system_type, repository=repository.name, defaults={ 'first_submission_timestamp': time.time(), 'build_os_name': build_platform.os_name, 'build_platform': build_platform.platform, 'build_architecture': build_platform.architecture, 'machine_os_name': machine_platform.os_name, 'machine_platform': machine_platform.platform, 'machine_architecture': machine_platform.architecture, 'job_group_name': job_group.name, 'job_group_symbol': job_group.symbol, 'job_type_name': job_type.name, 'job_type_symbol': job_type.symbol, 'option_collection_hash': option_collection_hash }) tier = job_datum.get('tier') or 1 result = job_datum.get('result', 'unknown') submit_time = datetime.fromtimestamp( _get_number(job_datum.get('submit_timestamp'))) start_time = datetime.fromtimestamp( _get_number(job_datum.get('start_timestamp'))) end_time = datetime.fromtimestamp( _get_number(job_datum.get('end_timestamp'))) # first, try to create the job with the given guid (if it doesn't # exist yet) job_guid_root = get_guid_root(job_guid) if not Job.objects.filter(guid__in=[job_guid, job_guid_root]).exists(): # This could theoretically already have been created by another process # that is running updates simultaneously. So just attempt to create # it, but allow it to skip if it's the same guid. The odds are # extremely high that this is a pending and running job that came in # quick succession and are being processed by two different workers. Job.objects.get_or_create( guid=job_guid, defaults={ "repository": repository, "signature": signature, "build_platform": build_platform, "machine_platform": machine_platform, "machine": machine, "option_collection_hash": option_collection_hash, "job_type": job_type, "job_group": job_group, "product": product, "failure_classification": default_failure_classification, "who": who, "reason": reason, "result": result, "state": state, "tier": tier, "submit_time": submit_time, "start_time": start_time, "end_time": end_time, "last_modified": datetime.now(), "push_id": push_id } ) # Can't just use the ``job`` we would get from the ``get_or_create`` # because we need to try the job_guid_root instance first for update, # rather than a possible retry job instance. try: job = Job.objects.get(guid=job_guid_root) except ObjectDoesNotExist: job = Job.objects.get(guid=job_guid) # add taskcluster metadata if applicable if all([k in job_datum for k in ['taskcluster_task_id', 'taskcluster_retry_id']]): try: TaskclusterMetadata.objects.create( job=job, task_id=job_datum['taskcluster_task_id'], retry_id=job_datum['taskcluster_retry_id']) except IntegrityError: pass # Update job with any data that would have changed Job.objects.filter(id=job.id).update( guid=job_guid, signature=signature, build_platform=build_platform, machine_platform=machine_platform, machine=machine, option_collection_hash=option_collection_hash, job_type=job_type, job_group=job_group, product=product, result=result, state=state, tier=tier, submit_time=submit_time, start_time=start_time, end_time=end_time, last_modified=datetime.now(), push_id=push_id) artifacts = job_datum.get('artifacts', []) has_text_log_summary = any(x for x in artifacts if x['name'] == 'text_log_summary') if artifacts: artifacts = serialize_artifact_json_blobs(artifacts) # need to add job guid to artifacts, since they likely weren't # present in the beginning for artifact in artifacts: if not all(k in artifact for k in ("name", "type", "blob")): raise ValueError( "Artifact missing properties: {}".format(artifact)) # Ensure every artifact has a ``job_guid`` value. # It is legal to submit an artifact that doesn't have a # ``job_guid`` value. But, if missing, it should inherit that # value from the job itself. if "job_guid" not in artifact: artifact["job_guid"] = job_guid store_job_artifacts(artifacts) log_refs = job_datum.get('log_references', []) job_logs = [] if log_refs: for log in log_refs: name = log.get('name') or 'unknown' name = name[0:50] url = log.get('url') or 'unknown' url = url[0:255] # this indicates that a summary artifact was submitted with # this job that corresponds to the buildbot_text log url. # Therefore, the log does not need parsing. So we should # ensure that it's marked as already parsed. if has_text_log_summary and name == 'buildbot_text': parse_status = JobLog.PARSED else: parse_status_map = dict([(k, v) for (v, k) in JobLog.STATUSES]) mapped_status = parse_status_map.get( log.get('parse_status')) if mapped_status: parse_status = mapped_status else: parse_status = JobLog.PENDING jl, _ = JobLog.objects.get_or_create( job=job, name=name, url=url, defaults={ 'status': parse_status }) job_logs.append(jl) _schedule_log_parsing(job, job_logs, result) return job_guid def _schedule_log_parsing(job, job_logs, result): """Kick off the initial task that parses the log data. log_data is a list of job log objects and the result for that job """ # importing here to avoid an import loop from treeherder.log_parser.tasks import parse_logs task_types = { "errorsummary_json", "buildbot_text", "builds-4h" } job_log_ids = [] for job_log in job_logs: # a log can be submitted already parsed. So only schedule # a parsing task if it's ``pending`` # the submitter is then responsible for submitting the # text_log_summary artifact if job_log.status != JobLog.PENDING: continue # if this is not a known type of log, abort parse if job_log.name not in task_types: continue job_log_ids.append(job_log.id) # TODO: Replace the use of different queues for failures vs not with the # RabbitMQ priority feature (since the idea behind separate queues was # only to ensure failures are dealt with first if there is a backlog). if result != 'success': queue = 'log_parser_fail' priority = 'failures' else: queue = 'log_parser' priority = "normal" parse_logs.apply_async(queue=queue, args=[job.id, job_log_ids, priority]) def store_job_data(repository, originalData): """ Store job data instances into jobs db Example: [ { "revision": "24fd64b8251fac5cf60b54a915bffa7e51f636b5", "job": { "job_guid": "d19375ce775f0dc166de01daa5d2e8a73a8e8ebf", "name": "xpcshell", "desc": "foo", "job_symbol": "XP", "group_name": "Shelliness", "group_symbol": "XPC", "product_name": "firefox", "state": "TODO", "result": 0, "reason": "scheduler", "who": "sendchange-unittest", "submit_timestamp": 1365732271, "start_timestamp": "20130411165317", "end_timestamp": "1365733932" "machine": "tst-linux64-ec2-314", "build_platform": { "platform": "Ubuntu VM 12.04", "os_name": "linux", "architecture": "x86_64" }, "machine_platform": { "platform": "Ubuntu VM 12.04", "os_name": "linux", "architecture": "x86_64" }, "option_collection": { "opt": true }, "log_references": [ { "url": "http://ftp.mozilla.org/pub/...", "name": "unittest" } ], artifacts:[{ type:" json | img | ...", name:"", log_urls:[ ] blob:"" }], }, "superseded": [] }, ... ] """ data = copy.deepcopy(originalData) # Ensure that we have job data to process if not data: return # remove any existing jobs that already have the same state data = _remove_existing_jobs(data) if not data: return superseded_job_guid_placeholders = [] # TODO: Refactor this now that store_job_data() is only over called with one job at a time. for datum in data: try: # TODO: this might be a good place to check the datum against # a JSON schema to ensure all the fields are valid. Then # the exception we caught would be much more informative. That # being said, if/when we transition to only using the pulse # job consumer, then the data will always be vetted with a # JSON schema before we get to this point. job = datum['job'] revision = datum['revision'] superseded = datum.get('superseded', []) revision_field = 'revision__startswith' if len(revision) < 40 else 'revision' filter_kwargs = {'repository': repository, revision_field: revision} push_id = Push.objects.values_list('id', flat=True).get(**filter_kwargs) # load job job_guid = _load_job(repository, job, push_id) for superseded_guid in superseded: superseded_job_guid_placeholders.append( # superseded by guid, superseded guid [job_guid, superseded_guid] ) except Exception as e: # Surface the error immediately unless running in production, where we'd # rather report it on New Relic and not block storing the remaining jobs. # TODO: Once buildbot support is removed, remove this as part of # refactoring this method to process just one job at a time. if 'DYNO' not in os.environ: raise logger.exception(e) # make more fields visible in new relic for the job # where we encountered the error datum.update(datum.get("job", {})) newrelic.agent.record_exception(params=datum) # skip any jobs that hit errors in these stages. continue # Update the result/state of any jobs that were superseded by those ingested above. if superseded_job_guid_placeholders: for (job_guid, superseded_by_guid) in superseded_job_guid_placeholders: Job.objects.filter(guid=superseded_by_guid).update( result='superseded', state='completed')
KWierso/treeherder
treeherder/etl/jobs.py
Python
mpl-2.0
18,563
package logmon import ( "context" "github.com/hashicorp/nomad/client/logmon/proto" ) type logmonClient struct { client proto.LogMonClient } func (c *logmonClient) Start(cfg *LogConfig) error { req := &proto.StartRequest{ LogDir: cfg.LogDir, StdoutFileName: cfg.StdoutLogFile, StderrFileName: cfg.StderrLogFile, MaxFiles: uint32(cfg.MaxFiles), MaxFileSizeMb: uint32(cfg.MaxFileSizeMB), StdoutFifo: cfg.StdoutFifo, StderrFifo: cfg.StderrFifo, } _, err := c.client.Start(context.Background(), req) return err } func (c *logmonClient) Stop() error { req := &proto.StopRequest{} _, err := c.client.Stop(context.Background(), req) return err }
nak3/nomad
client/logmon/client.go
GO
mpl-2.0
690
import React from 'react'; import cn from 'classnames'; import keyboardJS from 'keyboardjs'; import ReactTooltip from 'react-tooltip'; import sendToAddon from '../client-lib/send-to-addon'; export default class PrevButton extends React.Component { constructor(props) { super(props); this.state = {historyIndex: 0}; } componentDidMount() { // previous track keyboardJS.bind('<', () => this.prevTrack()); } prevTrack() { let index; // if clicked more than once within // 5 seconds increment the index so // the user can get to further back // in history. Resets when timeout wears out. if (this.searchingHistory) { if (this.props.history.length > this.state.historyIndex + 1) { this.setState({historyIndex: this.state.historyIndex + 1}); } index = this.state.historyIndex; } else { index = 0; this.searchingHistory = true; setTimeout(() => { this.searchingHistory = false; this.setState({historyIndex: 0}); }, 5000); } sendToAddon({ action: 'track-added-from-history', index }); } render() { return ( <div className={cn('prev-wrapper', {hidden: (!this.props.hovered && !this.props.minimized) || this.props.confirm || !this.props.history.length})}> <a onClick={this.prevTrack.bind(this)} className='prev' data-tip data-for='prev' /> <ReactTooltip id='prev' effect='solid' place='right'>{this.props.strings.ttPrev}</ReactTooltip> </div> ); } }
meandavejustice/min-vid
frontend/components/prev-button.js
JavaScript
mpl-2.0
1,552
<?php /** * Copyright 2006 - 2018 TubePress LLC (http://tubepress.com) * * This file is part of TubePress (http://tubepress.com) * * 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/. */ class tubepress_internal_boot_helper_uncached_UncachedContainerSupplier { /** * @var tubepress_api_log_LoggerInterface */ private $_logger; /** * @var bool */ private $_shouldLog; /** * @var tubepress_internal_boot_helper_uncached_Compiler */ private $_iocCompiler; /** * @var tubepress_internal_ioc_ContainerBuilder */ private $_containerBuilder; /** * @var \Symfony\Component\DependencyInjection\Dumper\DumperInterface */ private $_containerDumper; /** * @var tubepress_api_boot_BootSettingsInterface */ private $_bootSettings; /** * @var Symfony\Component\ClassLoader\MapClassLoader */ private $_mapClassLoader; /** * @var tubepress_internal_boot_helper_uncached_contrib_ManifestFinder */ private $_manifestFinder; /** * @var tubepress_internal_boot_helper_uncached_contrib_AddonFactory */ private $_addonFactory; /** * @var callable */ private $_serializer; public function __construct(tubepress_api_log_LoggerInterface $logger, tubepress_internal_boot_helper_uncached_contrib_ManifestFinder $manifestFinder, tubepress_internal_boot_helper_uncached_contrib_AddonFactory $addonFactory, tubepress_internal_boot_helper_uncached_Compiler $ici, tubepress_api_boot_BootSettingsInterface $sfri) { $this->_logger = $logger; $this->_shouldLog = $logger->isEnabled(); $this->_iocCompiler = $ici; $this->_bootSettings = $sfri; $this->_manifestFinder = $manifestFinder; $this->_addonFactory = $addonFactory; } public function getNewSymfonyContainer() { if (!isset($this->_containerBuilder)) { $this->_containerBuilder = new tubepress_internal_ioc_ContainerBuilder(); } $this->_containerBuilder->set('tubepress_api_ioc_ContainerInterface', $this->_containerBuilder); $this->_containerBuilder->set('symfony_service_container', $this->_containerBuilder->getDelegateContainerBuilder()); $this->_containerBuilder->set('tubepress_internal_logger_BootLogger', $this->_logger); $this->_containerBuilder->set(tubepress_api_boot_BootSettingsInterface::_, $this->_bootSettings); $addons = $this->_findAllAddons(); if ($this->_bootSettings->isClassLoaderEnabled()) { $this->_setupClassLoader($addons); } $this->_iocCompiler->compile($this->_containerBuilder, $addons); if ($this->_bootSettings->isClassLoaderEnabled()) { spl_autoload_unregister(array($this->_mapClassLoader, 'loadClass')); } return $this->_convertToSymfonyContainer($this->_containerBuilder); } private function _findAllAddons() { $manifests = $this->_manifestFinder->find(); $addons = array(); foreach ($manifests as $path => $data) { try { $errors = $this->_addonFactory->fromManifestData($path, $data); if (is_array($errors)) { //these will have been logged already continue; } $addons[] = $errors; } catch (Exception $e) { continue; } } if (!isset($this->_serializer)) { $this->_serializer = array( new tubepress_internal_boot_helper_uncached_Serializer($this->_bootSettings), 'serialize' ); } $artifacts = array( 'add-ons' => call_user_func($this->_serializer, $addons, $this->_bootSettings) ); $this->_containerBuilder->setParameter( tubepress_internal_boot_PrimaryBootstrapper::CONTAINER_PARAM_BOOT_ARTIFACTS, $artifacts ); return $addons; } private function _setupClassLoader(array $addons) { $addonClassMap = $this->_getClassMapFromAddons($addons); $fullClassMap = require TUBEPRESS_ROOT . '/src/php/scripts/classloading/classmap.php'; $finalClassMap = array_merge($fullClassMap, $addonClassMap); $this->_mapClassLoader = new \Symfony\Component\ClassLoader\MapClassLoader($finalClassMap); $systemCachePath = $this->_bootSettings->getPathToSystemCacheDirectory(); $dumpPath = $systemCachePath . DIRECTORY_SEPARATOR . 'classmap.php'; $exportedClassMap = var_export($finalClassMap, true); $toDump = sprintf('<?php return %s;', $exportedClassMap); if ($this->_shouldLog) { $this->_logDebug( sprintf('Our final classmap has <code>%d</code> classes in it. We\'ll try to dump it to <code>%s</code>.', count($finalClassMap), $dumpPath )); } $this->_mapClassLoader->register(); $result = @file_put_contents($dumpPath, $toDump); if ($this->_shouldLog) { if ($result !== false) { $msg = sprintf('Successfully wrote <code>%d</code> bytes to <code>%s</code>', $result, $dumpPath ); } else { $msg = sprintf('Unable to write to <code>%s</code>', $dumpPath); } $this->_logDebug($msg); } } /** * @param tubepress_internal_ioc_ContainerBuilder $containerBuilder * * @return \Symfony\Component\DependencyInjection\ContainerInterface */ private function _convertToSymfonyContainer(tubepress_internal_ioc_ContainerBuilder $containerBuilder) { if ($this->_shouldLog) { $this->_logDebug('Preparing to store boot to cache.'); } $dumpedContainerText = $this->_getDumpedSymfonyContainerAsString($containerBuilder->getDelegateContainerBuilder()); if ($this->_bootSettings->isSystemCacheEnabled()) { $cachePath = $this->_bootSettings->getPathToSystemCacheDirectory(); $storagePath = sprintf('%s%sTubePressServiceContainer.php', $cachePath, DIRECTORY_SEPARATOR); } else { $storagePath = tempnam(sys_get_temp_dir(), 'TubePressServiceContainer'); } if (!is_dir(dirname($storagePath))) { if ($this->_shouldLog) { $this->_logDebug(sprintf('Attempting to create all the parent directories of <code>%s</code>', $storagePath)); } $success = @mkdir(dirname($storagePath), 0755, true); if ($this->_shouldLog) { if ($success === true) { $this->_logDebug(sprintf('Created all the parent directories of <code>%s</code>', $storagePath)); } else { $this->_logger->error(sprintf('Failed to create all the parent directories of <code>%s</code>', $storagePath)); } } if ($success !== true) { return $containerBuilder->getDelegateContainerBuilder(); } } if ($this->_shouldLog) { $this->_logDebug(sprintf('Now writing dumped container to <code>%s</code>', $storagePath)); } $success = @file_put_contents($storagePath, $dumpedContainerText) !== false; if ($success) { if ($this->_shouldLog) { $this->_logDebug(sprintf('Saved service container to <code>%s</code>. Now including it.', $storagePath)); } if (!class_exists('TubePressServiceContainer', false)) { /** @noinspection PhpIncludeInspection */ require $storagePath; } } else { if ($this->_shouldLog) { $this->_logger->error(sprintf('Could not write service container to <code>%s</code>.', $storagePath)); } return $containerBuilder->getDelegateContainerBuilder(); } /** @noinspection PhpUndefinedClassInspection */ return new TubePressServiceContainer(); } private function _getDumpedSymfonyContainerAsString(\Symfony\Component\DependencyInjection\ContainerBuilder $containerBuilder) { if ($this->_shouldLog) { $this->_logDebug('Preparing to dump container builder to string'); } $dumpConfig = array( 'class' => 'TubePressServiceContainer' ); if (!isset($this->_containerDumper)) { $this->_containerDumper = new \Symfony\Component\DependencyInjection\Dumper\PhpDumper($containerBuilder); } $dumped = $this->_containerDumper->dump($dumpConfig); if ($this->_shouldLog) { $this->_logDebug(sprintf('Done dumping container builder to string. Check the HTML source to view the full' . ' container. <div style="display:none"><pre>%s</pre></div>', $dumped)); } return $dumped; } private function _getClassMapFromAddons(array $addons) { if ($this->_shouldLog) { $this->_logDebug(sprintf('Examining classloading data for <code>%d</code> add-ons', count($addons))); } $toReturn = array(); /** * @var $addon tubepress_api_contrib_AddonInterface */ foreach ($addons as $addon) { $map = $addon->getClassMap(); if ($this->_shouldLog) { $this->_logDebug(sprintf('Add-on <code>%s</code> has a classmap of size <code>%d</code>', $addon->getName(), count($map))); } $toReturn = array_merge($toReturn, $map); } if ($this->_shouldLog) { $this->_logDebug(sprintf('Done gathering classmaps for <code>%d</code> add-ons.', count($addons))); } return $toReturn; } /** * This is here strictly for testing! :/ * * @param tubepress_internal_ioc_ContainerBuilder $containerBuilder */ public function __setContainerBuilder(tubepress_internal_ioc_ContainerBuilder $containerBuilder) { $this->_containerBuilder = $containerBuilder; } public function __setContainerDumper(\Symfony\Component\DependencyInjection\Dumper\DumperInterface $dumper) { $this->_containerDumper = $dumper; } public function __setSerializer(array $callback) { $this->_serializer = $callback; } private function _logDebug($msg) { $this->_logger->debug(sprintf('(Uncached Container Supplier) %s', $msg)); } }
tubepress/tubepress
src/php/classes/internal/tubepress/internal/boot/helper/uncached/UncachedContainerSupplier.php
PHP
mpl-2.0
11,179
package tsp; public class Ciudad { private String nombre; private int id; private CiudadesDistancias[] distanciasC = new CiudadesDistancias[22]; private boolean visitado = false; private boolean inicial = false; Ciudad(int idd, String nom){ nombre = nom; id = idd; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getId() { return id; } public void setId(int id) { this.id = id; } public CiudadesDistancias distanciasACiudades(int i) { return distanciasC[i]; } public CiudadesDistancias[] getDistancias() { return distanciasC; } public void setDistancias(CiudadesDistancias[] distancias) { this.distanciasC = distancias; } public boolean getVisitado() { return visitado; } public void setVisitado(){ this.visitado = true; } public void setInicial(){ this.inicial = true; } public boolean getInicial() { return inicial; } public int getDistancia(String cd){ int distancia = 0; for (int i=0;i<22;i++){ if(distanciasC[i].getCiudadDestino().equals(cd)){ distancia=distanciasC[i].getDistancia(); } } return distancia; } }
arian-22/AlgoritmosGeneticos-UTN
Ejercicio-03/src/tsp/Ciudad.java
Java
mpl-2.0
1,265
/******************************************************************************* * Copyright (c) 2007, 2018 Stefaan Van Cauwenberge * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0 (the "License"). If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Initial Developer of the Original Code is * Stefaan Van Cauwenberge. Portions created by * the Initial Developer are Copyright (C) 2007, 2018 by * Stefaan Van Cauwenberge. All Rights Reserved. * * Contributor(s): none so far. * Stefaan Van Cauwenberge: Initial API and implementation *******************************************************************************/ package info.vancauwenberge.filedriver.filereader.csv; import java.io.File; import java.io.FileInputStream; import java.io.Reader; import java.util.Map; import com.novell.nds.dirxml.driver.Trace; import com.novell.nds.dirxml.driver.xds.Constraint; import com.novell.nds.dirxml.driver.xds.DataType; import com.novell.nds.dirxml.driver.xds.Parameter; import com.novell.nds.dirxml.driver.xds.XDSParameterException; import info.vancauwenberge.filedriver.api.AbstractStrategy; import info.vancauwenberge.filedriver.api.IFileReadStrategy; import info.vancauwenberge.filedriver.exception.ReadException; import info.vancauwenberge.filedriver.filepublisher.IPublisher; import info.vancauwenberge.filedriver.filereader.RecordQueue; import info.vancauwenberge.filedriver.shim.driver.GenericFileDriverShim; import info.vancauwenberge.filedriver.util.TraceLevel; import info.vancauwenberge.filedriver.util.Util; public class CSVFileReader extends AbstractStrategy implements IFileReadStrategy { private boolean useHeaderNames; private char seperator; private String encoding; private boolean hasHeader; private boolean skipEmptyLines; private Thread parsingThread; private RecordQueue queue; private String[] schema; private Trace trace; private CSVFileParser handler; protected enum Parameters implements IStrategyParameters { //@formatter:off SKIP_EMPTY_LINES("csvReader_skipEmptyLines","true",DataType.BOOLEAN), USE_HEADER_NAMES("csvReader_UseHeaderNames","true",DataType.BOOLEAN), HAS_HEADER ("csvReader_hasHeader" ,"true",DataType.BOOLEAN), FORCED_ENCODING ("csvReader_forcedEncoding",null ,DataType.STRING), SEPERATOR ("csvReader_seperator" ,"," ,DataType.STRING); //@formatter:on private Parameters(final String name, final String defaultValue, final DataType dataType) { this.name = name; this.defaultValue = defaultValue; this.dataType = dataType; } private final String name; private final String defaultValue; private final DataType dataType; @Override public String getParameterName() { return name; } @Override public String getDefaultValue() { return defaultValue; } @Override public DataType getDataType() { return dataType; } @Override public Constraint[] getConstraints() { return null; } } /* * (non-Javadoc) * * @see * info.vancauwenberge.filedriver.api.IFileReader#init(com.novell.nds.dirxml * .driver.Trace, java.util.Map) */ @Override public void init(final Trace trace, final Map<String, Parameter> driverParams, final IPublisher publisher) throws XDSParameterException { if (trace.getTraceLevel() > TraceLevel.TRACE) { trace.trace("CSVFileReader.init() driverParams:" + driverParams); } this.trace = trace; useHeaderNames = getBoolValueFor(Parameters.USE_HEADER_NAMES, driverParams); // driverParams.get(TAG_USE_HEADER_NAMES).toBoolean().booleanValue(); encoding = getStringValueFor(Parameters.FORCED_ENCODING, driverParams); // driverParams.get(TAG_FORCED_ENCODING).toString(); hasHeader = getBoolValueFor(Parameters.HAS_HEADER, driverParams); // driverParams.get(TAG_HAS_HEADER).toBoolean().booleanValue(); skipEmptyLines = getBoolValueFor(Parameters.SKIP_EMPTY_LINES, driverParams); // driverParams.get(TAG_SKIP_EMPTY_LINES).toBoolean().booleanValue(); if ("".equals(encoding)) { encoding = Util.getSystemDefaultEncoding(); trace.trace("No encoding given. Using system default of " + encoding, TraceLevel.ERROR_WARN); } // Tabs and spaces in the driver config are removed by Designer, so we // need to use a special 'encoding' for the tab character. final String strSeperator = getStringValueFor(Parameters.SEPERATOR, driverParams); // driverParams.get(TAG_SEPERATOR).toString(); if ("{tab}".equalsIgnoreCase(strSeperator)) { seperator = '\t'; } else if ("{space}".equalsIgnoreCase(strSeperator)) { seperator = ' '; } else if ((strSeperator != null) && !"".equals(strSeperator)) { seperator = strSeperator.charAt(0);// This is a required field, so // we should have at least one // character } else { throw new XDSParameterException("Invalid parameter value for seperator:" + strSeperator); } schema = GenericFileDriverShim.getSchemaAsArray(driverParams); } /* * (non-Javadoc) * * @see * info.vancauwenberge.filedriver.api.IFileReader#openFile(com.novell.nds. * dirxml.driver.Trace, java.io.File) */ @Override public void openFile(final File f) throws ReadException { try { // Start the parser that will parse this document final FileInputStream fr = new FileInputStream(f); final Reader reader = new UnicodeReader(fr, encoding); handler = new CSVFileParser(seperator, schema, skipEmptyLines, hasHeader, useHeaderNames); handler.resetParser(); queue = handler.getQueue(); parsingThread = new Thread() { @Override public void run() { try { handler.doParse(reader); } catch (final Exception e) { Util.printStackTrace(trace, e); queue.setFinishedInError(e); } } }; parsingThread.setDaemon(true); parsingThread.setName("CSVParser"); parsingThread.start(); } catch (final Exception e1) { trace.trace("Exception while handeling CSV document:" + e1.getMessage(), TraceLevel.ERROR_WARN); throw new ReadException("Exception while handeling CSV document:" + e1.getMessage(), e1); } } /* * (non-Javadoc) * * @see * info.vancauwenberge.filedriver.api.IFileReader#readRecord(com.novell.nds. * dirxml.driver.Trace) */ @Override public Map<String, String> readRecord() throws ReadException { try { return queue.getNextRecord(); } catch (final Exception e) { throw new ReadException(e); } } /* * (non-Javadoc) * * @see info.vancauwenberge.filedriver.api.IFileReader#close() */ @Override public void close() throws ReadException { queue = null; if (parsingThread.isAlive()) { trace.trace("WARN: parsing thread is still alive...", TraceLevel.ERROR_WARN); try { parsingThread.join(); } catch (final InterruptedException e) { e.printStackTrace(); } } // Thread is dead. Normal situation. parsingThread = null; handler = null; } @SuppressWarnings("unchecked") @Override public <E extends Enum<?> & IStrategyParameters> Class<E> getParametersEnum() { return (Class<E>) Parameters.class; } @Override public String[] getActualSchema() { // The parsing is done in a seperate thread. We need to make sure that // at least one record is read. return handler.getCurrentSchema(); } }
scauwe/Generic-File-Driver-for-IDM
shim/src/main/java/info/vancauwenberge/filedriver/filereader/csv/CSVFileReader.java
Java
mpl-2.0
7,573
namespace Reader_UI { partial class TereziDummy { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(130)))), ((int)(((byte)(130))))); this.label1.Location = new System.Drawing.Point(12, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(486, 40); this.label1.TabIndex = 0; this.label1.Text = "1F YOU DON\'T KNOW TH3 P4SSWORD Y3T, 1T M34NS YOU\'R3 NOT SUPPOS3D TO, DUMMY! GO B4" + "CK!!!"; // // button1 // this.button1.Font = new System.Drawing.Font("Verdana", 10.5F); this.button1.Location = new System.Drawing.Point(417, 35); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(81, 25); this.button1.TabIndex = 1; this.button1.Text = "OK"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // TereziDummy // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(510, 72); this.ControlBox = false; this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "TereziDummy"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "P4SSWORD H1NT"; this.TopMost = true; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; } }
cybnetsurfe3011/MSPA-Reader
Reader UI/TereziDummy.Designer.cs
C#
mpl-2.0
3,226
package aws import ( "fmt" "log" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" "github.com/hashicorp/aws-sdk-go-base/tfawserr" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/rds/finder" ) func resourceAwsDbProxyTarget() *schema.Resource { return &schema.Resource{ Create: resourceAwsDbProxyTargetCreate, Read: resourceAwsDbProxyTargetRead, Delete: resourceAwsDbProxyTargetDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ "db_proxy_name": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validateRdsIdentifier, }, "target_group_name": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validateRdsIdentifier, }, "db_instance_identifier": { Type: schema.TypeString, Optional: true, ForceNew: true, ExactlyOneOf: []string{ "db_instance_identifier", "db_cluster_identifier", }, ValidateFunc: validateRdsIdentifier, }, "db_cluster_identifier": { Type: schema.TypeString, Optional: true, ForceNew: true, ExactlyOneOf: []string{ "db_instance_identifier", "db_cluster_identifier", }, ValidateFunc: validateRdsIdentifier, }, "endpoint": { Type: schema.TypeString, Computed: true, }, "port": { Type: schema.TypeInt, Computed: true, }, "rds_resource_id": { Type: schema.TypeString, Computed: true, }, "target_arn": { Type: schema.TypeString, Computed: true, }, "tracked_cluster_id": { Type: schema.TypeString, Computed: true, }, "type": { Type: schema.TypeString, Computed: true, }, }, } } func resourceAwsDbProxyTargetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).rdsconn dbProxyName := d.Get("db_proxy_name").(string) targetGroupName := d.Get("target_group_name").(string) params := rds.RegisterDBProxyTargetsInput{ DBProxyName: aws.String(dbProxyName), TargetGroupName: aws.String(targetGroupName), } if v, ok := d.GetOk("db_instance_identifier"); ok { params.DBInstanceIdentifiers = []*string{aws.String(v.(string))} } if v, ok := d.GetOk("db_cluster_identifier"); ok { params.DBClusterIdentifiers = []*string{aws.String(v.(string))} } resp, err := conn.RegisterDBProxyTargets(&params) if err != nil { return fmt.Errorf("error registering RDS DB Proxy (%s/%s) Target: %w", dbProxyName, targetGroupName, err) } dbProxyTarget := resp.DBProxyTargets[0] d.SetId(strings.Join([]string{dbProxyName, targetGroupName, aws.StringValue(dbProxyTarget.Type), aws.StringValue(dbProxyTarget.RdsResourceId)}, "/")) return resourceAwsDbProxyTargetRead(d, meta) } func resourceAwsDbProxyTargetParseID(id string) (string, string, string, string, error) { idParts := strings.SplitN(id, "/", 4) if len(idParts) != 4 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" || idParts[3] == "" { return "", "", "", "", fmt.Errorf("unexpected format of ID (%s), expected db_proxy_name/target_group_name/type/id", id) } return idParts[0], idParts[1], idParts[2], idParts[3], nil } func resourceAwsDbProxyTargetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).rdsconn dbProxyName, targetGroupName, targetType, rdsResourceId, err := resourceAwsDbProxyTargetParseID(d.Id()) if err != nil { return err } dbProxyTarget, err := finder.DBProxyTarget(conn, dbProxyName, targetGroupName, targetType, rdsResourceId) if tfawserr.ErrCodeEquals(err, rds.ErrCodeDBProxyNotFoundFault) { log.Printf("[WARN] RDS DB Proxy Target (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if tfawserr.ErrCodeEquals(err, rds.ErrCodeDBProxyTargetGroupNotFoundFault) { log.Printf("[WARN] RDS DB Proxy Target (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { return fmt.Errorf("error reading RDS DB Proxy Target (%s): %w", d.Id(), err) } if dbProxyTarget == nil { log.Printf("[WARN] RDS DB Proxy Target (%s) not found, removing from state", d.Id()) d.SetId("") return nil } d.Set("db_proxy_name", dbProxyName) d.Set("endpoint", dbProxyTarget.Endpoint) d.Set("port", dbProxyTarget.Port) d.Set("rds_resource_id", dbProxyTarget.RdsResourceId) d.Set("target_arn", dbProxyTarget.TargetArn) d.Set("target_group_name", targetGroupName) d.Set("tracked_cluster_id", dbProxyTarget.TrackedClusterId) d.Set("type", dbProxyTarget.Type) if aws.StringValue(dbProxyTarget.Type) == rds.TargetTypeRdsInstance { d.Set("db_instance_identifier", dbProxyTarget.RdsResourceId) } else { d.Set("db_cluster_identifier", dbProxyTarget.RdsResourceId) } return nil } func resourceAwsDbProxyTargetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).rdsconn params := rds.DeregisterDBProxyTargetsInput{ DBProxyName: aws.String(d.Get("db_proxy_name").(string)), TargetGroupName: aws.String(d.Get("target_group_name").(string)), } if v, ok := d.GetOk("db_instance_identifier"); ok { params.DBInstanceIdentifiers = []*string{aws.String(v.(string))} } if v, ok := d.GetOk("db_cluster_identifier"); ok { params.DBClusterIdentifiers = []*string{aws.String(v.(string))} } log.Printf("[DEBUG] Deregister DB Proxy target: %#v", params) _, err := conn.DeregisterDBProxyTargets(&params) if tfawserr.ErrCodeEquals(err, rds.ErrCodeDBProxyNotFoundFault) { return nil } if tfawserr.ErrCodeEquals(err, rds.ErrCodeDBProxyTargetGroupNotFoundFault) { return nil } if tfawserr.ErrCodeEquals(err, rds.ErrCodeDBProxyTargetNotFoundFault) { return nil } if err != nil { return fmt.Errorf("Error deregistering DB Proxy target: %s", err) } return nil }
terraform-providers/terraform-provider-aws
aws/resource_aws_db_proxy_target.go
GO
mpl-2.0
5,998
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris // +build darwin dragonfly freebsd linux netbsd openbsd solaris package executor import ( "fmt" "os" "syscall" ) // configure new process group for child process func (e *UniversalExecutor) setNewProcessGroup() error { if e.childCmd.SysProcAttr == nil { e.childCmd.SysProcAttr = &syscall.SysProcAttr{} } e.childCmd.SysProcAttr.Setpgid = true return nil } // Cleanup any still hanging user processes func (e *UniversalExecutor) cleanupChildProcesses(proc *os.Process) error { // If new process group was created upon command execution // we can kill the whole process group now to cleanup any leftovers. if e.childCmd.SysProcAttr != nil && e.childCmd.SysProcAttr.Setpgid { if err := syscall.Kill(-proc.Pid, syscall.SIGKILL); err != nil && err.Error() != noSuchProcessErr { return err } return nil } return proc.Kill() } // Only send the process a shutdown signal (default INT), doesn't // necessarily kill it. func (e *UniversalExecutor) shutdownProcess(sig os.Signal, proc *os.Process) error { if sig == nil { sig = os.Interrupt } if err := proc.Signal(sig); err != nil && err.Error() != finishedErr { return fmt.Errorf("executor shutdown error: %v", err) } return nil }
hashicorp/nomad
drivers/shared/executor/executor_unix.go
GO
mpl-2.0
1,293
<?php namespace Devlabs\SportifyBundle\Form; use FOS\UserBundle\Util\LegacyFormHelper; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ResettingFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('plainPassword', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\RepeatedType'), array( 'type' => LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\PasswordType'), 'options' => array('translation_domain' => 'FOSUserBundle'), 'first_options' => array('label' => 'form.new_password'), 'second_options' => array('label' => 'form.new_password_confirmation'), 'invalid_message' => 'fos_user.password.mismatch', 'error_bubbling' => true )); } public function getParent() { return 'FOS\UserBundle\Form\Type\ResettingFormType'; // Or for Symfony < 2.8 // return 'fos_user_registration'; } public function getBlockPrefix() { return 'app_user_registration'; } // For Symfony 2.x public function getName() { return $this->getBlockPrefix(); } }
dev-labs-bg/sportify
src/Devlabs/SportifyBundle/Form/ResettingFormType.php
PHP
agpl-3.0
1,394
# -*- coding: utf-8 -*- # Copyright: Damien Elmes <anki@ichi2.net> # Copyright © 2014 Roland Sieker <ospalh@gmail.com> # # License: GNU AGPL, version 3 or later; # http://www.gnu.org/licenses/agpl.html import os import re import shutil import zipfile from . import Collection from .hooks import runHook from .lang import _ from .utils import ids2str, json, splitFields class Exporter(object): def __init__(self, col, did=None): self.col = col self.did = did def exportInto(self, path): self._escapeCount = 0 file = open(path, "wb") self.doExport(file) file.close() def escapeText(self, text): "Escape newlines, tabs, CSS and quotechar." text = text.replace("\n", "<br>") text = text.replace("\t", " " * 8) text = re.sub("(?i)<style>.*?</style>", "", text) if "\"" in text: text = "\"" + text.replace("\"", "\"\"") + "\"" return text def cardIds(self): if not self.did: cids = self.col.db.list("select id from cards") else: cids = self.col.decks.cids(self.did, children=True) self.count = len(cids) return cids # Cards as TSV ###################################################################### class TextCardExporter(Exporter): key = _("Cards in Plain Text") ext = ".txt" hideTags = True def __init__(self, col): Exporter.__init__(self, col) def doExport(self, file): ids = sorted(self.cardIds()) # strids = ids2str(ids) def esc(s): # strip off the repeated question in answer if exists s = re.sub("(?si)^.*<hr id=answer>\n*", "", s) return self.escapeText(s) out = "" for cid in ids: c = self.col.getCard(cid) out += esc(c.q()) out += "\t" + esc(c.a()) + "\n" file.write(out.encode("utf-8")) # Notes as TSV ###################################################################### class TextNoteExporter(Exporter): key = _("Notes in Plain Text") ext = ".txt" def __init__(self, col): Exporter.__init__(self, col) self.includeID = False self.includeTags = True def doExport(self, file): cardIds = self.cardIds() data = [] for id, flds, tags in self.col.db.execute(""" select guid, flds, tags from notes where id in (select nid from cards where cards.id in %s)""" % ids2str(cardIds)): row = [] # note id if self.includeID: row.append(str(id)) # fields row.extend([self.escapeText(f) for f in splitFields(flds)]) # tags if self.includeTags: row.append(tags.strip()) data.append("\t".join(row)) self.count = len(data) out = "\n".join(data) file.write(out.encode("utf-8")) # Anki decks ###################################################################### # media files are stored in self.mediaFiles, but not exported. class AnkiExporter(Exporter): key = _("Anki 2.0 Deck") ext = ".anki2" def __init__(self, col): Exporter.__init__(self, col) self.includeSched = False self.includeMedia = True def exportInto(self, path): # create a new collection at the target try: os.unlink(path) except (IOError, OSError): pass self.dst = Collection(path) self.src = self.col # find cards if not self.did: cids = self.src.db.list("select id from cards") else: cids = self.src.decks.cids(self.did, children=True) # copy cards, noting used nids nids = {} data = [] for row in self.src.db.execute( "select * from cards where id in " + ids2str(cids)): nids[row[1]] = True data.append(row) self.dst.db.executemany( "insert into cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", data) # notes strnids = ids2str(list(nids.keys())) notedata = [] for row in self.src.db.all( "select * from notes where id in "+strnids): # remove system tags if not exporting scheduling info if not self.includeSched: row = list(row) row[5] = self.removeSystemTags(row[5]) notedata.append(row) self.dst.db.executemany( "insert into notes values (?,?,?,?,?,?,?,?,?,?,?)", notedata) # models used by the notes mids = self.dst.db.list( "select distinct mid from notes where id in " + strnids) # card history and revlog if self.includeSched: data = self.src.db.all( "select * from revlog where cid in " + ids2str(cids)) self.dst.db.executemany( "insert into revlog values (?,?,?,?,?,?,?,?,?)", data) else: # need to reset card state self.dst.sched.resetCards(cids) # models - start with zero self.dst.models.models = {} for m in self.src.models.all(): if int(m['id']) in mids: self.dst.models.update(m) # decks if not self.did: dids = [] else: dids = [self.did] + [ x[1] for x in self.src.decks.children(self.did)] dconfs = {} for d in self.src.decks.all(): if str(d['id']) == "1": continue if dids and d['id'] not in dids: continue if not d['dyn'] and d['conf'] != 1: if self.includeSched: dconfs[d['conf']] = True if not self.includeSched: # scheduling not included, so reset deck settings to default d = dict(d) d['conf'] = 1 self.dst.decks.update(d) # copy used deck confs for dc in self.src.decks.allConf(): if dc['id'] in dconfs: self.dst.decks.updateConf(dc) # find used media media = {} self.mediaDir = self.src.media.dir() if self.includeMedia: for row in notedata: flds = row[6] mid = row[2] for file in self.src.media.filesInStr(mid, flds): media[file] = True if self.mediaDir: for fname in os.listdir(self.mediaDir): if fname.startswith("_"): media[fname] = True self.mediaFiles = list(media.keys()) self.dst.crt = self.src.crt # todo: tags? self.count = self.dst.cardCount() self.dst.setMod() self.postExport() self.dst.close() def postExport(self): # overwrite to apply customizations to the deck before it's closed, # such as update the deck description pass def removeSystemTags(self, tags): return self.src.tags.remFromStr("marked leech", tags) # Packaged Anki decks ###################################################################### class AnkiPackageExporter(AnkiExporter): key = _("Anki Deck Package") ext = ".apkg" def __init__(self, col): AnkiExporter.__init__(self, col) def exportInto(self, path): # open a zip file z = zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) # if all decks and scheduling included, full export if self.includeSched and not self.did: media = self.exportVerbatim(z) else: # otherwise, filter media = self.exportFiltered(z, path) # media map z.writestr("media", json.dumps(media)) z.close() def exportFiltered(self, z, path): # export into the anki2 file colfile = path.replace(".apkg", ".anki2") AnkiExporter.exportInto(self, colfile) z.write(colfile, "collection.anki2") # and media self.prepareMedia() media = {} for c, file in enumerate(self.mediaFiles): c = str(c) mpath = os.path.join(self.mediaDir, file) if os.path.exists(mpath): z.write(mpath, c) media[c] = file # tidy up intermediate files os.unlink(colfile) p = path.replace(".apkg", ".media.db2") if os.path.exists(p): os.unlink(p) os.chdir(self.mediaDir) shutil.rmtree(path.replace(".apkg", ".media")) return media def exportVerbatim(self, z): # close our deck & write it into the zip file, and reopen self.count = self.col.cardCount() self.col.close() z.write(self.col.path, "collection.anki2") self.col.reopen() # copy all media if not self.includeMedia: return {} media = {} mdir = self.col.media.dir() for c, file in enumerate(os.listdir(mdir)): c = str(c) mpath = os.path.join(mdir, file) if os.path.exists(mpath): z.write(mpath, c) media[c] = file return media def prepareMedia(self): # chance to move each file in self.mediaFiles into place before media # is zipped up pass # Export modules ########################################################################## def exporters(): def id(obj): return ("%s (*%s)" % (obj.key, obj.ext), obj) exps = [ id(AnkiPackageExporter), id(TextNoteExporter), id(TextCardExporter), ] runHook("exportersList", exps) return exps
ospalh/libanki3
libanki3/exporting.py
Python
agpl-3.0
9,791
import './FilteredListSection.css'; import * as React from 'react'; import * as c from 'classnames'; interface Props { className?: string; title?: string; } export class FilteredListSection extends React.Component<Props, {}> { public render() { const { children, title, } = this.props; return ( <div className={this.getClassNames()}> {title && <div className={`pur-FilteredListSection__title`}>{title}</div>} <div className={`pur-FilteredListSection__content`}> {children} </div> </div> ); } private getClassNames() { const { className } = this.props; return c('pur-FilteredListSection', { // 'pur-FilteredListSeperator--modifier-class': boolean, }, className); } }
part-up/part-up
app/packages/partup-client-react/react/src/components/FilteredList/FilteredListSection.tsx
TypeScript
agpl-3.0
881
<?php // The source code packaged with this file is Free Software, Copyright (C) 2005 by // Ricardo Galli <gallir at uib dot es>. // It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise. // You can get copies of the licenses here: // http://www.affero.org/oagpl.html // AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING". class Mafia { protected $valid; protected $error; protected $published; protected $ids = []; protected $links = []; protected $users = []; public function __construct($uri, $published, $ids) { if (!$this->validate($uri)) { return $this; } $this->published = $published; $this->links = $this->loadRelatedLinks($this->link); if (empty($ids)) { return; } array_map(function ($value) use ($ids) { $value->selected = in_array($value->link_id, $ids); }, $this->links); } public function isValid() { return $this->valid; } public function getError() { return $this->error; } public function getLinks() { return $this->links; } public function getUsers() { if ($this->valid !== true) { return []; } if ($this->users) { return $this->users; } $ids = array_filter(array_map(function ($value) { return $value->selected ? $value->link_id : null; }, $this->links)); return $this->getUsersByLinks($ids); } protected function validate($uri) { global $globals; if (empty($uri)) { return $this->setError('No se ha indicado una URL'); } if (strstr($uri, '/')) { if (!preg_match('#/story/([^/]+)#', $uri, $uri)) { return $this->setError('La URL indicada no es correcta'); } $uri = $uri[1]; } $this->link = $this->getLinkByUri($uri); if (empty($this->link)) { return $this->setError('Envío no encontrado'); } return $this->valid = true; } protected function getLinkByUri($uri) { global $db; return $db->get_row(' SELECT *, false AS `selected` FROM `links` WHERE `link_uri` = "'.$db->escape($uri).'" LIMIT 1; '); } protected function loadRelatedLinks($link) { global $db; $domain = $this->getDomain($link->link_url); return array_merge( [$link], $db->get_results(' SELECT *, false AS `selected` FROM `links` WHERE ( `link_id` < "'.(int)$link->link_id.'" AND `link_url` LIKE "%'.$domain.'/%" '.($this->published ? 'AND link_status = "published"' : '').' ) ORDER BY `link_id` DESC LIMIT 5; '), $db->get_results(' SELECT *, false AS `selected` FROM `links` WHERE ( `link_id` > "'.(int)$link->link_id.'" AND `link_url` LIKE "%'.$domain.'/%" '.($this->published ? 'AND link_status = "published"' : '').' ) ORDER BY `link_id` ASC LIMIT 5; ') ); } protected function setError($error) { $this->error = $error; return $this->valid = false; } protected function getDomain($uri) { return implode('.', array_slice(explode('.', parse_url($uri, PHP_URL_HOST)), -2)); } protected function getUsersByLinks(array $link_ids) { global $db, $globals; $users = $db->get_results(' SELECT `users`.`user_id`, `users`.`user_login` FROM `users`, `votes` WHERE ( `votes`.`vote_type` = "links" AND `votes`.`vote_link_id` IN ("'.implode('","', $link_ids).'") AND `users`.`user_id` = `votes`.`vote_user_id` AND `votes`.`vote_value` > 0 ) GROUP BY `users`.`user_id` HAVING COUNT(`users`.`user_id`) = "'.count($link_ids).'"; '); foreach ($users as $user) { $user->user_link = $globals['base_url_general'].'user/'.htmlspecialchars($user->user_login).'/'.$user->user_id; } usort($users, function ($a, $b) { return ($a->user_login > $b->user_login) ? 1 : -1; }); return $users; } }
gallir/Meneame
www/libs/mafia.php
PHP
agpl-3.0
4,683
# -*- coding: utf-8 -*- # See README.rst file on addon root folder for license details from . import res_partner
incaser/odoo-templates
sample_addon_oca/models/__init__.py
Python
agpl-3.0
114
/* * Copyright (c) 2012 - 2020 Splice Machine, Inc. * * This file is part of Splice Machine. * Splice Machine is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either * version 3, or (at your option) any later version. * Splice Machine 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Splice Machine. * If not, see <http://www.gnu.org/licenses/>. */ package com.splicemachine.derby.impl.sql.execute; import com.splicemachine.db.catalog.UUID; import com.splicemachine.db.iapi.sql.execute.ConstantAction; /** * @author Scott Fines * Date: 1/13/16 */ public class MemGenericConstantActionFactory extends SpliceGenericConstantActionFactory{ @Override public ConstantAction getDropIndexConstantAction(String fullIndexName, String indexName, String tableName, String schemaName, UUID tableId, long tableConglomerateId, UUID dbId){ return new MemDropIndexConstantOperation(fullIndexName, indexName, tableName, schemaName, tableId, tableConglomerateId, dbId); } }
splicemachine/spliceengine
mem_sql/src/main/java/com/splicemachine/derby/impl/sql/execute/MemGenericConstantActionFactory.java
Java
agpl-3.0
1,384
#!/usr/bin/env node process.chdir(__dirname) var crypto = require('crypto'), fs = require('fs'), config = require('../config.js') var newPasswordSha1 = crypto.createHash('sha1').update('').digest('hex') var content = '// auto-generated\n' + 'exports.port = ' + config.port + '\n' + 'exports.host = ' + JSON.stringify(config.host) + '\n' + 'exports.keySha1 = ' + JSON.stringify(newPasswordSha1) + '\n' fs.writeFileSync('../config.js', content) console.log('New key is an empty string')
aimnadze/audio-player-server
scripts/disable-key.js
JavaScript
agpl-3.0
515
<?php /** * @copyright Copyright (c) 2018 Joas Schilling <coding@schilljs.com> * * @author Joas Schilling <coding@schilljs.com> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\Core\Migrations; use OCP\DB\ISchemaWrapper; use OCP\Migration\SimpleMigrationStep; use OCP\Migration\IOutput; /** * Delete the admin|personal sections and settings tables */ class Version14000Date20180129121024 extends SimpleMigrationStep { /** * @param IOutput $output * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper` * @param array $options * @return null|ISchemaWrapper * @since 13.0.0 */ public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); $schema->dropTable('admin_sections'); $schema->dropTable('admin_settings'); $schema->dropTable('personal_sections'); $schema->dropTable('personal_settings'); return $schema; } }
michaelletzgus/nextcloud-server
core/Migrations/Version14000Date20180129121024.php
PHP
agpl-3.0
1,660
MetaclicUtils.Templates = {}; MetaclicUtils.Templates.datasets = [ ' {{#ifCond sort "!=" false}}', ' <div class="result-sort"><label>Trier par</label>', ' <select name="sort" class="form-control">', ' {{#each sortTypes}}', ' {{#ifCond id "==" ../sort}}', ' <option value="{{id}}" selected>{{name}}</option>', ' {{else}}', ' <option value="{{id}}">{{name}}</option>', ' {{/ifCond}}', ' {{/each}}', ' </select>', ' <a href="#" class="sortdirection">', ' {{#ifCond sortDesc "==" true}}', ' <i class="fa fa-sort-alpha-desc"></i>', ' {{else}}', ' <i class="fa fa-sort-alpha-asc"></i>', ' {{/ifCond}}', ' </a>', '</div>', '{{/ifCond}}', '<div class="result-count">{{ total }} résultat(s)</div>', '<div class="metaclic-row">', '{{#ifCond facets "!=" undefined}}', '<div class="Metaclic-results">', '{{else}}', '<div class="Metaclic-results Metaclic-results-full">', '{{/ifCond}}', ' <ul class="search-results">', ' {{#each data}}', ' <li class="search-result dataset-result" data-dataset="{{id}}">', ' <a href="{{ page }}" title="{{ organization.name }}" data-dataset="{{id}}">', '', ' <div class="result-logo">', ' <img alt="" src="{{organization.logo}}" >', ' </div>', ' {{#if organization.public_service }}', ' <img alt="certified"', ' class="certified" rel="popover"', ' data-title="{{_ \'certified_public_service\'}}"', ' data-content="{{_ \'the_identity_of_this_public_service_public_is_certified_by_etalab\'}}"', ' data-container="body" data-trigger="hover"/>', ' {{/if}}', ' <div class="result-body">', ' <h4 class="result-title">{{title}}</h4>', '', ' <div class="result-description">', ' {{mdshort description 128}}</div></div>', '', ' </a><ul class="result-infos">', '', ' {{#if temporal_coverage }}', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'temporal_coverage\'}}">', ' <span class="fa fa-calendar fa-fw"></span>', ' {{dt temporal_coverage.start format=\'L\' }} {{_ \'to\'}} {{dt temporal_coverage.end format=\'L\' }}', ' </span>', ' </li>', ' {{/if}}', '', ' {{#if frequency }}', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Update frequency\' }}">', ' <span class="fa fa-clock-o fa-fw"></span>', ' {{_ frequency }}', ' </span>', ' </li>', ' {{/if}}', '', ' {{#if spatial.territories }}', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Spatial coverage\'}}">', ' <span class="fa fa-map-marker fa-fw"></span>', ' {{_ spatial.territories.0.name }}', ' </span>', ' </li>', ' {{/if}}', '', ' {{#if spatial.granularity }}', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Spatial granularity\'}}">', ' <span class="fa fa-bullseye fa-fw"></span>', ' {{_ spatial.granularity }}', ' </span>', ' </li>', ' {{/if}}', '', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Reuses\'}}">', ' <span class="fa fa-retweet fa-fw"></span>', ' {{default metrics.reuses 0 }}', ' </span>', ' </li>', '', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Followers\'}}">', ' <span class="fa fa-star fa-fw"></span>', ' {{default metrics.followers 0 }}', ' </span>', ' </li>', '', ' </ul>', ' </li>', ' {{/each}}', ' </ul>', '</div>', '{{#ifCond facets "!=" undefined}}', '<div class="Metaclic-facets">', '{{#ifCond facets.organization "!=" undefined}}', '{{#if facets.organization}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-tags fa-fw"></i> Organisme</div>', ' <ul data-limitlist=5>', ' {{#each facets.organization}}', ' <a href="#" data-addID="{{this.[0]._id.$oid}}">', ' <span>{{this.[1]}}</span>', ' {{this.[0].name}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', '{{#ifCond facets.tag "!=" undefined}}', '{{#if facets.tag}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-tags fa-fw"></i> Tags</div>', ' <ul data-limitlist=5>', ' {{#each facets.tag}}', ' <a href="#" data-addTag="{{this.[0]}}">', ' <span>{{this.[1]}}</span>', ' {{this.[0]}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', '{{#ifCond facets.license "!=" undefined}}', '{{#if facets.license}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-copyright fa-fw"></i> Licences</div>', ' <ul data-limitlist=5>', ' {{#each facets.license}}', ' <a href="#" data-addLicense="{{this.[0]._id}}">', ' <span>{{this.[1]}}</span>', ' {{this.[0].title}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', //couverture temporelle '{{#ifCond facets.geozone "!=" undefined}}', '{{#if facets.geozone}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-map-marker fa-fw"></i> Couverture spatiale</div>', ' <ul data-limitlist=5>', ' {{#each facets.geozone}}', ' <a class="geozone-to-load" href="#" data-addGeozone="{{this.[0]._id}}">', ' <span>{{this.[1]}}</span>', ' {{this.[0]._id}} ({{this.[0].code}})', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', '{{#ifCond facets.granularity "!=" undefined}}', '{{#if facets.granularity}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-bullseye fa-fw"></i> Granularité territoriale</div>', ' <ul data-limitlist=5>', ' {{#each facets.granularity}}', ' <a href="#" data-addGranularity="{{this.[0]}}">', ' <span>{{this.[1]}}</span>', ' {{_ this.[0]}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', '{{#ifCond facets.format "!=" undefined}}', '{{#if facets.format}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-file fa-fw"></i> Formats</div>', ' <ul data-limitlist=5>', ' {{#each facets.format}}', ' <a href="#" data-addFormat="{{this.[0]}}">', ' <span>{{this.[1]}}</span>', ' {{_ this.[0]}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', // reuse '</div>', '{{/ifCond}}', '</div>', ' <div class="metaclic-pagination">', ' {{{ paginate page total page_size }}}', ' </div>', ]; MetaclicUtils.Templates.dataset = [ '<div class="dataset" data-dataset="{{id}}">', '', ' <div class=\'dataset-info\'>', ' <blockquote>{{md description }}</blockquote>', ' {{#if extras.remote_url}}', ' <a class="site_link" href="{{extras.remote_url}}" target=_blank>', ' Voir le site original', ' </a>', ' {{/if}}', ' <p class="published_on">', ' {{_ \'published_on\' }} {{dt created_at}}', ' {{_ \'and_modified_on\'}} {{dt last_modified}}', ' {{_ \'by\'}} <a title="{{organization.name}}" href="{{organization.page}}">{{organization.name}}</a>', ' </p>', ' </div>', '', ' <div class="resources-list">', ' <h3>{{_ \'Resources\'}}</h3>', ' {{#each resources}}', ' <div data-checkurl="/api/1/datasets/checkurl/" itemtype="http://schema.org/DataDownload" itemscope="itemscope" id="resource-{{id}}">', '', ' <a href="{{url}}" data-size="{{filesize}}" data-format="{{uppercase format}}" data-map_title="{{../title}}" data-title="{{title}}" data-id="{{id}}" itemprop="url" target=_blank>', ' <h4>', ' <span data-format="{{uppercase format}}">', ' {{uppercase format}}', ' </span>', ' {{title}}', ' <p>', ' Dernière modification le {{dt last_modified}}', ' </p>', ' </h4>', ' </a>', '', ' </div>', ' {{/each}}', ' </div>', '', ' <div class="meta">', '', ' <div class="producer">', ' <h3>{{_ \'Producer\'}}</h3>', ' <a title="{{organization.name}}" href="{{organization.page}}">', ' <img class="organization-logo producer" alt="{{organization.name}}" src="{{fulllogo organization.logo}}"><br>', ' <span class="name">', ' {{organization.name}}', ' </span>', ' </a>', ' </div>', '', '', ' <div class="info">', ' <h3>{{_ \'Informations\'}}</h3>', ' <ul>', ' <li title="{{_ \'License\'}}" rel="tooltip">', ' <i class="fa fa-copyright"></i>', ' <!--a href="http://opendatacommons.org/licenses/odbl/summary/"-->', ' {{_ license}}', ' <!--/a-->', ' </li>', ' <li title="{{_ \'Frequency\'}}" rel="tooltip">', ' <span class="fa fa-clock-o"></span>', ' {{_ frequency}}', ' </li>', ' <li title="{{_ \'Spatial granularity\'}}" rel="tooltip">', ' <span class="fa fa-bullseye"></span>', ' {{_ spatial.granularity}}', ' </li>', ' </ul>', ' <ul class="spatial_zones">', ' {{#each spatial.zones}}', ' <li data-zone="{{.}}">{{.}}</li>', ' {{/each}}', ' </ul>', ' <ul class="tags">', ' {{#each tags}}', ' <li><a title="{{.}}" href="https://www.data.gouv.fr/fr/search/?tag={{.}}">', ' {{.}}', ' </a>', ' </li>', ' {{/each}}', ' </ul>', ' <div class="Metaclic-clear">', ' </div>', ' </div>', ' </div>', '', '', ' </div>' ]; MetaclicUtils.Templates.organizationAdd = [ '{{#if generator}}', '<div class="organization_add">', '<h1>Générateur de code metaClic</h1></br>', '<i>Ajoutez des organismes en saisissant leur nom et en les sélectionnant dans la liste</i></br>', ' <input type="text" name="research" list="metaclic-autocomplete-list" class="form-control" placeholder="Organisation">', ' <datalist id="metaclic-autocomplete-list">', ' </datalist>', '</div>', ' <ul class="tags">', ' {{#if orgs}}', ' {{#each orgs}}', ' {{#if name}}', ' <li><a title="Fermer" href="#" class="facet-remove facet-organization" data-removeorganizationtoorigin="organization" data-id="{{id}}"> {{name}} ×</a></li>', ' {{/if}}', ' {{/each}}', ' {{/if}}', ' </ul>', ' <div class="Metaclic-clear"></div>', '{{/if}}', ]; MetaclicUtils.Templates.datasetsForm = [ '<div class="datasetsForm">', ' <form action="" method="get">', ' <input type="hidden" name="option" value="com_metaclic"></input>', ' <input type="hidden" name="view" value="metaclic"></input>', ' <div><label>&nbsp;</label><input type="text" name="q" value="{{q}}" placeholder="Rechercher des données" class="form-control"></input></div>', ' {{#ifCount orgs ">" 1 }}', ' <div>', ' {{else}}', ' <div class="hidden">', ' {{/ifCount}}', ' </div>', ' </form>', ' <div class="selected_facets">', '<ul class="tags">', ' {{#if organization}}', ' {{#if organization_name}}', ' {{#ifNotall organization "|"}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-organization" data-removeOrganization="organization"> {{organization_name}} &times;</a></li>', ' {{/ifNotall}}', ' {{/if}}', ' {{/if}}', ' {{#if tags}}', ' {{#each tags}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-tag" data-removeTag="{{.}}"><i class="fa fa-tags fa-fw"></i> {{.}} &times;</a></li>', ' {{/each}}', ' {{/if}}', ' {{#if license}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-license" data-removeParam="license"><i class="fa fa-copyright fa-fw"></i> {{license}} &times;</a></li>', ' {{/if}}', ' {{#if geozone}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-geozone" data-removeParam="geozone"><i class="fa fa-map-marker fa-fw"></i> {{geozone}} &times;</a></li>', ' {{/if}}', ' {{#if granularity}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-granularity" data-removeParam="granularity"><i class="fa fa-bullseye fa-fw"></i> {{granularity}} &times;</a></li>', ' {{/if}}', ' {{#if format}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-format" data-removeParam="format"><i class="fa fa-file fa-fw"></i> {{format}} &times;</a></li>', ' {{/if}}', ' </div>', ' </ul>', '</div>', ' <br>' ]; MetaclicUtils.Templates.lastdatasets = [ '<div class="Metaclic-lastdatasets">', ' {{#each data}}', ' <div class="card dataset-card">', ' <a class="card-logo" href="{{ organization.uri }}" target="datagouv">', ' <img alt="{{ organization.name }}" src="{{ organization.logo }}" width="70" height="70">', ' </a>', ' <div class="card-body">', ' <h4>', ' <a href="{{ url }}" title="{{title}}">', ' {{title}}', ' </a>', ' </h4>', ' </div>', ' <footer>', ' <ul>', ' <li>', ' <a rel="tooltip" data-placement="top" data-container="body" title="" data-original-title="Réutilisations">', ' <span class="fa fa-retweet fa-fw"></span>', ' {{default metrics.reuses 0 }}', ' </a>', ' </li>', ' <li>', ' <a rel="tooltip" data-placement="top" data-container="body" title="" data-original-title="Favoris">', ' <span class="fa fa-star fa-fw"></span>', ' {{default metrics.followers 0 }}', ' </a>', ' </li>', ' </ul>', ' </footer>', ' <a href="{{ url }}" title="{{title}}">', ' {{trimString description}}', ' </a>', ' <footer>', ' <ul>', ' {{#if temporal_coverage }}', ' <li>', ' <a rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Temporal coverage\' }}">', ' <span class="fa fa-calendar fa-fw"></span>', ' {{dt temporal_coverage.start format=\'L\' }} {{_ \'to\'}} {{dt temporal_coverage.end format=\'L\' }}', ' </a>', ' </li>', ' {{/if}}', '', ' {{#if spatial.granularity }}', ' <li>', ' <a rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Territorial coverage granularity\' }}">', ' <span class="fa fa-bullseye fa-fw"></span>', ' {{_ spatial.granularity }}', ' </a>', ' </li>', ' {{/if}}', '', ' {{#if frequency }}', ' <li>', ' <a rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Frequency\' }}">', ' <span class="fa fa-clock-o fa-fw"></span>', ' {{_ frequency }}', ' </a>', ' </li>', ' {{/if}}', ' </ul>', ' </footer>', ' </div>', ' {{/each}}', ' </div>' ]; MetaclicUtils.Templates.shareCode = [ '{{#if generator}}', '{{#if organizationList}}', '<div class="Metaclic-shareCode">', '<div>', ' Code à intégrer dans votre site Internet :', ' <pre>', '&lt;script&gt;window.jQuery || document.write("&lt;script src=\'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js\'&gt;&lt;\\\/script&gt;")&lt;/script&gt;', '', '&lt;!-- chargement feuille de style font-awesome --&gt;', '&lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"&gt;', '', '&lt;script src="https://unpkg.com/metaclic/dist/metaclic.js"&gt;&lt;/script&gt;', '&lt;div class="Metaclic-data"', ' data-q="{{q}}"', ' data-organizations="{{organizationList}}"', ' data-background_layers="{{background_layers}}"', ' data-facets="all"', ' data-page_size="{{page_size}}"', '&gt&lt;/div&gt', ' </pre>', " <p>Plus de paramétrage disponible dans la documentation: <a href='https://github.com/datakode/metaclic/wiki/Personnalisation' target='_blank'>https://github.com/datakode/metaclic/wiki/Personnalisation</a></p>", " <p><h1>Prévisualisation : </h1></p>", '</div>', '</div>', '{{/if}}', '{{/if}}', ]; MetaclicUtils.Templates.shareLinkMap = [ '<div class="MetaclicMap-shareLink">', '<div class="linkDiv"><a href="#">intégrez cette carte à votre site&nbsp;<i class="fa fa-share-alt"></i></a></div>', '<div class="hidden">', ' <h4>Vous pouvez intégrer cet carte sur votre site</h4>', ' <p>Pour ceci collez le code suivant dans le code HTML de votre page</p>', ' <pre>', '&lt;script&gt;window.jQuery || document.write("&lt;script src=\'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js\'&gt;&lt;\\\/script&gt;")&lt;/script&gt;', '', '&lt;script src="{{baseUrl}}metaclic.js"&gt;&lt;/script&gt;', '&lt;div class="Metaclic-map"', " data-resources='{{jsonencode resources}}'", //" data-leaflet_map_options='{{jsonencode leaflet_map_options}}'", " data-title='{{title}}'", '&gt&lt;/div&gt', ' </pre>', " <p>vous pouvez trouver plus d'info sur cet outil et son paramétrage à cette adresse: <a href='https://github.com/datakode/metaclic' target='_blank'>https://github.com/datakode/metaclic</a></p>", '</div>', '</div>', ]; MetaclicUtils.Templates.li_resource = [ '<li data-id="{{id}}">', '<a href="{{metadata_url}}">{{title}}</a>', '<i class="fa fa-copyright"></i> {{_ license}}', '<p class="organization" data-id="{{organization.id}}" data-slug="{{organization.slug}}">', '<img alt="{{ organization.name }}" src="{{ organization.logo }}">', '<span>{{organization.name}}</span>', '</p>', '</li>' ];
datakode/metaclic
js/templates.js
JavaScript
agpl-3.0
22,464
package storage /* An implementation of a 2-dimentional R*-Tree used for storing <lat,long> coordinates of boats. See references [0] and [9] for description of the datastructure (haven't followed the instructions 100%) Notes: - MBR - Minimum Bounding Rectangle - The FindWithin() & FindAll() function returns the coordinates (& the mmsi number?) for the boat. More info about the boats are found when clicking the leafletjs markers/ querying the API - The height of a node will never change, but its level will increase as the root is split - All leaf nodes must be on the same level - Internal nodes contains entries of the form <childNode, mbr> - Leaf nodes contains entries of the form <mbr, mmsi> - Wiki: best performance has been experienced with a minimum fill of 30%–40% of the maximum number of entries - Boats are stored as zero-area rectangles instead of points, because it works better with the R*tree */ import ( "errors" "log" "sort" "github.com/tormol/AIS/geo" ) const RTree_M = 5 //max entries per node. const RTree_m = 2 //min entries per node. 40% of M is best // RTree is a two-dimensional R*-tree implementation with float64 positions and uint32 values type RTree struct { root *node numOfBoats int } // NumOfBoats return the total number of boats stored in the structure. func (rt *RTree) NumOfBoats() int { return rt.numOfBoats } // Match is used to store a match found when searching the tree. type Match struct { MMSI uint32 Lat float64 Long float64 } type node struct { parent *node //Points to parent node entries []entry //Array of all the node's entries (should have a default length of M+1) height int //Height of the node ( = number of edges between node and a leafnode) } // isLeaf returns true of the node is a leafnode. func (n *node) isLeaf() bool { return n.height == 0 } // Needed for node to be sortable [11]: type byLat []entry // for sorting by Latitude type byLong []entry // for sorting by Longitude func (e byLat) Len() int { return len(e) } func (e byLat) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e byLat) Less(i, j int) bool { //first sorted by min, then if tie, by max if e[i].mbr.Min().Lat < e[j].mbr.Min().Lat { return true } else if e[i].mbr.Min().Lat == e[j].mbr.Min().Lat { return e[i].mbr.Max().Lat < e[j].mbr.Max().Lat } return false } func (e byLong) Len() int { return len(e) } func (e byLong) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e byLong) Less(i, j int) bool { //first sorted by min, then if tie by max if e[i].mbr.Min().Long < e[j].mbr.Min().Long { return true } else if e[i].mbr.Min().Long == e[j].mbr.Min().Long { return e[i].mbr.Max().Long < e[j].mbr.Max().Long } return false } /* As described in [9]: - A non-leaf node contains entries of the form (child_pointer, rectangle) - A leaf node contains entries of the form (Object_ID, rectangle) */ type entry struct { mbr *geo.Rectangle //Points to the MBR containing all the children of this entry child *node //Points to the node (only used in internal nodes) mmsi uint32 //The mmsi number of the boat (only used in leafnode-entries) dist float64 //The distance from center of mbr to center of parents mbr (used for the reInsert algorithm) } /* Needed for sorting a list of entries by the distance from their center to the center of the "parent node" mbr. (used by reInsert algorithm) */ type byDist []entry func (e byDist) Len() int { return len(e) } func (e byDist) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e byDist) Less(i, j int) bool { return e[i].dist < e[j].dist } // NewRTree returns a pointer to a new R-Tree object. func NewRTree() *RTree { //TODO could take M (and m) as input? return &RTree{ root: &node{ parent: nil, entries: make([]entry, 0, RTree_M+1), height: 0, }, } } // InsertData inserts a new boat into the tree structure. func (rt *RTree) InsertData(lat, long float64, mmsi uint32) error { r, err := geo.NewRectangle(lat, long, lat, long) if err != nil { return err } newEntry := entry{ //Dont have to set all the parameters... the rest will be set to its null-value mbr: r, mmsi: mmsi, } //[ID1] Insert starting with the leaf height as parameter rt.insert(0, newEntry, true) rt.numOfBoats++ return nil } // insert inserts an entry into a node at a given height. func (rt *RTree) insert(height int, newEntry entry, first bool) { //first is needed in case of overflowTreatment, it should normaly be true //[I1] ChooseSubtree with height as a parameter to find the node N n := rt.chooseSubtree(newEntry.mbr, height) //If an internal entry is re-inserted, the node's parent pointer must be updated if height >= 1 { newEntry.child.parent = n } //[I2] Append newEntry to n if room, else call OverflowTreatment [for reinsertion or split] n.entries = append(n.entries, newEntry) if len(n.entries) >= RTree_M+1 { // n is full -> call overflowTreatment didSplit, nn := rt.overflowTreatment(n, first) //OT finds the appropriate height from n.height if didSplit { //[I3] if OverflowTreatment was called and a split was performed: propagate OT upwards if nn.height == rt.root.height { // if root was split: create a new root newRoot := node{ parent: nil, entries: make([]entry, 0, RTree_M+1), height: rt.root.height + 1, } nEntry := entry{mbr: n.recalculateMBR(), child: n} nnEntry := entry{mbr: nn.recalculateMBR(), child: nn} newRoot.entries = append(newRoot.entries, nEntry) newRoot.entries = append(newRoot.entries, nnEntry) n.parent = &newRoot nn.parent = &newRoot rt.root = &newRoot //fmt.Printf("Root was split...^ new height is %d\n", newRoot.height) return //The root has no MBR, so there is no need to adjust any MBRs } // n was split into n & nn -> insert nn into the tree at the same height rt.insert(nn.height+1, entry{mbr: nn.recalculateMBR(), child: nn}, true) } } //[I4] Adjust all MBR in the insertion path for n.height < rt.root.height { pIdx, err := n.parentEntriesIdx() CheckErr(err, "insert had some trouble adjusting the MBR...") n.parent.entries[pIdx].mbr = n.recalculateMBR() n = n.parent } return } // overflowTreatment handles the overflowing node n. // It will first try a reinsert, then do a split. func (rt *RTree) overflowTreatment(n *node, first bool) (bool, *node) { //returns if n wasSplit, and nn (false -> reInserted ) //[OT1] if height is not root && this is first call of OT in given height during insertion: reInsert. else: split if first && n.height < rt.root.height { rt.reInsert(n) return false, nil } else { // The entry has been inserted before -> split the node nn, err := n.split() CheckErr(err, "overflowTreatment failed to split a node") return true, nn } } // reInsert is uses to re-insert some of the entries of the node. // It is used when the node is full. func (rt *RTree) reInsert(n *node) { //[RI1] for all M+1 entries: compute distance between their center and the center of the mbr of n // Finding the center of the MBR of n i, err := n.parentEntriesIdx() CheckErr(err, "reInsert had some trouble locating the entry in the parent node") centerOfMBR := n.parent.entries[i].mbr.Center() // Computing the distance for all entries in n for _, ent := range n.entries { ent.dist = ent.mbr.Center().DistanceTo(centerOfMBR) } //[RI2] sort the entries by distance in decreasing order sort.Sort(sort.Reverse(byDist(n.entries))) //[RI3] remove the first p entries from n, and adjust mbr of n f := (RTree_M * 0.3) //30% of M performs best according to [9] p := int(f) tmp := make([]entry, p) copy(tmp, n.entries[:p]) n.entries = n.entries[p:] //TODO now the cap of n.entries is only 8... newMBR := n.recalculateMBR() n.parent.entries[i].mbr = newMBR //[RI4] starting with min distance: invoke insert to reinsert the entries for k := len(tmp) - 1; k >= 0; k-- { rt.insert(n.height, tmp[k], false) // "first" is set to false because the entry has previously been inserted } } // chooseSubtree chooses the leaf node (or the best node of a given height) in which to place a new entry. func (rt *RTree) chooseSubtree(r *geo.Rectangle, height int) *node { n := rt.root //CS1 for !n.isLeaf() && n.height > height { //CS2 n.height gets lower for every iteration bestChild := n.entries[0] pointsToLeaves := false if n.height == 1 { pointsToLeaves = true } var bestDifference float64 //must be reset for each node n if pointsToLeaves { bestDifference = bestChild.overlapChangeWith(r) } else { bestDifference = bestChild.mbr.AreaDifference(bestChild.mbr.MBRWith(r)) } for i := 1; i < len(n.entries); i++ { e := n.entries[i] if pointsToLeaves { //childpointer points to leaves -> [Determine the minimum overlap cost] overlapDifference := e.overlapChangeWith(r) if overlapDifference <= bestDifference { if overlapDifference < bestDifference { //strictly smaller bestDifference = overlapDifference bestChild = e //CS3 set new bestChild, repeat from CS2 } else { //tie -> choose the entry whose rectangle needs least area enlargement eNew := e.mbr.MBRWith(r).AreaDifference(e.mbr) eOld := bestChild.mbr.MBRWith(r).AreaDifference(bestChild.mbr) if eNew < eOld { bestDifference = overlapDifference bestChild = e //CS3 set new bestChild, repeat from CS2 } else if e.mbr.Area() < bestChild.mbr.Area() { //if tie again: -> choose the entry with the smallest MBR bestDifference = overlapDifference bestChild = e //CS3 set new bestChild, repeat from CS2 } //else the bestChild is kept } } } else { //childpointer do not point to leaves -> choose the child-node whose rectangle needs least enlargement to include r newMBR := e.mbr.MBRWith(r) areaDifference := e.mbr.AreaDifference(newMBR) if areaDifference <= bestDifference { //we have a new best (or a tie) if areaDifference < bestDifference { bestDifference = areaDifference //CS3 set new bestChild, repeat from CS2 bestChild = e } else if e.mbr.Area() < bestChild.mbr.Area() { // change in MBR is a tie -> keep the rectangle with the smallest area bestDifference = areaDifference //CS3 set new bestChild, repeat from CS2 bestChild = e } } } } n = bestChild.child } return n } // overlapChangeWith calculates how much overlap enlargement it takes to include the given rectangle. func (e *entry) overlapChangeWith(r *geo.Rectangle) float64 { return e.mbr.OverlapWith(r) } // split() will split a node in order to add a new entry to a full node (using the R*Tree algorithm)[9]. func (n *node) split() (*node, error) { // the goal is to partition the set of M+1 entries into two groups // sorts the entries by the best axis, and finds the best index to split into two distributions if len(n.entries) != RTree_M+1 { return nil, errors.New("Cannot split: node n does not contain M+1 entries") } k := n.chooseSplitAxis() group1 := make([]entry, 0, RTree_M+1) group2 := make([]entry, 0, RTree_M+1) nn := &node{ parent: n.parent, entries: []entry{}, height: n.height, } for i, e := range n.entries { if i < RTree_m-1+k { group1 = append(group1, e) } else { group2 = append(group2, e) if e.child != nil { //update the parent pointer if splitting an internal node e.child.parent = nn } } } //group1 n.entries = group1 //group2 nn.entries = group2 return nn, nil } // chooseSplitAxis() chooses the axis perpendicular to which the split is performed. func (n *node) chooseSplitAxis() int { //TODO Make the code prettier //[CSA 1] //Entries sorted by Latitude S_lat := 0.000000 //used to determine the best axis to split on bestK_lat := 0 //used to determine the best distribution minOverlap_lat := -1.000000 best_area_lat := -1.000000 sortByLat := make([]entry, len(n.entries)) // len(sortByLat) == len(n.entries) is needed for copy to work copy(sortByLat, n.entries) sort.Sort(byLat(sortByLat)) //Entries sorted by Longitude S_long := 0.000000 //used to determine the best axis to split on bestK_long := 0 //used to determine the best distribution minOverlap_long := -1.000000 best_area_long := -1.000000 sort.Sort(byLong(n.entries)) //For each axis: M - 2m + 2 distributions of the M+1 entries into two groups are determined d := (RTree_M - (2 * RTree_m) + 2) for k := 1; k <= d; k++ { //By Latitude LatGroup1 := make([]entry, (RTree_m - 1 + k)) LatGroup2 := make([]entry, (RTree_M - len(LatGroup1) + 1)) copy(LatGroup1, sortByLat[:RTree_m-1+k]) copy(LatGroup2, sortByLat[RTree_m-1+k:]) latGoodness := marginOf(LatGroup1) + marginOf(LatGroup2) S_lat += latGoodness // test if this distribution has the best overlap value for latitude mbr1 := mbrOf(LatGroup1...) mbr2 := mbrOf(LatGroup2...) if o := mbr1.OverlapWith(mbr2); o <= minOverlap_lat || minOverlap_lat == -1 { if o < minOverlap_lat || minOverlap_lat == -1 { bestK_lat = k //we have a new best minOverlap_lat = o best_area_lat = mbr1.Area() + mbr2.Area() } else { //tie -> keep the distribution with the least area a_now := mbr1.Area() + mbr2.Area() if a_now < best_area_lat { bestK_lat = k //we have a new best minOverlap_lat = o best_area_lat = mbr1.Area() + mbr2.Area() } } } //else don't change the value //By Longitude LongGroup1 := make([]entry, (RTree_m - 1 + k)) LongGroup2 := make([]entry, (RTree_M - len(LongGroup1) + 1)) copy(LongGroup1, n.entries[:RTree_m-1+k]) copy(LongGroup2, n.entries[RTree_m-1+k:]) longGoodness := marginOf(LongGroup1) + marginOf(LongGroup2) S_long += longGoodness // test if this distribution has the best overlap value for longitude mbr1 = mbrOf(LongGroup1...) mbr2 = mbrOf(LongGroup2...) if o := mbr1.OverlapWith(mbr2); o <= minOverlap_long || minOverlap_long == -1 { if o < minOverlap_long || minOverlap_long == -1 { bestK_long = k //we have a new best minOverlap_long = o best_area_long = mbr1.Area() + mbr2.Area() } else { //tie -> keep the distribution with the least area a_now := mbr1.Area() + mbr2.Area() if a_now < best_area_long { bestK_long = k //we have a new best minOverlap_long = o best_area_long = mbr1.Area() + mbr2.Area() } } } //else don't change the value } //CSA2: Choose the axis with the minimum S as split axis if S_lat < S_long { n.entries = sortByLat return bestK_lat } return bestK_long } // recalculateMBR returns the MBR that contains all the children of n. func (n *node) recalculateMBR() *geo.Rectangle { return mbrOf(n.entries...) } // marginOf returns the margin of the MBR containing the entries. func marginOf(entries []entry) float64 { return mbrOf(entries...).Margin() } // mbrOf returns the MBR of some entry-objects. func mbrOf(entries ...entry) *geo.Rectangle { nMinLat := entries[0].mbr.Min().Lat nMinLong := entries[0].mbr.Min().Long nMaxLat := entries[0].mbr.Max().Lat nMaxLong := entries[0].mbr.Max().Long for _, e := range entries { if e.mbr.Min().Lat < nMinLat { nMinLat = e.mbr.Min().Lat } if e.mbr.Min().Long < nMinLong { nMinLong = e.mbr.Min().Long } if e.mbr.Max().Lat > nMaxLat { nMaxLat = e.mbr.Max().Lat } if e.mbr.Max().Long > nMaxLong { nMaxLong = e.mbr.Max().Long } } r, err := geo.NewRectangle(nMinLat, nMinLong, nMaxLat, nMaxLong) CheckErr(err, "mbrOf had some trouble creating a new MBR of the provided entries") return r } // FindWithin returns all the boats that overlaps a given rectangle of the map [0]. func (rt *RTree) FindWithin(r *geo.Rectangle) *[]Match { n := rt.root matches := []entry{} if !n.isLeaf() { matches = append(matches, n.searchChildren(r, matches)...) } else { //only need to search the root node for _, e := range n.entries { if geo.Overlaps(e.mbr, r) { matches = append(matches, e) } } } return rt.toMatches(matches) } // searchChildren is the recursive method for finding the nodes whose mbr overlaps the searchBox [0]. func (n *node) searchChildren(searchBox *geo.Rectangle, matches []entry) []entry { //TODO Test performance by searching children concurrently? if !n.isLeaf() { //Internal node: for _, e := range n.entries { if geo.Overlaps(e.mbr, searchBox) { matches = e.child.searchChildren(searchBox, matches) //recursively search the child node } } } else { //Leaf node: for _, e := range n.entries { if geo.Overlaps(e.mbr, searchBox) { matches = append(matches, e) } } } return matches } // Update is used to update the location of a boat that is already stored in the structure. // It deletes the old entry, and inserts a new entry. func (rt *RTree) Update(mmsi uint32, oldLat, oldLong, newLat, newLong float64) error { // Old coordinates oldR, err := geo.NewRectangle(oldLat, oldLong, oldLat, oldLong) if err != nil { return errors.New("Illegal coordinates, please use <latitude, longitude> coodinates") } // Deletes the old coordinates err = rt.delete(mmsi, oldR) if err != nil { return err } // Inserts the new coordinates rt.InsertData(newLat, newLong, mmsi) return nil } // delete removes the Point(zero-area Rectangle) from the RTree [0]. func (rt *RTree) delete(mmsi uint32, r *geo.Rectangle) error { //D1 [Find node containing record] (and also the index of the entry) l, idx := rt.root.findLeaf(mmsi, r) if l != nil && idx >= 0 { //D2 [Delete record] l.entries = append(l.entries[:idx], l.entries[idx+1:]...) //D3 [Propagate changes] rt.condenseTree(l) } else { return errors.New("Failed to delete, could not find the leaf node containing the boat") } rt.numOfBoats-- return nil } // findLeaf finds the leaf node containing the given rectangle r [0]. func (n *node) findLeaf(mmsi uint32, r *geo.Rectangle) (*node, int) { if !n.isLeaf() { //FL1 for _, e := range n.entries { if geo.Overlaps(e.mbr, r) { l, idx := e.child.findLeaf(mmsi, r) // Searches childnode if l != nil { return l, idx // The childnode was the correct leafnode } } } } else { //FL2 [Search leaf node for record] for idx, ent := range n.entries { if geo.Overlaps(ent.mbr, r) && mmsi == ent.mmsi { //locating the exact entry return n, idx } } } return nil, -1 // no match found } // condenseTree is used when an entry has been deleted from n [0]. // It traverses the tree from the node and up to the root and makes the necessary changes to the nodes. func (rt *RTree) condenseTree(n *node) { //CT1 [initialize] q := []entry{} // Contains orphaned entries for rt.root != n { //CT2 [find parent entry] p := n.parent idx, err := n.parentEntriesIdx() CheckErr(err, "Trouble condensing the tree") en := p.entries[idx] // the entry containing n //CT3 [eliminate under-full node] if len(n.entries) < RTree_m { p.entries = append(p.entries[:idx], p.entries[idx+1:]...) //[8] remove n from its parent q = append(q, en.child.entries...) } else { //CT4 [Adjust MBR] (if n has not been eliminated) en.mbr = n.recalculateMBR() } n = p // CT5 [Move up one height in tree] } //CT6 [Re-insert orphaned entries] for _, e := range q { if e.child != nil { //inserting an internal rt.insert(e.child.height+1, e, true) //TODO false or true? _, err := e.child.parent.parentEntriesIdx() CheckErr(err, "Cannot find parent of re-inserted orphaned internal entry") } else { //inserting a leaf entry rt.insert(0, e, true) //TODO false or true? } } //D4 [Shorten tree] (if root has only 1 child, promote that child to root) if len(rt.root.entries) == 1 && !rt.root.isLeaf() { rt.root = rt.root.entries[0].child rt.root.parent = nil //fmt.Printf("Promoted a child to root, new height is %d\n", rt.root.height) } } // parentEntriesIdx returns the index of the node in its parent's list of entries. func (n *node) parentEntriesIdx() (int, error) { p := n.parent if p != nil { for idx, e := range p.entries { if e.child == n { return idx, nil } } } return -1, errors.New("This node is not found in parent's entries") } // toMatches returns a slice of Match-objects that can be used to create GeoJSON output func (rt *RTree) toMatches(matches []entry) *[]Match { s := []Match{} for _, m := range matches { s = append(s, Match{m.mmsi, m.mbr.Max().Lat, m.mbr.Max().Long}) } return &s } // CheckErr is a function for checking an error. // Takes the error and a message as input and does log.Fatalf() if error. func CheckErr(err error, message string) { if err != nil { log.Fatalf("ERROR: %s \n %s", message, err) } } /* TODOs: - 180 meridianen... (~International date line) References: [0] http://www.cs.jhu.edu/%7Emisha/ReadingSeminar/Papers/Guttman84.pdf [1] https://en.wikipedia.org/wiki/Tree_%28data_structure%29 https://en.wikipedia.org/wiki/R-tree https://www.youtube.com/watch?v=39GuS7c4uZI https://blog.golang.org/go-slices-usage-and-internals https://blog.golang.org/go-maps-in-action [7] http://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go http://herman.asia/efficient-string-concatenation-in-go [8] http://stackoverflow.com/questions/25025409/delete-element-in-a-slice [9] http://dbs.mathematik.uni-marburg.de/publications/myPapers/1990/BKSS90.pdf (R* Trees) [10] https://en.wikipedia.org/wiki/R*_tree [11] https://golang.org/pkg/sort/ [12] http://www.eng.auburn.edu/~weishinn/Comp7970/Presentation/rstartree.pdf https://golang.org/ref/spec#Passing_arguments_to_..._parameters [13] http://geojsonlint.com/ [14] http://stackoverflow.com/questions/7933460/how-do-you-write-multiline-strings-in-go#7933487 */
tormol/AIS
storage/rStarTree.go
GO
agpl-3.0
21,959
/* * TeleStax, Open Source Cloud Communications Copyright 2012. * and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.ss7.management.console; /** * @author sergey.povarnin */ public interface ShellServerMBean { String getAddress(); void setAddress(String address); int getPort(); void setPort(int port); String getSecurityDomain(); void setSecurityDomain(String securityDomain); int getQueueNumber(); }
RestComm/jss7
management/shell-server-impl/src/main/java/org/restcomm/ss7/management/console/ShellServerMBean.java
Java
agpl-3.0
1,338
# -*- coding: utf-8 -*- # Copyright© 2016 ICTSTUDIO <http://www.ictstudio.eu> # Copyright 2016 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': "MIS Builder Cost Center Filter", 'version': '8.0.1.0.0', 'category': 'Reporting', 'summary': """ Add Cost Center filters to MIS Reports """, 'author': 'ICTSTUDIO,' 'ACSONE SA/NV,' 'Odoo Community Association (OCA)', 'website': "http://www.ictstudio.eu", 'license': 'AGPL-3', 'depends': [ 'mis_builder', 'account_cost_center' ], 'data': [ 'views/mis_report_view.xml', 'views/mis_builder_cost_center.xml', ], 'qweb': [ 'static/src/xml/mis_widget.xml' ], }
ICTSTUDIO/accounting-addons
mis_builder_cost_center_filter/__openerp__.py
Python
agpl-3.0
793
import { VariableSupportType } from '@grafana/data'; import { getVariableQueryEditor, StandardVariableQueryEditor } from './getVariableQueryEditor'; import { LegacyVariableQueryEditor } from './LegacyVariableQueryEditor'; describe('getVariableQueryEditor', () => { describe('happy cases', () => { describe('when called with a data source with custom variable support', () => { it('then it should return correct editor', async () => { const editor: any = StandardVariableQueryEditor; const datasource: any = { variables: { getType: () => VariableSupportType.Custom, query: () => undefined, editor }, }; const result = await getVariableQueryEditor(datasource); expect(result).toBe(editor); }); }); describe('when called with a data source with standard variable support', () => { it('then it should return correct editor', async () => { const editor: any = StandardVariableQueryEditor; const datasource: any = { variables: { getType: () => VariableSupportType.Standard, toDataQuery: () => undefined }, }; const result = await getVariableQueryEditor(datasource); expect(result).toBe(editor); }); }); describe('when called with a data source with datasource variable support', () => { it('then it should return correct editor', async () => { const editor: any = StandardVariableQueryEditor; const plugin = { components: { QueryEditor: editor } }; const importDataSourcePluginFunc = jest.fn().mockResolvedValue(plugin); const datasource: any = { variables: { getType: () => VariableSupportType.Datasource }, meta: {} }; const result = await getVariableQueryEditor(datasource, importDataSourcePluginFunc); expect(result).toBe(editor); expect(importDataSourcePluginFunc).toHaveBeenCalledTimes(1); expect(importDataSourcePluginFunc).toHaveBeenCalledWith({}); }); }); describe('when called with a data source with legacy variable support', () => { it('then it should return correct editor', async () => { const editor: any = StandardVariableQueryEditor; const plugin = { components: { VariableQueryEditor: editor } }; const importDataSourcePluginFunc = jest.fn().mockResolvedValue(plugin); const datasource: any = { metricFindQuery: () => undefined, meta: {} }; const result = await getVariableQueryEditor(datasource, importDataSourcePluginFunc); expect(result).toBe(editor); expect(importDataSourcePluginFunc).toHaveBeenCalledTimes(1); expect(importDataSourcePluginFunc).toHaveBeenCalledWith({}); }); }); }); describe('negative cases', () => { describe('when variable support is not recognized', () => { it('then it should return null', async () => { const datasource: any = {}; const result = await getVariableQueryEditor(datasource); expect(result).toBeNull(); }); }); describe('when called with a data source with datasource variable support but missing QueryEditor', () => { it('then it should return throw', async () => { const plugin = { components: {} }; const importDataSourcePluginFunc = jest.fn().mockResolvedValue(plugin); const datasource: any = { variables: { getType: () => VariableSupportType.Datasource }, meta: {} }; await expect(getVariableQueryEditor(datasource, importDataSourcePluginFunc)).rejects.toThrow( new Error('Missing QueryEditor in plugin definition.') ); expect(importDataSourcePluginFunc).toHaveBeenCalledTimes(1); expect(importDataSourcePluginFunc).toHaveBeenCalledWith({}); }); }); describe('when called with a data source with legacy variable support but missing VariableQueryEditor', () => { it('then it should return LegacyVariableQueryEditor', async () => { const plugin = { components: {} }; const importDataSourcePluginFunc = jest.fn().mockResolvedValue(plugin); const datasource: any = { metricFindQuery: () => undefined, meta: {} }; const result = await getVariableQueryEditor(datasource, importDataSourcePluginFunc); expect(result).toBe(LegacyVariableQueryEditor); expect(importDataSourcePluginFunc).toHaveBeenCalledTimes(1); expect(importDataSourcePluginFunc).toHaveBeenCalledWith({}); }); }); }); });
grafana/grafana
public/app/features/variables/editor/getVariableQueryEditor.test.tsx
TypeScript
agpl-3.0
4,480
<?php /** * This file is part of the login-cidadao project or it's bundles. * * (c) Guilherme Donato <guilhermednt on github> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace LoginCidadao\OpenIDBundle\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use LoginCidadao\OpenIDBundle\Entity\ClientMetadata; class SectorIdentifierValidator extends ConstraintValidator { public function validate($value, Constraint $constraint) { if (!($value instanceof ClientMetadata)) { $this->context->buildViolation('Invalid class')->addViolation(); return; } $redirectUris = $this->parseUris($value->getRedirectUris()); if ($value->getSectorIdentifierUri() !== null) { $sectorIdentifier = parse_url($value->getSectorIdentifierUri()); } else { $sectorIdentifier = null; } $hosts = array(); foreach ($redirectUris as $uri) { @$hosts[$uri['host']] += 1; } if (!$sectorIdentifier && count($hosts) > 1) { $message = 'sector_identifier_uri is required when multiple hosts are used in redirect_uris. (#rfc.section.8.1)'; $this->context->buildViolation($message) ->atPath('sector_identifier_uri') ->setParameter('value', $message) ->addViolation(); } } /** * @param array $uris * @return string[][] */ private function parseUris(array $uris) { return array_map('parse_url', $uris); } }
PROCERGS/login-cidadao
src/LoginCidadao/OpenIDBundle/Constraints/SectorIdentifierValidator.php
PHP
agpl-3.0
1,699
/* * ISABEL: A group collaboration tool for the Internet * Copyright (C) 2011 Agora System S.A. * * This file is part of Isabel. * * Isabel is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Isabel 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 * Affero GNU General Public License for more details. * * You should have received a copy of the Affero GNU General Public License * along with Isabel. If not, see <http://www.gnu.org/licenses/>. */ package isabel.argonauta; import javax.swing.*; import javax.swing.filechooser.*; import java.awt.*; import java.awt.event.*; /** * File browser. * * Select documents are open with xdg-open */ public class Argonauta { JFileChooser fc; /** * main method. */ public static void main(String[] args) { Argonauta demo = new Argonauta(); } /** * FileChooserDemo Constructor */ public Argonauta() { fc = new JFileChooser(); fc.setDragEnabled(false); // set the current directory: // fc.setCurrentDirectory(swingFile); // Add file filters: javax.swing.filechooser.FileFilter filter; filter = new FileNameExtensionFilter("Images", "jpg", "jpeg", "png", "gif"); fc.addChoosableFileFilter(filter); filter = new FileNameExtensionFilter("PDF", "PDF"); fc.addChoosableFileFilter(filter); filter = new FileNameExtensionFilter("Office", "ppt", "pptx", "doc", "docx"); fc.addChoosableFileFilter(filter); fc.setAcceptAllFileFilterUsed(true); // remove the approve/cancel buttons fc.setControlButtonsAreShown(false); // Actions & Listener: Action openAction = createOpenAction(); Action dismissAction = createDismissAction(); fc.addActionListener(openAction); // make custom controls JPanel buttons = new JPanel(); buttons.add(new JButton(dismissAction)); buttons.add(new JButton(openAction)); // Main Window: JFrame jf = new JFrame("File browser"); jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jf.getContentPane().add(fc, BorderLayout.CENTER); jf.getContentPane().add(buttons, BorderLayout.SOUTH); jf.pack(); jf.setVisible(true); } public Action createOpenAction() { return new AbstractAction("Open") { public void actionPerformed(ActionEvent e) { if (!e.getActionCommand().equals(JFileChooser.CANCEL_SELECTION) && fc.getSelectedFile() != null) { openDocument(fc.getSelectedFile().getPath()); } } }; } public Action createDismissAction() { return new AbstractAction("Dismiss") { public void actionPerformed(ActionEvent e) { System.exit(0); } }; } private void openDocument(String name) { try { Runtime rt = Runtime.getRuntime(); String[] command = { "xdg-open", name }; rt.exec(command); } catch (Exception e) { System.err.println("I can not open this document: " + name); } } }
ging/isabel
components/vnc/navegador/isabel/argonauta/Argonauta.java
Java
agpl-3.0
3,156
/* * Copyright (C) 2013 OpenJST Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openjst.server.mobile.web.rest; import org.openjst.server.commons.mq.IRestCrud; import org.openjst.server.commons.mq.QueryListParams; import org.openjst.server.commons.mq.results.QuerySingleResult; import org.openjst.server.mobile.mq.model.AccountModel; import org.openjst.server.mobile.mq.model.AccountSummaryModel; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * @author Sergey Grachev */ @Path("/accounts") @Produces(MediaType.APPLICATION_JSON) public interface Accounts extends IRestCrud<AccountModel, QueryListParams> { @POST @Path("/generateAccountAPIKey") QuerySingleResult<String> generateAccountAPIKey(@FormParam("accountId") Long accountId); @GET @Path("/{id}/summary") QuerySingleResult<AccountSummaryModel> getSummary(@PathParam("id") Long accountId); }
devmix/openjst
server/mobile/war/src/main/java/org/openjst/server/mobile/web/rest/Accounts.java
Java
agpl-3.0
1,540
/* * DesktopSessionLauncher.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopSessionLauncher.hpp" #include <boost/bind.hpp> #include <core/WaitUtils.hpp> #include <core/system/ParentProcessMonitor.hpp> #include <QProcess> #include <QtNetwork/QTcpSocket> #include "DesktopUtils.hpp" #include "DesktopOptions.hpp" #include "DesktopSlotBinders.hpp" using namespace core; namespace desktop { namespace { void launchProcess(std::string absPath, QStringList argList, QProcess** ppProc) { QProcess* pProcess = new QProcess(); pProcess->setProcessChannelMode(QProcess::SeparateChannels); pProcess->start(QString::fromUtf8(absPath.c_str()), argList); *ppProc = pProcess; } core::WaitResult serverReady(QString host, QString port) { QTcpSocket socket; socket.connectToHost(host, port.toInt()); return WaitResult(socket.waitForConnected() ? WaitSuccess : WaitContinue, Success()); } } // anonymous namespace Error SessionLauncher::launchFirstSession(const QString& filename, ApplicationLaunch* pAppLaunch) { // save reference to app launch pAppLaunch_ = pAppLaunch; // build a new new launch context QString host, port; QStringList argList; QUrl url; buildLaunchContext(&host, &port, &argList, &url); // launch the process Error error = launchSession(argList, &pRSessionProcess_); if (error) return error; // jcheng 03/16/2011: Due to crashing caused by authenticating // proxies, bypass all proxies from Qt until we can get the problem // completely solved. This is only expected to affect CRAN mirror // selection (which falls back to local mirror list) and update // checking. //NetworkProxyFactory* pProxyFactory = new NetworkProxyFactory(); //QNetworkProxyFactory::setApplicationProxyFactory(pProxyFactory); pMainWindow_ = new MainWindow(url); pMainWindow_->setSessionProcess(pRSessionProcess_); pAppLaunch->setActivationWindow(pMainWindow_); desktop::options().restoreMainWindowBounds(pMainWindow_); error = waitForSession(host, port); if (error) return error; // one-time workbench intiailized hook for startup file association if (!filename.isNull() && !filename.isEmpty()) { StringSlotBinder* filenameBinder = new StringSlotBinder(filename); pMainWindow_->connect(pMainWindow_, SIGNAL(firstWorkbenchInitialized()), filenameBinder, SLOT(trigger())); pMainWindow_->connect(filenameBinder, SIGNAL(triggered(QString)), pMainWindow_, SLOT(openFileInRStudio(QString))); } pMainWindow_->connect(pAppLaunch_, SIGNAL(openFileRequest(QString)), pMainWindow_, SLOT(openFileInRStudio(QString))); pMainWindow_->connect(pRSessionProcess_, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(onRSessionExited())); pMainWindow_->show(); pAppLaunch->activateWindow(); pMainWindow_->loadUrl(url); return Success(); } void SessionLauncher::onRSessionExited() { if (pMainWindow_->collectPendingSwitchToProjectRequest()) { // close all satellite windows QWidgetList topLevels = QApplication::topLevelWidgets(); for (int i = 0; i < topLevels.size(); i++) { QWidget* pWindow = topLevels.at(i); if (pWindow != pMainWindow_) pWindow->close(); } // launch next session Error error = launchNextSession(); if (error) { LOG_ERROR(error); showMessageBox(QMessageBox::Critical, pMainWindow_, QString::fromUtf8("RStudio"), launchFailedErrorMessage()); pMainWindow_->quit(); } } else { pMainWindow_->quit(); } } Error SessionLauncher::launchNextSession() { // disconnect the firstWorkbenchInitialized event so it doesn't occur // again when we launch the next session pMainWindow_->disconnect(SIGNAL(firstWorkbenchInitialized())); // delete the old process object pMainWindow_->setSessionProcess(NULL); if (pRSessionProcess_) { delete pRSessionProcess_; pRSessionProcess_ = NULL; } // build a new new launch context QString host, port; QStringList argList; QUrl url; buildLaunchContext(&host, &port, &argList, &url); // launch the process Error error = launchSession(argList, &pRSessionProcess_); if (error) return error; // update the main window's reference to the process object pMainWindow_->setSessionProcess(pRSessionProcess_); // wait for it to be available error = waitForSession(host, port); if (error) return error; // connect to quit event pMainWindow_->connect(pRSessionProcess_, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(onRSessionExited())); // laod url -- use a delay because on occation we've seen the // mac client crash during switching of projects and this could // be some type of timing related issue nextSessionUrl_ = url; QTimer::singleShot(100, this, SLOT(onReloadFrameForNextSession())); return Success(); } void SessionLauncher::onReloadFrameForNextSession() { pMainWindow_->loadUrl(nextSessionUrl_); nextSessionUrl_.clear(); } Error SessionLauncher::launchSession(const QStringList& argList, QProcess** ppRSessionProcess) { return parent_process_monitor::wrapFork( boost::bind(launchProcess, sessionPath_.absolutePath(), argList, ppRSessionProcess)); } Error SessionLauncher::waitForSession(const QString& host, const QString& port) { return waitWithTimeout(boost::bind(serverReady, host, port), 50, 25, 10); } QString SessionLauncher::launchFailedErrorMessage() const { QString errMsg = QString::fromUtf8("The R session failed to start."); if (pRSessionProcess_) { QString errmsgs = QString::fromLocal8Bit( pRSessionProcess_->readAllStandardError()); if (errmsgs.size()) { errMsg = errMsg.append( QString::fromAscii("\n\n")).append(errmsgs); } } return errMsg; } void SessionLauncher::cleanupAtExit() { if (pMainWindow_) desktop::options().saveMainWindowBounds(pMainWindow_); } void SessionLauncher::buildLaunchContext(QString* pHost, QString* pPort, QStringList* pArgList, QUrl* pUrl) const { *pHost = QString::fromAscii("127.0.0.1"); *pPort = desktop::options().newPortNumber(); *pUrl = QUrl(QString::fromAscii("http://") + *pHost + QString::fromAscii(":") + *pPort + QString::fromAscii("/")); if (!confPath_.empty()) { *pArgList << QString::fromAscii("--config-file") << QString::fromUtf8(confPath_.absolutePath().c_str()); } else { // explicitly pass "none" so that rsession doesn't read an // /etc/rstudio/rsession.conf file which may be sitting around // from a previous configuratin or install *pArgList << QString::fromAscii("--config-file") << QString::fromAscii("none"); } *pArgList << QString::fromAscii("--program-mode") << QString::fromAscii("desktop"); *pArgList << QString::fromAscii("--www-port") << *pPort; } } // namespace desktop
Sage-Bionetworks/rstudio
src/cpp/desktop/DesktopSessionLauncher.cpp
C++
agpl-3.0
8,278
# -*- coding: utf-8 -*- __license__ = "GNU Affero General Public License, Ver.3" __author__ = "Pablo Alvarez de Sotomayor Posadillo" # This file is part of Kirinki. # # Kirinki is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Kirinki 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public # License along with kirinki. If not, see <http://www.gnu.org/licenses/>. # Python general imports import os import os.path import subprocess import httplib from datetime import datetime # Django imports from django import forms from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from django.template.loader import render_to_string # Application imports from kirinki.config import Config from kirinki.common import ErrorClear from kirinki.mainviewer import MainViewer from kirinki.models import streaming from kirinki.models import video from kirinki.message import Message from kirinki.user import LoginForm class StreamingController(): '''Class that implements the Streaming controller''' def __init__(self, request): if request.session.get('isConfig', False) is False: Config.getSession(request.session) # Left block leftBlocks = [] if not request.session['user'].is_authenticated(): leftBlocks = [render_to_string('kirinki/section.html', {'title' : 'login', 'content': render_to_string('kirinki/form.html', {'form' : LoginForm(), 'action' : request.session['base_url'] + '/login'}, context_instance=RequestContext(request))})] # Center block centerBlocks = [] try: videoStr = streaming.objects.all() for video in videoStr: centerBlocks = [render_to_string('kirinki/section.html', {'title' : 'login', 'content': str(video.idStreaming)})] except streaming.DoesNotExist: pass self.render = MainViewer(request).render(leftBlocks, centerBlocks, []) def getRender(self): '''This method return the html rendered''' return self.render class StrForm(forms.Form): isVideo = forms.BooleanField(label='Emitir Video', required=False) srcIP = forms.IPAddressField(label='Ip de origen', required=False) srcPort = forms.IntegerField(label='Puerto de origen', required=False) srcMux = forms.ChoiceField(label='Multiplexor de origen', choices=[('ogg', 'ogg'), ('ffmpeg{mux=flv}', 'mp4'), ('webm', 'webm')], required=False) vStream = forms.ChoiceField(label='Video a emitir', choices=[], required=True) class StreamController(): '''Class to implement the Stream controller''' def __init__(self, request): if request.session.get('isConfig', False) is False: Config.getSession(request.session) if request.method == 'GET': # GET request form = StrForm(error_class=ErrorClear) form.fields['isVideo'].initial = False form.fields['srcIP'].initial = request.META['REMOTE_ADDR'] form.fields['srcPort'].initial = 9000 form.fields['vStream'].choices = self.userVideos(request) self.render = MainViewer(request).render([], [render_to_string('kirinki/form.html', {'form' : form, 'action' : request.session['base_url'] + '/stream', 'id' : 'stream'}, context_instance=RequestContext(request))], []) elif request.method == 'POST': # POST request form = StrForm(request.POST, error_class=ErrorClear) form.fields['isVideo'].initial = False form.fields['srcIP'].initial = request.META['REMOTE_ADDR'] form.fields['srcPort'].initial = 9000 form.fields['vStream'].choices = self.userVideos(request) # Check if the form data is valid and try to start the streaming if form.is_valid(): try: v = video.objects.filter(idVideo=form.cleaned_data['vStream'])[0] except video.DoesNotExist: v = None if form.cleaned_data['isVideo'] is True and v is not None: clvc = None if v.format == 'video/mp4': cvlc = subprocess.Popen(["/usr/bin/cvlc " + v.path + " --sout '#http{mux=ffmpeg{mux=flv},dst=" + request.session['strIP'] + ":" + request.session['strPort'] + "/} -no-sout-rtp-sap -no-sout-standard-sap -sout-keep' --ttl 12"], shell=True) elif v.format == 'video/webm': cvlc = subprocess.Popen(["/usr/bin/cvlc " + v.path + " --sout '#http{mux=webm,dst=" + request.session['strIP'] + ":" + request.session['strPort'] + "/} -no-sout-rtp-sap -no-sout-standard-sap -sout-keep' --ttl 12"], shell=True) elif v.format == 'video/ogg': cvlc = subprocess.Popen(["/usr/bin/cvlc " + v.path + " --sout '#http{mux=ogg,dst=" + request.session['strIP'] + ":" + request.session['strPort'] + "/} -no-sout-rtp-sap -no-sout-standard-sap -sout-keep' --ttl 12"], shell=True) else: Message.pushMessage(request, Message.ERROR,'Video type not supported') if clvc is not None: vStream = streaming(src=form.cleaned_data['srcIP'], port=form.cleaned_data['srcPort'], mux=form.cleaned_data['srcMux'], vMode=form.cleaned_data['isVideo'], pid=cvlc.pid,video=v, owner=request.session['user']) vStream.save() Message.pushMessage(request, Message.INFO,'Video streaming') elif form.cleaned_data['isVideo'] is False: if form.cleaned_data['srcMux'] != "ffmpeg{mux=flv}" and form.cleaned_data['srcMux'] != "webm" and form.cleaned_data['srcMux'] != "ogg": Message.pushMessage(request, Message.ERROR,'Video type not supported') else: cvlc = subprocess.Popen(["/usr/bin/cvlc http://" + str(form.cleaned_data['srcIP']) + ":" + str(form.cleaned_data['srcPort']) + " --sout '#http{mux=" + str(form.cleaned_data['srcMux']) + ",dst=" + request.session['strIP'] + ":" + request.session['strPort'] + "/} -no-sout-rtp-sap -no-sout-standard-sap -sout-keep' --ttl 12"], shell=True) vStream = streaming(src=form.cleaned_data['srcIP'], port=form.cleaned_data['srcPort'], mux=form.cleaned_data['srcMux'], vMode=form.cleaned_data['isVideo'], pid=cvlc.pid,video=v, owner=request.session['user']) vStream.save() Message.pushMessage(request, Message.ERROR, 'External video streaming.') else: Message.pushMessage(request, Message.ERROR, 'If you select the video mode you must select a video.') # os.waitpid(p.pid, 0)[1] self.render = HttpResponseRedirect('/streaming') else: for error in form.errors: Message.pushMessage(request, Message.ERROR, 'Error en ' + error + ': ' + str(form._errors[error])) if request.META.get('HTTP_REFERER', False) is not False: self.render = HttpResponseRedirect(request.META['HTTP_REFERER']) else: self.render = HttpResponseRedirect('/index') else: raise Http404 def userVideos(self, request): '''This method return the videos owned by the actual user.''' init = [] try: videos = video.objects.filter(owner=request.session['user']) for v in videos: init.append((v.idVideo, v.name)) except video.DoesNotExist: pass return init def getRender(self): '''This method return the html rendered''' return self.render class VideoController(): '''Class to implement the Video controller''' # Definition of the video actions LIST = 0 VIEW = 1 DELETE = 2 REFERENCE = 3 def __init__(self, request, action=0, key=None): if request.session.get('isConfig', False) is False: Config.getSession(request.session) # Blocks assigned to the left area leftBlocks = [] if not request.session['user'].is_authenticated(): leftBlocks = [render_to_string('kirinki/section.html', {'title' : 'login', 'content': render_to_string('kirinki/form.html', {'form' : LoginForm(), 'action' : request.session['base_url'] + '/login'}, context_instance=RequestContext(request))})] else: try: myVideos = video.objects.filter(owner = request.session['user']) leftBlocks = [render_to_string('kirinki/section.html', {'title' : 'Mis vídeos', 'content' : render_to_string('kirinki/myVideo.html', {'videos' : myVideos, 'session' : request.session}).encode('utf-8')})] except video.DoesNotExist: pass # Blocks assigned to the center area centerBlocks = [] if action == self.LIST: try: videoList = video.objects.all() centerBlocks = [render_to_string('kirinki/section.html', {'title' : 'Lista de videos', 'content': render_to_string('kirinki/videoList.html', {'videos' : videoList, 'session' : request.session}).encode('utf-8')})] except video.DoesNotExist: pass elif action == self.VIEW: if key is not None: try: v = video.objects.get(idVideo=key) bfile = '/media/'+v.path[v.path.rfind('/')+1:v.path.rfind('.')] src = {'orig' : request.session['base_url'] + '/media/'+v.path[v.path.rfind('/')+1:]} if os.path.exists(v.path[:v.path.rfind('.')]+'.ogv'): src['ogv'] = request.session['base_url'] +bfile+'.ogv' if os.path.exists(v.path[:v.path.rfind('.')]+'.webm'): src['webm'] = request.session['base_url'] +bfile+'.webm' if os.path.exists(v.path[:v.path.rfind('.')]+'.mp4'): src['mp4'] = request.session['base_url'] +bfile+'.mp4' if os.path.exists(v.path[:v.path.rfind('.')]+'.flv'): src['flv'] = request.session['base_url'] +bfile+'.flv' src['flash'] = request.session['base_url']+'/static/flowplayer/flowplayer-3.2.5.swf' src['flash_str'] = request.session['base_url']+'/static/flowplayer.pseudostreaming/flowplayer.pseudostreaming-3.2.5.swf' centerBlocks = [render_to_string('kirinki/section.html', {'title' : v.name, 'content': render_to_string('kirinki/video.html', {'controls' : True, 'src' : src})})] except video.DoesNotExist: pass elif action == self.DELETE: try: v = video.objects.get(idVideo=key, owner=request.session['user']) name = v.name os.remove(v.path) v.delete() centerBlocks = ['<p>Video ' + name + ' deleted.</p>'] except video.DoesNotExist: pass elif action == self.REFERENCE: pass else: # Error. Action not defined raise Http404 # Blocks assigned to the right area # Ultimos subidos, ultimos usuarios que han subido, usuarios que mas han subido, ... rightBlocks = [] self.render = MainViewer(request).render(leftBlocks, centerBlocks, rightBlocks) def getRender(self): '''This method returns the html generated''' return self.render class UploadForm(forms.Form): title = forms.CharField(label='Título', min_length=5, max_length=80, required=True) description = forms.CharField(label='Descripción', min_length=5, max_length=250, required=True) fileUpload = forms.FileField(label='Fichero', required=True) convertMP4 = forms.BooleanField(label='Convertir a mp4', required=False) convertOGG = forms.BooleanField(label='Convertir a ogg', required=False) convertWEBM = forms.BooleanField(label='Convertir a webm', required=False) class UploadController(): '''Class to implement the Upload controller. This class will be merged with the VideoController''' def __init__(self, request): if request.session.get('isConfig', False) is False: Config.getSession(request.session) if request.method == 'GET': # GET request leftBlocks = [self.getMyVideos(request.session)] centerBlocks = [self.getUploadVideo(request.session['base_url'], request)] self.render = MainViewer(request).render(leftBlocks, centerBlocks, []) elif request.method == 'POST': # POST request. form = UploadForm(request.POST, request.FILES, error_class=ErrorClear) if form.is_valid(): upFile = request.FILES['fileUpload'] if upFile.size > 0: path = '' if request.session.get('upload_path', False): path = request.session['upload_path']+'/' path += upFile.name destination = open(path, 'wb+') for chunk in upFile.chunks(): destination.write(chunk) destination.close() v = video(name=form.cleaned_data['title'], description=form.cleaned_data['description'], path=path, format=upFile.content_type, pub_date=datetime.now(), owner=request.session['user']) v.save() if form.cleaned_data['convertMP4'] and path[v.path.rfind('.'):].lower() != 'mp4': pass if form.cleaned_data['convertOGG'] and path[v.path.rfind('.'):].lower() != 'ogg': pass if form.cleaned_data['convertWEBM'] and path[v.path.rfind('.'):].lower() != 'web': pass if path[v.path.rfind('.'):].lower() != 'flv': pass else: for error in form.errors: Message.pushMessage(request, Message.ERROR, 'Error en ' + error + ': ' + str(form._errors[error])) if request.META.get('HTTP_REFERER', False) is not False: self.render = HttpResponseRedirect(request.META['HTTP_REFERER']) else: self.render = HttpResponseRedirect('/index') else: raise Http404 def getMyVideos(self, session): '''This method return the videos owned by the actual user.''' content = '' try: myVideos = video.objects.filter(owner = session['user']) content = render_to_string('kirinki/myVideo.html', {'videos' : myVideos, 'session' : session}).encode('utf-8') except video.DoesNotExist: pass return render_to_string('kirinki/section.html', {'title' : 'Mis vídeos', 'content' : content}) def getUploadVideo(self, base_url, request): content = render_to_string('kirinki/form.html', {'form' : UploadForm(request.POST, request.FILES, error_class=ErrorClear), 'action' : base_url + '/upload', 'upload' : True}, context_instance=RequestContext(request)) return render_to_string('kirinki/section.html', {'title' : 'Subir vídeo', 'content' : content}) def getRender(self): '''This method returns the html generated''' return self.render
i02sopop/Kirinki
kirinki/videos.py
Python
agpl-3.0
16,846
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** # Import the relevant PTS classes and modules from pts.modeling.core.environment import load_modeling_environment_cwd from pts.modeling.config.component import definition # ----------------------------------------------------------------- # Load environment and model suite environment = load_modeling_environment_cwd() runs = environment.fitting_runs # ----------------------------------------------------------------- properties = ["representation", "filters", "ranges", "genetic", "grid", "units", "types"] # ----------------------------------------------------------------- definition = definition.copy() # ----------------------------------------------------------------- # The fitting run for which to adapt the configuration if runs.empty: raise RuntimeError("No fitting runs are present") elif runs.has_single: definition.add_fixed("name", "name of the fitting run", runs.single_name) else: definition.add_required("name", "string", "name of the fitting run", choices=runs.names) # ----------------------------------------------------------------- # Dust or stellar definition.add_positional_optional("properties", "string_list", "properties to adapt", default=properties, choices=properties) # ----------------------------------------------------------------- # Select certain properties definition.add_optional("contains", "string", "only adapt properties containing this string in their name") definition.add_optional("not_contains", "string", "don't adapt properties containing this string in their name") definition.add_optional("exact_name", "string", "only adapt properties with this exact string as their name") definition.add_optional("exact_not_name", "string", "don't adapt properties with this exact string as their name") definition.add_optional("startswith", "string", "only adapt properties whose name starts with this string") definition.add_optional("endswith", "string", "only adapt properties whose name starts with this string") # ----------------------------------------------------------------- # Save definition.add_flag("save", "save adapted properties", True) # -----------------------------------------------------------------
SKIRT/PTS
modeling/config/adapt_fit.py
Python
agpl-3.0
2,495
/* * Copyright 2013-2018 Emmanuel BRUN (contact@amapj.fr) * * This file is part of AmapJ. * * AmapJ is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * AmapJ 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with AmapJ. If not, see <http://www.gnu.org/licenses/>. * * */ package fr.amapj.model.engine.transaction; public @interface DbWrite { }
amapj/amapj
amapj/src/fr/amapj/model/engine/transaction/DbWrite.java
Java
agpl-3.0
868
import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files class Command(BaseCommand): """ Upgrades Janeway """ help = "Upgrades an install from one version to another." def add_arguments(self, parser): """Adds arguments to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.get('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`') else: translation.activate('en') upgrade_module_name = options.get('path') upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name) try: upgrade_module = import_module(upgrade_module_path) upgrade_module.execute() except ImportError as e: print('There was an error running the requested upgrade: ') print(e)
BirkbeckCTP/janeway
src/utils/management/commands/run_upgrade.py
Python
agpl-3.0
1,613
from .naive import StratNaive import random import numpy as np class BetaDecreaseStrat(StratNaive): def __init__(self, vu_cfg, time_scale=0.9, **strat_cfg2): StratNaive.__init__(self,vu_cfg=vu_cfg, **strat_cfg2) self.time_scale = time_scale def update_speaker(self, ms, w, mh, voc, mem, bool_succ, context=[]): self.voc_update.beta = max(0,self.voc_update.beta - 1./self.time_scale) return self.voc_update.update_speaker(ms, w, mh, voc, mem, bool_succ, context) def update_hearer(self, ms, w, mh, voc, mem, bool_succ, context=[]): self.voc_update.beta = max(0,self.voc_update.beta - 1./self.time_scale) return self.voc_update.update_hearer(ms, w, mh, voc, mem, bool_succ, context)
flowersteam/naminggamesal
naminggamesal/ngstrat/beta_decrease.py
Python
agpl-3.0
700
/* * Copyright © 2013-2018 Metreeca srl. All rights reserved. * * This file is part of Metreeca. * * Metreeca is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Metreeca 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Metreeca. If not, see <http://www.gnu.org/licenses/>. */ package com.metreeca.spec.codecs; import com.metreeca.jeep.rdf.Values; import com.metreeca.spec.Shape; import com.metreeca.spec.Shift; import com.metreeca.spec.Spec; import com.metreeca.spec.shapes.*; import com.metreeca.spec.shifts.Count; import com.metreeca.spec.shifts.Step; import org.eclipse.rdf4j.model.*; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.util.RDFCollections; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.Rio; import java.io.IOException; import java.io.StringReader; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Collection; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Stream; import static com.metreeca.jeep.rdf.Cell.Missing; import static com.metreeca.jeep.rdf.Values.bnode; import static com.metreeca.jeep.rdf.Values.integer; import static com.metreeca.jeep.rdf.Values.statement; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; public final class ShapeCodec { private static final RDFFormat Format=RDFFormat.NTRIPLES; public Resource encode(final Shape shape, final Collection<Statement> model) { if ( shape == null ) { throw new IllegalArgumentException("null shape"); } if ( model == null ) { throw new IllegalArgumentException("null model"); } return shape(shape, model); } public Shape decode(final Resource root, final Collection<Statement> model) { if ( root == null ) { throw new IllegalArgumentException("null root"); } if ( model == null ) { throw new IllegalArgumentException("null model"); } return shape(root, model); } public Shape decode(final String spec) { // !!! review/remove if ( spec == null ) { throw new IllegalArgumentException("null spec"); } try { final Model model=Rio.parse(new StringReader(spec), "", Format); final Resource root=model.subjects().stream() .filter(subject -> !model.contains(null, null, subject)) .findFirst().orElseThrow(Missing); return decode(root, model); } catch ( final IOException e ) { throw new UncheckedIOException(e); } } //// Shapes //////////////////////////////////////////////////////////////////////////////////////////////////////// private Resource shape(final Shape shape, final Collection<Statement> model) { return shape.accept(new Shape.Probe<Resource>() { @Override public Resource visit(final Datatype datatype) { return datatype(datatype, model); } @Override public Resource visit(final Clazz clazz) { return clazz(clazz, model); } @Override public Resource visit(final MinExclusive minExclusive) { return minExclusive(minExclusive, model); } @Override public Resource visit(final MaxExclusive maxExclusive) { return maxExclusive(maxExclusive, model); } @Override public Resource visit(final MinInclusive minInclusive) { return minInclusive(minInclusive, model); } @Override public Resource visit(final MaxInclusive maxInclusive) { return maxInclusive(maxInclusive, model); } @Override public Resource visit(final Pattern pattern) { return pattern(pattern, model); } @Override public Resource visit(final Like like) { return like(like, model); } @Override public Resource visit(final MinLength minLength) { return minLength(minLength, model); } @Override public Resource visit(final MaxLength maxLength) { return maxLength(maxLength, model); } @Override public Resource visit(final MinCount minCount) { return minCount(minCount, model); } @Override public Resource visit(final MaxCount maxCount) { return maxCount(maxCount, model); } @Override public Resource visit(final In in) { return in(in, model); } @Override public Resource visit(final All all) { return all(all, model); } @Override public Resource visit(final Any any) { return any(any, model); } @Override public Resource visit(final Trait trait) { return trait(trait, model); } @Override public Resource visit(final Virtual virtual) { return virtual(virtual, model); } @Override public Resource visit(final And and) { return and(and, model); } @Override public Resource visit(final Or or) { return or(or, model); } @Override public Resource visit(final Test test) { return test(test, model); } @Override public Resource visit(final When when) { return when(when, model); } @Override public Resource visit(final Alias alias) { return alias(alias, model); } @Override public Resource visit(final Label label) { return label(label, model); } @Override public Resource visit(final Notes notes) { return notes(notes, model); } @Override public Resource visit(final Placeholder placeholder) { return placeholder(placeholder, model); } @Override public Resource visit(final Default dflt) { return dflt(dflt, model); } @Override public Resource visit(final Hint hint) { return hint(hint, model); } @Override public Resource visit(final Group group) { return group(group, model); } @Override protected Resource fallback(final Shape shape) { throw new UnsupportedOperationException("unsupported shape ["+shape+"]"); } }); } private Shape shape(final Resource root, final Collection<Statement> model) { final Set<Value> types=types(root, model); return types.contains(Spec.Datatype) ? datatype(root, model) : types.contains(Spec.Class) ? clazz(root, model) : types.contains(Spec.MinExclusive) ? minExclusive(root, model) : types.contains(Spec.MaxExclusive) ? maxExclusive(root, model) : types.contains(Spec.MinInclusive) ? minInclusive(root, model) : types.contains(Spec.MaxInclusive) ? maxInclusive(root, model) : types.contains(Spec.Pattern) ? pattern(root, model) : types.contains(Spec.Like) ? like(root, model) : types.contains(Spec.MinLength) ? minLength(root, model) : types.contains(Spec.MaxLength) ? maxLength(root, model) : types.contains(Spec.MinCount) ? minCount(root, model) : types.contains(Spec.MaxCount) ? maxCount(root, model) : types.contains(Spec.In) ? in(root, model) : types.contains(Spec.All) ? all(root, model) : types.contains(Spec.Any) ? any(root, model) : types.contains(Spec.required) ? required(root, model) : types.contains(Spec.optional) ? optional(root, model) : types.contains(Spec.repeatable) ? repeatable(root, model) : types.contains(Spec.multiple) ? multiple(root, model) : types.contains(Spec.only) ? only(root, model) : types.contains(Spec.Trait) ? trait(root, model) : types.contains(Spec.Virtual) ? virtual(root, model) : types.contains(Spec.And) ? and(root, model) : types.contains(Spec.Or) ? or(root, model) : types.contains(Spec.Test) ? test(root, model) : types.contains(Spec.When) ? when(root, model) : types.contains(Spec.Alias) ? alias(root, model) : types.contains(Spec.Label) ? label(root, model) : types.contains(Spec.Notes) ? notes(root, model) : types.contains(Spec.Placeholder) ? placeholder(root, model) : types.contains(Spec.Default) ? dflt(root, model) : types.contains(Spec.Hint) ? hint(root, model) : types.contains(Spec.Group) ? group(root, model) : types.contains(Spec.create) ? create(root, model) : types.contains(Spec.relate) ? relate(root, model) : types.contains(Spec.update) ? update(root, model) : types.contains(Spec.delete) ? delete(root, model) : types.contains(Spec.client) ? client(root, model) : types.contains(Spec.server) ? server(root, model) : types.contains(Spec.digest) ? digest(root, model) : types.contains(Spec.detail) ? detail(root, model) : types.contains(Spec.verify) ? verify(root, model) : types.contains(Spec.filter) ? filter(root, model) : error("unknown shape type "+types); } private Resource datatype(final Datatype datatype, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Datatype)); model.add(statement(node, Spec.iri, datatype.getIRI())); return node; } private Shape datatype(final Resource root, final Collection<Statement> model) { return Datatype.datatype(iri(root, Spec.iri, model)); } private Resource clazz(final Clazz clazz, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Class)); model.add(statement(node, Spec.iri, clazz.getIRI())); return node; } private Shape clazz(final Resource root, final Collection<Statement> model) { return Clazz.clazz(iri(root, Spec.iri, model)); } private Resource minExclusive(final MinExclusive minExclusive, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.MinExclusive)); model.add(statement(node, Spec.value, minExclusive.getValue())); return node; } private Shape minExclusive(final Resource root, final Collection<Statement> model) { return MinExclusive.minExclusive(value(root, Spec.value, model)); } private Resource maxExclusive(final MaxExclusive maxExclusive, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.MaxExclusive)); model.add(statement(node, Spec.value, maxExclusive.getValue())); return node; } private Shape maxExclusive(final Resource root, final Collection<Statement> model) { return MaxExclusive.maxExclusive(value(root, Spec.value, model)); } private Resource minInclusive(final MinInclusive minInclusive, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.MinInclusive)); model.add(statement(node, Spec.value, minInclusive.getValue())); return node; } private Shape minInclusive(final Resource root, final Collection<Statement> model) { return MinInclusive.minInclusive(value(root, Spec.value, model)); } private Resource maxInclusive(final MaxInclusive maxInclusive, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.MaxInclusive)); model.add(statement(node, Spec.value, maxInclusive.getValue())); return node; } private Shape maxInclusive(final Resource root, final Collection<Statement> model) { return MaxInclusive.maxInclusive(value(root, Spec.value, model)); } private Resource pattern(final Pattern pattern, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Pattern)); model.add(statement(node, Spec.text, Values.literal(pattern.getText()))); model.add(statement(node, Spec.flags, Values.literal(pattern.getFlags()))); return node; } private Shape pattern(final Resource root, final Collection<Statement> model) { return Pattern.pattern( literal(root, Spec.text, model).stringValue(), literal(root, Spec.flags, model).stringValue()); } private Resource like(final Like like, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Like)); model.add(statement(node, Spec.text, Values.literal(like.getText()))); return node; } private Shape like(final Resource root, final Collection<Statement> model) { return Like.like(literal(root, Spec.text, model).stringValue()); } private Resource minLength(final MinLength minLength, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.MinLength)); model.add(statement(node, Spec.limit, Values.literal(integer(minLength.getLimit())))); return node; } private Shape minLength(final Resource root, final Collection<Statement> model) { return MinLength.minLength(literal(root, Spec.limit, model).integerValue().intValue()); } private Resource maxLength(final MaxLength maxLength, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.MaxLength)); model.add(statement(node, Spec.limit, Values.literal(integer(maxLength.getLimit())))); return node; } private Shape maxLength(final Resource root, final Collection<Statement> model) { return MaxLength.maxLength(literal(root, Spec.limit, model).integerValue().intValue()); } private Resource minCount(final MinCount minCount, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.MinCount)); model.add(statement(node, Spec.limit, Values.literal(integer(minCount.getLimit())))); return node; } private Shape minCount(final Resource root, final Collection<Statement> model) { return MinCount.minCount(literal(root, Spec.limit, model).integerValue().intValue()); } private Resource maxCount(final MaxCount maxCount, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.MaxCount)); model.add(statement(node, Spec.limit, Values.literal(integer(maxCount.getLimit())))); return node; } private Shape maxCount(final Resource root, final Collection<Statement> model) { return MaxCount.maxCount(literal(root, Spec.limit, model).integerValue().intValue()); } private Resource in(final In in, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.In)); model.add(statement(node, Spec.values, values(in.getValues(), model))); return node; } private Shape in(final Resource root, final Collection<Statement> model) { return In.in(values(resource(root, Spec.values, model), model)); } private Resource all(final All all, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.All)); model.add(statement(node, Spec.values, values(all.getValues(), model))); return node; } private Shape all(final Resource root, final Collection<Statement> model) { return All.all(values(resource(root, Spec.values, model), model)); } private Resource any(final Any any, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Any)); model.add(statement(node, Spec.values, values(any.getValues(), model))); return node; } private Shape any(final Resource root, final Collection<Statement> model) { return Any.any(values(resource(root, Spec.values, model), model)); } private Shape required(final Resource root, final Collection<Statement> model) { return Shape.required(); } private Shape optional(final Resource root, final Collection<Statement> model) { return Shape.optional(); } private Shape repeatable(final Resource root, final Collection<Statement> model) { return Shape.repeatable(); } private Shape multiple(final Resource root, final Collection<Statement> model) { return Shape.multiple(); } private Shape only(final Resource root, final Collection<Statement> model) { return Shape.only(values(resource(root, Spec.values, model), model)); } private Resource trait(final Trait trait, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Trait)); model.add(statement(node, Spec.step, step(trait.getStep(), model))); model.add(statement(node, Spec.shape, shape(trait.getShape(), model))); return node; } private Trait trait(final Resource root, final Collection<Statement> model) { return Trait.trait( step(resource(root, Spec.step, model), model), shape(resource(root, Spec.shape, model), model) ); } private Resource virtual(final Virtual virtual, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Virtual)); model.add(statement(node, Spec.trait, shape(virtual.getTrait(), model))); model.add(statement(node, Spec.shift, shift(virtual.getShift(), model))); return node; } private Shape virtual(final Resource root, final Collection<Statement> model) { return Virtual.virtual( trait(resource(root, Spec.trait, model), model), shift(resource(root, Spec.shift, model), model) ); } private Resource and(final And and, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.And)); model.add(statement(node, Spec.shapes, shapes(and.getShapes(), model))); return node; } private Shape and(final Resource root, final Collection<Statement> model) { final Resource shapes=resource(root, Spec.shapes, model); return shapes.equals(RDF.NIL) ? And.and() : And.and(shapes(shapes, model)); } private Resource or(final Or or, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Or)); model.add(statement(node, Spec.shapes, shapes(or.getShapes(), model))); final Collection<Shape> shapes=or.getShapes(); return node; } private Shape or(final Resource root, final Collection<Statement> model) { final Resource shapes=resource(root, Spec.shapes, model); return shapes.equals(RDF.NIL) ? Or.or() : Or.or(shapes(shapes, model)); } private Resource test(final Test test, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Test)); model.add(statement(node, Spec.test, shape(test.getTest(), model))); model.add(statement(node, Spec.pass, shape(test.getPass(), model))); model.add(statement(node, Spec.fail, shape(test.getFail(), model))); return node; } private Shape test(final Resource root, final Collection<Statement> model) { return Test.test( shape(resource(root, Spec.test, model), model), shape(resource(root, Spec.pass, model), model), shape(resource(root, Spec.fail, model), model) ); } private Resource when(final When when, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.When)); model.add(statement(node, Spec.iri, when.getIRI())); model.add(statement(node, Spec.values, values(when.getValues(), model))); return node; } private Shape when(final Resource root, final Collection<Statement> model) { return When.when( iri(root, Spec.iri, model), values(resource(root, Spec.values, model), model) ); } private Resource alias(final Alias alias, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Alias)); model.add(statement(node, Spec.text, Values.literal(alias.getText()))); return node; } private Shape alias(final Resource root, final Collection<Statement> model) { return Alias.alias(literal(root, Spec.text, model).stringValue()); } private Resource label(final Label label, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Label)); model.add(statement(node, Spec.text, Values.literal(label.getText()))); return node; } private Shape label(final Resource root, final Collection<Statement> model) { return Label.label(literal(root, Spec.text, model).stringValue()); } private Resource notes(final Notes notes, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Notes)); model.add(statement(node, Spec.text, Values.literal(notes.getText()))); return node; } private Shape notes(final Resource root, final Collection<Statement> model) { return Notes.notes(literal(root, Spec.text, model).stringValue()); } private Resource placeholder(final Placeholder placeholder, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Placeholder)); model.add(statement(node, Spec.text, Values.literal(placeholder.getText()))); return node; } private Shape placeholder(final Resource root, final Collection<Statement> model) { return Placeholder.placeholder(literal(root, Spec.text, model).stringValue()); } private Resource dflt(final Default dflt, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Default)); model.add(statement(node, Spec.value, dflt.getValue())); return node; } private Shape dflt(final Resource root, final Collection<Statement> model) { return Default.dflt(value(root, Spec.value, model)); } private Resource hint(final Hint hint, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Hint)); model.add(statement(node, Spec.iri, hint.getIRI())); return node; } private Shape hint(final Resource root, final Collection<Statement> model) { return Hint.hint(iri(root, Spec.iri, model)); } private Resource group(final Group group, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Group)); model.add(statement(node, Spec.shape, shape(group.getShape(), model))); return node; } private Shape group(final Resource root, final Collection<Statement> model) { return Group.group(shape(resource(root, Spec.shape, model), model)); } private Shape create(final Resource root, final Collection<Statement> model) { return Shape.create(shapes(resource(root, Spec.shapes, model), model)); } private Shape relate(final Resource root, final Collection<Statement> model) { return Shape.relate(shapes(resource(root, Spec.shapes, model), model)); } private Shape update(final Resource root, final Collection<Statement> model) { return Shape.update(shapes(resource(root, Spec.shapes, model), model)); } private Shape delete(final Resource root, final Collection<Statement> model) { return Shape.delete(shapes(resource(root, Spec.shapes, model), model)); } private Shape client(final Resource root, final Collection<Statement> model) { return Shape.client(shapes(resource(root, Spec.shapes, model), model)); } private Shape server(final Resource root, final Collection<Statement> model) { return Shape.server(shapes(resource(root, Spec.shapes, model), model)); } private Shape digest(final Resource root, final Collection<Statement> model) { return Shape.digest(shapes(resource(root, Spec.shapes, model), model)); } private Shape detail(final Resource root, final Collection<Statement> model) { return Shape.detail(shapes(resource(root, Spec.shapes, model), model)); } private Shape verify(final Resource root, final Collection<Statement> model) { return Shape.verify(shapes(resource(root, Spec.shapes, model), model)); } private Shape filter(final Resource root, final Collection<Statement> model) { return Shape.filter(shapes(resource(root, Spec.shapes, model), model)); } private Shape error(final String message) { throw new UnsupportedOperationException(message); } //// Shifts //////////////////////////////////////////////////////////////////////////////////////////////////////// private Resource shift(final Shift shift, final Collection<Statement> model) { return shift.accept(new Shift.Probe<Resource>() { @Override protected Resource fallback(final Shift shift) { throw new UnsupportedOperationException("unsupported shift ["+shift+"]"); } @Override public Resource visit(final Step step) { return step(step, model); } @Override public Resource visit(final Count count) { return count(count, model); } }); } private Shift shift(final Resource root, final Collection<Statement> model) { final Set<Value> types=types(root, model); return types.contains(Spec.Step) ? step(root, model) : types.contains(Spec.Count) ? count(root, model) : shift("unknown shape type "+types); } private Resource step(final Step step, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Step)); model.add(statement(node, Spec.iri, step.getIRI())); model.add(statement(node, Spec.inverse, Values.literal(step.isInverse()))); return node; } private Step step(final Resource root, final Collection<Statement> model) { return Step.step( iri(root, Spec.iri, model), literal(root, Spec.inverse, model).booleanValue() ); } private Resource count(final Count count, final Collection<Statement> model) { final Resource node=bnode(); model.add(statement(node, RDF.TYPE, Spec.Count)); model.add(statement(node, Spec.shift, shift(count.getShift(), model))); return node; } private Count count(final Resource root, final Collection<Statement> model) { return Count.count(shift(root, model)); } private Shift shift(final String message) { throw new UnsupportedOperationException(message); } //// Shape Lists /////////////////////////////////////////////////////////////////////////////////////////////////// private Value shapes(final Collection<Shape> shapes, final Collection<Statement> model) { return values(shapes.stream() .map(s -> shape(s, model)) .collect(toList()), model); } private Collection<Shape> shapes(final Resource shapes, final Collection<Statement> model) { return values(shapes, model) .stream() .filter(v -> v instanceof Resource) // !!! error reporting .map(v -> (Resource)v) .map(v -> decode(v, model)) .collect(toList()); } //// Value Lists /////////////////////////////////////////////////////////////////////////////////////////////////// private Value values(final Collection<Value> values, final Collection<Statement> model) { if ( values.isEmpty() ) { return RDF.NIL; } else { final Resource items=bnode(); RDFCollections.asRDF(values, items, model); return items; } } private Collection<Value> values(final Resource items, final Collection<Statement> model) { return RDFCollections.asValues(new LinkedHashModel(model), items, new ArrayList<>()); // !!! avoid model construction } //// Decoding ////////////////////////////////////////////////////////////////////////////////////////////////////// private Set<Value> types(final Resource root, final Collection<Statement> model) { return objects(root, RDF.TYPE, model).collect(toSet()); } private IRI iri(final Resource subject, final IRI predicate, final Collection<Statement> model) { return objects(subject, predicate, model) .filter(v -> v instanceof IRI) .map(v -> (IRI)v) .findFirst() .orElseThrow(missing(subject, predicate)); } private Resource resource(final Resource subject, final IRI predicate, final Collection<Statement> model) { return objects(subject, predicate, model) .filter(v -> v instanceof Resource) .map(v -> (Resource)v) .findFirst() .orElseThrow(missing(subject, predicate)); } private Literal literal(final Resource subject, final IRI predicate, final Collection<Statement> model) { return objects(subject, predicate, model) .filter(v -> v instanceof Literal) .map(v -> (Literal)v) .findFirst() .orElseThrow(missing(subject, predicate)); } private Value value(final Resource subject, final IRI predicate, final Collection<Statement> model) { return objects(subject, predicate, model) .findFirst() .orElseThrow(missing(subject, predicate)); } private Stream<Value> objects(final Resource subject, final IRI predicate, final Collection<Statement> model) { return model.stream() .filter(s -> s.getSubject().equals(subject) && s.getPredicate().equals(predicate)) .map(Statement::getObject); } private Supplier<IllegalArgumentException> missing(final Resource subject, final IRI predicate) { return () -> new IllegalArgumentException( "missing "+Values.format(predicate)+" property ["+subject+"]"); } }
metreeca/metreeca
back/spec/src/main/java/com/metreeca/spec/codecs/ShapeCodec.java
Java
agpl-3.0
28,505
# -*- coding: utf-8 -*- # Copyright (C) 2014-present Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.db import connection from django.conf import settings from django.utils import timezone from taiga.projects.history import services as history_service from taiga.projects.history.choices import HistoryType from . import tasks def _get_project_webhooks(project): webhooks = [] for webhook in project.webhooks.all(): webhooks.append({ "id": webhook.pk, "url": webhook.url, "key": webhook.key, }) return webhooks def on_new_history_entry(sender, instance, created, **kwargs): if not settings.WEBHOOKS_ENABLED: return None if instance.is_hidden: return None model = history_service.get_model_from_key(instance.key) pk = history_service.get_pk_from_key(instance.key) try: obj = model.objects.get(pk=pk) except model.DoesNotExist: # Catch simultaneous DELETE request return None webhooks = _get_project_webhooks(obj.project) if instance.type == HistoryType.create: task = tasks.create_webhook extra_args = [] elif instance.type == HistoryType.change: task = tasks.change_webhook extra_args = [instance] elif instance.type == HistoryType.delete: task = tasks.delete_webhook extra_args = [] by = instance.owner date = timezone.now() webhooks_args = [] for webhook in webhooks: args = [webhook["id"], webhook["url"], webhook["key"], by, date, obj] + extra_args webhooks_args.append(args) connection.on_commit(lambda: _execute_task(task, webhooks_args)) def _execute_task(task, webhooks_args): for webhook_args in webhooks_args: if settings.CELERY_ENABLED: task.delay(*webhook_args) else: task(*webhook_args)
taigaio/taiga-back
taiga/webhooks/signal_handlers.py
Python
agpl-3.0
2,526
"use strict"; var types = require('./types'); var Tree = require('./tree'); var Rule = require('./rule'); var Principle = require('./principle'); var Lexicon = require('./lexicon'); var Nothing = types.Nothing; var eq = types.eq; var normalize = types.normalize; function Parser ( grammar ) { return { borjes: 'parser', rules: grammar.rules, principles: grammar.principles, lexicon: grammar.lexicon, table: [], n: 0 } } function all_matches ( p, a_x, a_y, b_x, b_y ) { var a = p.table[a_x][a_y]; var b = p.table[b_x][b_y]; var matches = []; for (var i = 0; i<a.length; i++) { for (var j = 0; j<b.length; j++) { matches.push([a[i], b[j]]); } } return matches; } function all_legs ( p, from, to, n ) { if (n!=2) { throw "Non-binary rules not supported"; } var legs = []; for (var i = to-1; i >= 0; i--) { legs = legs.concat(all_matches(p, from, i, from+i+1, to-(i+1))); } return legs; }; function apply_principles ( p, ms, success, i ) { i = i || 0; if (i>=p.principles.length) { for (var j=0; j<ms.length; j++) { success(ms[j]); } } else { var prin = p.principles[i]; for (var j=0; j<ms.length; j++) { var r = Principle.apply(prin, ms[j]); apply_principles(p, r, success, i+1); } } } function exhaust ( p, from, to ) { p.table[from][to] = []; var cell = p.table[from][to]; for (var i = 0; i<p.rules.length; i++) { var rule = p.rules[i]; var legs = all_legs(p, from, to, rule.arity); for (var j = 0; j<legs.length; j++) { var mothers = Rule.apply(rule, legs[j].map(function(t) { return t.node; })); apply_principles(p, mothers, function(x) { cell.push(Tree(normalize(x), legs[j])); }); } } }; function input ( p, word ) { var w = Lexicon.get(p.lexicon, word); if (w === undefined) { w = Nothing; } var wordt = Tree(word); if (!w.length) { p.table[p.n] = [[ Tree(w, wordt) ]]; } else { p.table[p.n] = []; p.table[p.n][0] = w.map(function(x) { return Tree(x, wordt); }); } for (var i = p.n-1; i>=0; i--) { exhaust(p, i, p.n-i); } p.n++; }; function parse ( p, sentence ) { if (p.borjes !== 'parser') { p = Parser(p); } else { reset(p); } for (var i = 0; i<sentence.length; i++) { input(p, sentence[i]); } var top = p.table[0][p.n-1]; if (top.length === 0) { return Nothing; } else { return top; } }; function reset ( p ) { p.table = []; p.n = 0; }; Parser.reset = reset; Parser.input = input; Parser.parse = parse; module.exports = Parser;
agarsev/borjes
src/parser.js
JavaScript
agpl-3.0
2,855
<?php namespace Scuola247\Bundle\CoreBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class PersonefisicheType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('nome') ->add('cognome') ->add('sesso') ->add('natoil') ->add('decedutoil') ->add('comunedinascita') ->add('codicefiscale') ->add('statocivile') ->add('personafisica') ->add('tutore') ->add('padre') ->add('nazionedinascita') ->add('madre'); } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Scuola247\Bundle\CoreBundle\Entity\Personefisiche' )); } /** * @return string */ public function getName() { return 'scuola247_bundle_corebundle_personefisichetype'; } }
marcoalbarelli/PostgreSQL
Symfony/src/Scuola247/Bundle/CoreBundle/Form/PersonefisicheType.php
PHP
agpl-3.0
1,283
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.test; import org.silverpeas.core.annotation.Provider; import org.silverpeas.core.util.ServiceProvider; import javax.annotation.Resource; import javax.enterprise.inject.Produces; import javax.sql.DataSource; /** * A convenient provider of the data source used in the integration tests. * @author mmoquillon */ @Provider public class DataSourceProvider { @Resource(lookup = "java:/datasources/silverpeas") private DataSource dataSource; private static DataSourceProvider getInstance() { return ServiceProvider.getSingleton(DataSourceProvider.class); } @Produces public static DataSource getDataSource() { return getInstance().dataSource; } }
SilverDav/Silverpeas-Core
core-test/src/main/java/org/silverpeas/core/test/DataSourceProvider.java
Java
agpl-3.0
1,833
<?php use SuiteCRM\Test\SuitePHPUnitFrameworkTestCase; class AOS_InvoicesTest extends SuitePHPUnitFrameworkTestCase { protected function setUp() { parent::setUp(); global $current_user; get_sugar_config_defaults(); $current_user = new User(); } public function testAOS_Invoices() { // Execute the constructor and check for the Object type and attributes $aosInvoices = new AOS_Invoices(); $this->assertInstanceOf('AOS_Invoices', $aosInvoices); $this->assertInstanceOf('Basic', $aosInvoices); $this->assertInstanceOf('SugarBean', $aosInvoices); $this->assertAttributeEquals('AOS_Invoices', 'module_dir', $aosInvoices); $this->assertAttributeEquals('AOS_Invoices', 'object_name', $aosInvoices); $this->assertAttributeEquals('aos_invoices', 'table_name', $aosInvoices); $this->assertAttributeEquals(true, 'new_schema', $aosInvoices); $this->assertAttributeEquals(true, 'disable_row_level_security', $aosInvoices); $this->assertAttributeEquals(true, 'importable', $aosInvoices); } public function testSaveAndMark_deleted() { $aosInvoices = new AOS_Invoices(); $aosInvoices->name = 'test'; $aosInvoices->save(); //test for record ID to verify that record is saved $this->assertTrue(isset($aosInvoices->id)); $this->assertEquals(36, strlen($aosInvoices->id)); $this->assertGreaterThan(0, $aosInvoices->number); //mark the record as deleted and verify that this record cannot be retrieved anymore. $aosInvoices->mark_deleted($aosInvoices->id); $result = $aosInvoices->retrieve($aosInvoices->id); $this->assertEquals(null, $result); } }
ChangezKhan/SuiteCRM
tests/unit/phpunit/modules/AOS_Invoices/AOS_InvoicesTest.php
PHP
agpl-3.0
1,783
/* * Copyright (c) 2019 The Hyve B.V. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mskcc.cbio.portal.model; import java.io.Serializable; /** * @author Pim van Nierop, pim@thehyve.nl */ public class Treatment implements Serializable { private int id; private int geneticEntityId; private String stableId; private String name; private String description; private String refLink; /** * Create a Treatment object from fields * * @param treatmentId Treatment table ID key of the treament * @param geneticEntityId Genetic_entity table ID key associated to the treament record * @param stableId Stable identifier of the treatment used in the cBioPortal instance * @param name Name of the treatment * @param description Description of the treatment * @param refLink Url for the treatment */ public Treatment(int id, int geneticEntityId, String stableId, String name, String description, String refLink) { this.geneticEntityId = geneticEntityId; this.geneticEntityId = geneticEntityId; this.stableId = stableId; this.name = name; this.description = description; this.refLink = refLink; } /** * Create a Treatment object from fields * * @param treatmentId Treatment table ID key of the treament * @param geneticEntityId Genetic_entity table ID key associated to the treament record * @param stableId Stable identifier of the treatment used in the cBioPortal instance * @param name Name of the treatment * @param description Description of the treatment * @param refLink Url for the treatment */ public Treatment(String stableId, String name, String description, String refLink) { this.stableId = stableId; this.name = name; this.description = description; this.refLink = refLink; } /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the geneticEntityId */ public int getGeneticEntityId() { return geneticEntityId; } /** * @param geneticEntityId the geneticEntityId to set */ public void setGeneticEntityId(Integer geneticEntityId) { this.geneticEntityId = geneticEntityId; } /** * @return the stableId */ public String getStableId() { return stableId; } /** * @param stableId the stableId to set */ public void setStableId(String stableId) { this.stableId = stableId; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the refLink */ public String getRefLink() { return refLink; } /** * @param refLink the refLink to set */ public void setRefLink(String refLink) { this.refLink = refLink; } }
pughlab/cbioportal
core/src/main/java/org/mskcc/cbio/portal/model/Treatment.java
Java
agpl-3.0
4,931
<?php declare(strict_types=1); /* * This file is part of the Superdesk Web Publisher Core Bundle. * * Copyright 2020 Sourcefabric z.ú. and contributors. * * For the full copyright and license information, please see the * AUTHORS and LICENSE files distributed with this source code. * * @copyright 2020 Sourcefabric z.ú * @license http://www.superdesk.org/license */ namespace SWP\Bundle\CoreBundle\Form\Type; use SWP\Bundle\ContentBundle\Form\Type\RouteSelectorType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; final class ExportAnalyticsRouteType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('id', RouteSelectorType::class) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(['csrf_protection' => false]); } public function getBlockPrefix() { return ''; } }
superdesk/web-publisher
src/SWP/Bundle/CoreBundle/Form/Type/ExportAnalyticsRouteType.php
PHP
agpl-3.0
1,103
import React from 'react'; export function MessagePanel(props, context) { let message = context.messenger.getMessage(); let messagePanel; if (message !== undefined) { messagePanel = ( <div className={ 'alert alert-' + message.type }> { message.text } </div> ); context.messenger.clearMessages(); } else { messagePanel = ( <div style={{ 'display': 'none' }}></div> ); } return messagePanel; } MessagePanel.contextTypes = { messenger: React.PropTypes.object };
mapkiwiz/sectorisation
src/client/app/panels/message.panel.js
JavaScript
agpl-3.0
534
/* * Logger.cpp * * Created on: 2013. 9. 16. * Author: ilvsusie */ #include "Logger.h" #include "Poco/Logger.h" #include "Poco/SimpleFileChannel.h" #include "Poco/AutoPtr.h" #include "Poco/Message.h" #include "Poco/PatternFormatter.h" #include "Poco/FormattingChannel.h" using Poco::Channel; using Poco::Formatter; using Poco::SimpleFileChannel; using Poco::AutoPtr; using Poco::PatternFormatter; using Poco::FormattingChannel; namespace nanolat { Logger gLogger; Logger::Logger() { AutoPtr<SimpleFileChannel> pChannel(new SimpleFileChannel); pChannel->setProperty("path", "nanolat.log"); pChannel->setProperty("rotation", "10 M"); //"%d-%m-%Y %H:%M:%S: %t" AutoPtr<Formatter> formatter(new PatternFormatter("%d-%m-%Y %H:%M:%S %s: %t")); AutoPtr<Channel> formattingChannel(new FormattingChannel(formatter, pChannel)); Poco::Logger::root().setChannel(formattingChannel); logger_ = & Poco::Logger::get("SoTopless"); #if defined(NDEBUG) logger_->setLevel(Poco::Message::PRIO_INFORMATION); #else // Debug mode -> PRIO_TRACE logger_->setLevel(Poco::Message::PRIO_TRACE); #endif } Logger::~Logger() { // TODO Auto-generated destructor stub } } /* namespace nanolat */
Nanolat/sotopless
src/server/Logger.cpp
C++
agpl-3.0
1,222
<?php $data_on['CONNEXION']=$l->g(1255); $data_on['BAD CONNEXION']=$l->g(1256); if (!isset($protectedPost['onglet'])) $protectedPost['onglet']='CONNEXION'; if ($protectedPost['onglet'] == 'CONNEXION' or $protectedPost['onglet'] == 'BAD CONNEXION') { $ms_cfg_file=$_SESSION['OCS']['LOG_DIR']."log.csv"; $fd = @fopen ($ms_cfg_file, "r"); if (!$fd) return "NO_FILES"; $max=0; $array_profil[7]=$l->g(1259); $array_profil[30]=$l->g(1260); $array_profil['ALL']=$l->g(215); if (!isset($protectedPost['REST'])) $protectedPost['REST']=7; $stats.= $l->g(1251). ": " .show_modif($array_profil,"REST",2,$form_name)."<br>"; if (isset($protectedPost['REST']) and $protectedPost['REST'] != 'ALL') $lastWeek = time() - ($protectedPost['REST'] * 24 * 60 * 60); //msg_error(time()."=>".$lastWeek); //echo date('d/m/Y', $lastWeek) ; while( !feof($fd) ) { $line = trim( fgets( $fd, 256 ) ); $trait=explode (';',$line); if ($trait[3]==$protectedPost['onglet']){ $h=explode(' ',$trait[1]); $time=explode('/',$h[0]); //echo mktime(0, 0, 0, $time[1], $time[0], $time[2])." => ".$lastWeek."<br>" ; if (mktime(0, 0, 0, $time[1], $time[0], $time[2])>= $lastWeek){ $find_connexion[$h[0]]=$find_connexion[$h[0]]+1; if ($find_connexion[$h[0]]>$max) $max=$find_connexion[$h[0]]; } } } fclose( $fd ); if (isset($find_connexion)){ $stats.= '<CENTER><div id="chart" style="width: 700px; height: 500px"></div></CENTER>'; $stats.= '<script type="text/javascript"> $(function() { $("#chart").chart({ template: "line_speed_stat", tooltips: { serie1: ["'.implode('","',array_keys($find_connexion)).'"], }, values: { serie1: ['.implode(',',$find_connexion).'], }, defaultSeries: { fill: true, stacked: false, highlight: { scale: 2 }, startAnimation: { active: true, type: "grow", easing: "bounce" } } }); }); $.elycharts.templates[\'line_speed_stat\'] = { type: "line", margins: [10, 10, 20, 50], defaultSeries: { plotProps: { "stroke-width": 4 }, dot: true, dotProps: { stroke: "white", "stroke-width": 2 } }, series: { serie1: { color: "blue" }, }, defaultAxis: { labels: true }, features: { grid: { draw: [true, false], props: { "stroke-dasharray": "-" } }, legend: { horizontal: false, width: 80, height: 50, x: 220, y: 250, dotType: "circle", dotProps: { stroke: "white", "stroke-width": 2 }, borderProps: { opacity: 0.3, fill: "#c0c0c0", "stroke-width": 0 } } } }; </script>'; }else msg_warning($l->g(766)); } ?>
the-linux-schools-project/karoshi-server
serversetup/modules/ocsinventory/OCSNG_UNIX_SERVER/ocsreports/plugins/main_sections/ms_stats/ms_stats_connexion.php
PHP
agpl-3.0
2,929
// // // Description: This file is part of FET // // // Author: Lalescu Liviu <Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)> // Copyright (C) 2003 Liviu Lalescu <http://lalescu.ro/liviu/> // /*************************************************************************** * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include <QHash> #include <QList> #include <QMessageBox> #include <QPushButton> #include <QCheckBox> #include <QPlainTextEdit> #include <QLineEdit> #include <QHBoxLayout> #include <QVBoxLayout> #include "matrix.h" #include "spreadmindaysconstraintsfivedaysform.h" #include "longtextmessagebox.h" #include "timetable.h" #include <algorithm> using namespace std; extern Timetable gt; SpreadMinDaysConstraintsFiveDaysForm::SpreadMinDaysConstraintsFiveDaysForm(QWidget* parent): QDialog(parent) { setupUi(this); centerWidgetOnScreen(this); restoreFETDialogGeometry(this); okPushButton->setDefault(true); connect(okPushButton, SIGNAL(clicked()), this, SLOT(wasAccepted())); connect(cancelPushButton, SIGNAL(clicked()), this, SLOT(wasCanceled())); connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help())); spread2CheckBox->setChecked(false); spread3CheckBox->setChecked(false); } SpreadMinDaysConstraintsFiveDaysForm::~SpreadMinDaysConstraintsFiveDaysForm() { saveFETDialogGeometry(this); } void SpreadMinDaysConstraintsFiveDaysForm::wasAccepted() { double weight4; QString tmp=weight4LineEdit->text(); weight_sscanf(tmp, "%lf", &weight4); if(weight4<0.0 || weight4>100.0){ QMessageBox::warning(this, tr("FET information"), tr("Invalid weight (percentage) for all split activities - must be real number >=0.0 and <=100.0")); return; } double weight2; tmp=weight2LineEdit->text(); weight_sscanf(tmp, "%lf", &weight2); if(spread2CheckBox->isChecked() && (weight2<0.0 || weight2>100.0)){ QMessageBox::warning(this, tr("FET information"), tr("Invalid weight (percentage) for activities split into 2 components - must be real number >=0.0 and <=100.0")); return; } double weight3; tmp=weight3LineEdit->text(); weight_sscanf(tmp, "%lf", &weight3); if(spread3CheckBox->isChecked() && (weight3<0.0 || weight3>100.0)){ QMessageBox::warning(this, tr("FET information"), tr("Invalid weight (percentage) for activities split into 3 components - must be real number >=0.0 and <=100.0")); return; } bool spread2=spread2CheckBox->isChecked(); bool spread3=spread3CheckBox->isChecked(); bool spread4OrMore=spread4OrMoreCheckBox->isChecked(); if(!spread4OrMore){ QMessageBox::critical(this, tr("FET bug"), tr("You found a probable bug in FET - min 1 day should be selected automatically for " "all split activities. Please report error. FET will now abort current operation")); return; } assert(spread4OrMore); QHash<int, int> activitiesRepresentantIds; //first integer is the id, second is the index in the lists //QList<int> activitiesForRepresentant[MAX_ACTIVITIES]; Matrix1D<QList<int> > activitiesForRepresentant; activitiesForRepresentant.resize(gt.rules.activitiesList.count()); int nActs=0; foreach(Activity* act, gt.rules.activitiesList){ if(act->activityGroupId==0){ assert(!activitiesRepresentantIds.contains(act->id)); activitiesRepresentantIds.insert(act->id, nActs); activitiesForRepresentant[nActs].clear(); activitiesForRepresentant[nActs].append(act->id); nActs++; } else{ if(activitiesRepresentantIds.contains(act->activityGroupId)){ int k=activitiesRepresentantIds.value(act->activityGroupId); assert(!activitiesForRepresentant[k].contains(act->id)); activitiesForRepresentant[k].append(act->id); } else{ activitiesRepresentantIds.insert(act->activityGroupId, nActs); activitiesForRepresentant[nActs].clear(); activitiesForRepresentant[nActs].append(act->id); nActs++; } } } QHash<int, int> activityGroupIdHash; foreach(Activity* act, gt.rules.activitiesList) activityGroupIdHash.insert(act->id, act->activityGroupId); for(int i=0; i<nActs; i++){ //qSort(activitiesForRepresentant[i]); std::stable_sort(activitiesForRepresentant[i].begin(), activitiesForRepresentant[i].end()); int fid=activitiesForRepresentant[i].at(0); assert(activityGroupIdHash.contains(fid)); int gid=activityGroupIdHash.value(fid); if(gid>0){ assert(activitiesRepresentantIds.contains(gid)); assert(activitiesRepresentantIds.value(gid)==i); } else assert(activitiesForRepresentant[i].count()==1); } QList<ConstraintMinDaysBetweenActivities*> constraintsToBeRemoved; foreach(TimeConstraint* tc, gt.rules.timeConstraintsList){ if(tc->type==TimeConstraintType::CONSTRAINT_MIN_DAYS_BETWEEN_ACTIVITIES){ ConstraintMinDaysBetweenActivities* mdc=(ConstraintMinDaysBetweenActivities*) tc; //find representant int reprIndex=-1; bool toBeRemoved=true; for(int i=0; i<mdc->n_activities; i++){ if(!activityGroupIdHash.contains(mdc->activitiesId[i])){ QMessageBox::critical(this, tr("FET bug"), tr("You found a probable bug in FET - constraint %1\ncontains invalid activity id %2\n" "\nPlease report error. FET will now abort current operation").arg(mdc->getDetailedDescription(gt.rules)).arg(mdc->activitiesId[i])); return; } assert(activityGroupIdHash.contains(mdc->activitiesId[i])); if(reprIndex==-1) reprIndex=activityGroupIdHash.value(mdc->activitiesId[i]); else if(reprIndex!=activityGroupIdHash.value(mdc->activitiesId[i])){ toBeRemoved=false; break; } } if(reprIndex==0) toBeRemoved=false; if(toBeRemoved) constraintsToBeRemoved.append(mdc); } } bool consecutiveIfSameDay=consecutiveIfSameDayCheckBox->isChecked(); QList<ConstraintMinDaysBetweenActivities*> addedConstraints; for(int i=0; i<nActs; i++){ ConstraintMinDaysBetweenActivities* c1; ConstraintMinDaysBetweenActivities* c2; ConstraintMinDaysBetweenActivities* c3; c1=NULL; c2=NULL; c3=NULL; QList<int> cl=activitiesForRepresentant[i]; assert(cl.count()>=1); if(cl.count()>=2){ assert(spread4OrMore); int n_acts; QList<int> acts; //int acts[MAX_TimeConstraintType::CONSTRAINT_MIN_DAYS_BETWEEN_ACTIVITIES]; n_acts=cl.count(); acts.clear(); for(int k=0; k<cl.count(); k++){ //acts[k]=cl.at(k); acts.append(cl.at(k)); } c1=new ConstraintMinDaysBetweenActivities(weight4, consecutiveIfSameDay, n_acts, acts, 1); } if(cl.count()==3 && spread3){ int aloneComponent=-1, notAloneComp1=-1, notAloneComp2=-1; if(type123RadioButton->isChecked()){ aloneComponent=1; notAloneComp1=2; notAloneComp2=3; } else if(type213RadioButton->isChecked()){ aloneComponent=2; notAloneComp1=1; notAloneComp2=3; } else if(type312RadioButton->isChecked()){ aloneComponent=3; notAloneComp1=1; notAloneComp2=2; } else{ QMessageBox::information(this, tr("FET information"), tr("Please select the isolated component")); assert(c1!=NULL); delete c1; return; } aloneComponent--; notAloneComp1--; notAloneComp2--; int n_acts; //int acts[10]; QList<int> acts; n_acts=2; acts.clear(); //acts[0]=cl.at(aloneComponent); acts.append(cl.at(aloneComponent)); //acts[1]=cl.at(notAloneComp1); acts.append(cl.at(notAloneComp1)); c2=new ConstraintMinDaysBetweenActivities(weight3, consecutiveIfSameDay, n_acts, acts, 2); ////////// n_acts=2; acts.clear(); //acts[0]=cl.at(aloneComponent); acts.append(cl.at(aloneComponent)); //acts[1]=cl.at(notAloneComp2); acts.append(cl.at(notAloneComp2)); c3=new ConstraintMinDaysBetweenActivities(weight3, consecutiveIfSameDay, n_acts, acts, 2); } if(cl.count()==2 && spread2){ int n_acts; QList<int> acts; //int acts[10]; n_acts=2; acts.clear(); //acts[0]=cl.at(0); acts.append(cl.at(0)); //acts[1]=cl.at(1); acts.append(cl.at(1)); assert(c2==NULL); c2=new ConstraintMinDaysBetweenActivities(weight2, consecutiveIfSameDay, n_acts, acts, 2); } if(c1!=NULL) addedConstraints.append(c1); if(c2!=NULL) addedConstraints.append(c2); if(c3!=NULL) addedConstraints.append(c3); } /////////// QDialog dialog(this); dialog.setWindowTitle(tr("Last confirmation needed")); QVBoxLayout* top=new QVBoxLayout(&dialog); QLabel* topLabel=new QLabel(); topLabel->setText(tr("Operations that will be done:")); top->addWidget(topLabel); QPushButton* acceptPB=new QPushButton(tr("Accept")); QPushButton* cancelPB=new QPushButton(tr("Cancel")); QHBoxLayout* hl=new QHBoxLayout(); hl->addStretch(); hl->addWidget(acceptPB); hl->addWidget(cancelPB); QObject::connect(acceptPB, SIGNAL(clicked()), &dialog, SLOT(accept())); QObject::connect(cancelPB, SIGNAL(clicked()), &dialog, SLOT(reject())); QPlainTextEdit* removedText=new QPlainTextEdit(); QPlainTextEdit* addedText=new QPlainTextEdit(); QString s=tr("The following time constraints will be removed:"); s+="\n\n"; foreach(ConstraintMinDaysBetweenActivities* ctr, constraintsToBeRemoved){ s+=ctr->getDetailedDescription(gt.rules); s+="\n"; } removedText->setPlainText(s); removedText->setReadOnly(true); s=tr("The following time constraints will be added:"); s+="\n\n"; foreach(ConstraintMinDaysBetweenActivities* ctr, addedConstraints){ s+=ctr->getDetailedDescription(gt.rules); s+="\n"; } addedText->setPlainText(s); addedText->setReadOnly(true); top->addWidget(removedText); top->addWidget(addedText); top->addLayout(hl); //dialog.addLayout(top); const QString settingsName=QString("SpreadMinDaysBetweenActivitiesConstraintsLastConfirmationForm"); dialog.resize(600, 500); centerWidgetOnScreen(&dialog); restoreFETDialogGeometry(&dialog, settingsName); acceptPB->setFocus(); acceptPB->setDefault(true); setParentAndOtherThings(&dialog, this); int res=dialog.exec(); saveFETDialogGeometry(&dialog, settingsName); if(res==QDialog::Rejected){ constraintsToBeRemoved.clear(); foreach(ConstraintMinDaysBetweenActivities* ctr, addedConstraints){ delete ctr; } addedConstraints.clear(); return; } assert(res==QDialog::Accepted); //better QList<TimeConstraint*> removedList; foreach(ConstraintMinDaysBetweenActivities* mdc, constraintsToBeRemoved) removedList.append((TimeConstraint*)mdc); bool t=gt.rules.removeTimeConstraints(removedList); assert(t); removedList.clear(); constraintsToBeRemoved.clear(); /*foreach(ConstraintMinDaysBetweenActivities* mdc, constraintsToBeRemoved){ int t=gt.rules.timeConstraintsList.removeAll(mdc); assert(t==1); } gt.rules.internalStructureComputed=false; setRulesModifiedAndOtherThings(&gt.rules); foreach(ConstraintMinDaysBetweenActivities* mdc, constraintsToBeRemoved) delete mdc; constraintsToBeRemoved.clear();*/ foreach(ConstraintMinDaysBetweenActivities* tc, addedConstraints){ bool t=gt.rules.addTimeConstraint(tc); if(!t){ QMessageBox::critical(this, tr("FET bug"), tr("You found a probable bug in FET - trying to add constraint %1, " "but it is already existing. Please report error. FET will now continue operation").arg(tc->getDetailedDescription(gt.rules))); } } addedConstraints.clear(); QString s2=tr("Spreading of activities operation completed successfully"); s2+="\n\n"; s2+=tr("NOTE: If you are using constraints of type activities same starting time or activities same starting day, it is important" " (after current operation) to apply the operation of removing redundant constraints.") +" "+tr("Read Help/Important tips - tip 2) for details."); QMessageBox::information(this, tr("FET information"), s2); this->accept(); } void SpreadMinDaysConstraintsFiveDaysForm::wasCanceled() { this->reject(); } void SpreadMinDaysConstraintsFiveDaysForm::help() { QString s; s+=tr("Help on spreading the activities over the week:"); s+="\n\n"; s+=tr("How to choose the weights in this dialog:"); s+="\n\n"; s+=tr("Weights (percentages) of newly added constraints min days between activities - recommended between 95.0%-100.0% " "(maybe lower on those split into 3). Make weights 100.0% if the constraints need to be respected all the time." " It is recommended to enable the check boxes for activities split into 2 or 3 components (not to be in consecutive days), " "if your data is still possible to solve. You may use a progressive approach. Example of weights: 90.0%, 95.0%, 99.0%, 99.75%, 100.0%."); LongTextMessageBox::largeInformation(this, tr("FET help"), s); } void SpreadMinDaysConstraintsFiveDaysForm::on_spread2CheckBox_toggled() { weight2LineEdit->setEnabled(spread2CheckBox->isChecked()); weight2Label->setEnabled(spread2CheckBox->isChecked()); } void SpreadMinDaysConstraintsFiveDaysForm::on_spread3CheckBox_toggled() { weight3LineEdit->setEnabled(spread3CheckBox->isChecked()); weight3Label->setEnabled(spread3CheckBox->isChecked()); aloneGroupBox->setEnabled(spread3CheckBox->isChecked()); } void SpreadMinDaysConstraintsFiveDaysForm::on_spread4OrMoreCheckBox_toggled() { int k=spread4OrMoreCheckBox->isChecked(); if(!k){ spread4OrMoreCheckBox->setChecked(true); QMessageBox::information(this, tr("FET information"), tr("This box must remain checked, so that split activities" " are not in the same day (with the probability you write below)")); } }
janLo/FET
src/interface/spreadmindaysconstraintsfivedaysform.cpp
C++
agpl-3.0
14,004
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var Event = new Schema({ name: String, description: String, sport: String, place: { name: String, coords: { longitude: { type: Number }, latitude: { type: Number } }, address: {type: String, default: '', unique: true, trim: true}, landmarks: [{type: String, default: '', trim: true}], city : {type: String, default: '', trim: true}, }, when: Date, organizer: {type: Schema.ObjectId, ref: 'User'}, players: { 'yes': [{type: Schema.ObjectId, ref: 'User'}], 'no': [{type: Schema.ObjectId, ref: 'User'}], 'maybe': [{type: Schema.ObjectId, ref: 'User'}], 'none': [{type: Schema.ObjectId, ref: 'User'}] }, subscribers: [{type: Schema.ObjectId, ref: 'User'}], score: String, comments: [{ comment: String, commented_on: Date, by: {type: Schema.ObjectId, ref: 'User'} }], created_at: {type: Date, default: Date.now}, modified_at: {type: Date, default: Date.now} }); module.exports = mongoose.model('Event', Event);
asm-products/sportiz-backend
models/event.js
JavaScript
agpl-3.0
1,155
/* Places, Copyright 2014 Ansamb. This file is part of Places By Ansamb. Places By Ansamb is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Places By Ansamb 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 Affero GNU General Public License for more details. You should have received a copy of the Affero GNU General Public License along with Places By Ansamb. If not, see <http://www.gnu.org/licenses/>. */ module.exports = { up: function(migration, DataTypes, done) { migration.addColumn('places','request_id',{ type:DataTypes.STRING, allowNull:true, defaultValue:null }).success(function(res){ console.log("Migration to v0.0.4: Added request_id into table places",res); done() }); // add altering commands here, calling 'done' when finished }, down: function(migration, DataTypes, done) { // add reverting commands here, calling 'done' when finished done() } }
ansamb-places/places-application-runtime
core/migrations/application/20140402160700-migration-from-0.0.3-to-0.0.4.js
JavaScript
agpl-3.0
1,271
{{-- Copyright 2015-2017 ppy Pty. Ltd. This file is part of osu!web. osu!web is distributed with the hope of attracting more community contributions to the core ecosystem of osu!. osu!web is free software: you can redistribute it and/or modify it under the terms of the Affero GNU General Public License version 3 as published by the Free Software Foundation. osu!web is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with osu!web. If not, see <http://www.gnu.org/licenses/>. --}} {{-- <a class="btn-circle btn-circle--topic-entry" href="#" data-remote="1" data-method="POST" data-confirm="{{ trans('forum.topic_watches.topic_buttons.mark_read.confirmation') }}" title="{{ trans('forum.topic_watches.topic_buttons.mark_read.title') }}" > <i class="fas fa-check"></i> </a> --}} @php $watch = $topicWatchStatus[$topic->getKey()]; @endphp <button type="button" class="btn-circle btn-circle--topic-entry {{ $watch->mail ? 'btn-circle--activated' : '' }}" title="{{ trans('forum.topics.watch.'.($watch->mail ? 'mail_disable' : 'to_watching_mail')) }}" data-url="{{ route('forum.topic-watches.update', [ $topic, 'state' => $watch->mail ? 'watching' : 'watching_mail', 'return' => 'index' ]) }}" data-remote="1" data-reload-on-success="1" data-method="PUT" > <span class="btn-circle__content"> <i class="fas fa-envelope"></i> </span> </button> <button type="button" class="btn-circle btn-circle--topic-entry" title="{{ trans('forum.topic_watches.topic_buttons.remove.title') }}" data-url="{{ route('forum.topic-watches.update', [ $topic, 'state' => 'not_watching', 'return' => 'index' ]) }}" data-remote="1" data-reload-on-success="1" data-method="PUT" data-confirm="{{ trans('forum.topic_watches.topic_buttons.remove.confirmation') }}" > <span class="btn-circle__content"> <i class="fas fa-trash"></i> </span> </button>
kj415j45/osu-web
resources/views/forum/topic_watches/_topic_buttons.blade.php
PHP
agpl-3.0
2,261
/* Blackboard WebServices Serializable Objects Copyright (C) 2011-2013 Andrew Martin, Newcastle University This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package bbws.resource.gradecentre.column; //bbws import bbws.entity.enums.verbosity.BBLineitemVerbosity; //javax import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class BBLineitem { private String assessmentBbId; private String assessmentLocation; private Boolean available; private Integer columnPosition; private String dateAdded; private String dateChanged; private BBLineitemVerbosity verbosity; private String lineItemBbId; private String name; private String outcomeDefBbId; private Float pointsPossible; //private List<BBScore> scores; private String title; private String type; private Float weight; public BBLineitem(){} // public BBLineitem(Lineitem li,BBLineitemVerbosity verbosity) throws Exception // { // this.verbosity = verbosity; // // switch(this.verbosity) // { // case WithScores: // /*try // { // this.scores = bbws.util.factory.list.BBListFactory.getBBScoreListFromList(li.getScores(),bbws.gradecentre.grade.BBScore.BBScoreVerbosity.extended); // } // catch(Exception e) // { // this.scores = null; // }*/ // case WithoutScores: // Object o = li.getAssessmentId(); // if(o!=null) // { // this.assessmentBbId = o.getClass().getName(); // if(this.assessmentBbId.equalsIgnoreCase("java.lang.String")) // { // this.assessmentBbId = o.toString(); // } // else if(this.assessmentBbId.equalsIgnoreCase("blackboard.persist.Id")) // { // this.assessmentBbId = ((blackboard.persist.Id)o).getExternalString(); // } // } // if(li.getAssessmentLocation().equals(AssessmentLocation.EXTERNAL)){this.assessmentLocation = "EXTERNAL";} // else if(li.getAssessmentLocation().equals(AssessmentLocation.INTERNAL)){this.assessmentLocation = "INTERNAL";} // else if(li.getAssessmentLocation().equals(AssessmentLocation.UNSET)){this.assessmentLocation = "UNSET";} // this.available = li.getIsAvailable(); // this.columnPosition = li.getColumnOrder(); // this.dateAdded = getDateTimeFromCalendar(li.getDateAdded()); // this.dateChanged = getDateTimeFromCalendar(li.getDateChanged()); // this.lineItemBbId = li.getId().toExternalString(); // this.name = li.getName(); // this.outcomeDefBbId = li.getOutcomeDefinition().getId().toExternalString(); // this.pointsPossible = li.getPointsPossible(); // this.type = li.getType(); // this.weight = li.getWeight(); // return; // } // throw new Exception("Undefined verbosity of line item"); // } public String getAssessmentBbId() { return this.assessmentBbId; } public void setAssessmentBbId(String assessmentBbId) { this.assessmentBbId = assessmentBbId; } public String getAssessmentLocation() { return this.assessmentLocation; } public void setAssessmentLocation(String assessmentLocation) { this.assessmentLocation = assessmentLocation; } public Boolean getAvailable() { return this.available; } public void setAvailable(Boolean available) { this.available = available; } public Integer getColumnPosition() { return this.columnPosition; } public void setColumnPosition(Integer columnPosition) { this.columnPosition = columnPosition; } public String getDateAdded() { return this.dateAdded; } public void setDateAdded(String dateAdded) { this.dateAdded = dateAdded; } public String getDateChanged() { return this.dateChanged; } public void setDateChanged(String dateChanged) { this.dateChanged = dateChanged; } public String getLineItemBbId() { return this.lineItemBbId; } public void setLineItemBbId(String lineItemBbId) { this.lineItemBbId = lineItemBbId; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getOutcomeDefBbId() { return this.outcomeDefBbId; } public void setOutcomeDefBbId(String outcomeDefBbId) { this.outcomeDefBbId = outcomeDefBbId; } public Float getPointsPossible() { return this.pointsPossible; } public void setPointsPossible(Float pointsPossible) { this.pointsPossible = pointsPossible; } /*public List<BBScore> getScores() { return this.scores; } public void setScores(List<BBScore> scores) { this.scores = scores; }*/ public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public Float getWeight() { return this.weight; } public void setWeight(Float weight) { this.weight = weight; } }
andmar8/Blackboard-Java-WebservicesBBSerializableObjects
src/bbws/resource/gradecentre/column/BBLineitem.java
Java
agpl-3.0
6,229
<?php /** * @author Thomas Müller <thomas.mueller@tmit.eu> * * @copyright Copyright (c) 2018, ownCloud GmbH * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCA\DAV\Avatars; use OCP\IAvatar; use Sabre\DAV\File; class AvatarNode extends File { private $ext; private $size; private $avatar; /** * AvatarNode constructor. * * @param integer $size * @param string $ext * @param IAvatar $avatar */ public function __construct($size, $ext, $avatar) { $this->size = $size; $this->ext = $ext; $this->avatar = $avatar; } /** * Returns the name of the node. * * This is used to generate the url. * * @return string */ function getName() { return "$this->size.$this->ext"; } function get() { $image = $this->avatar->get($this->size); $res = $image->resource(); ob_start(); if ($this->ext === 'png') { imagepng($res); } else { imagejpeg($res); } return ob_get_clean(); } /** * Returns the mime-type for a file * * If null is returned, we'll assume application/octet-stream * * @return string|null */ function getContentType() { if ($this->ext === 'png') { return 'image/png'; } return 'image/jpeg'; } function getETag() { return $this->avatar->getFile($this->size)->getEtag(); } function getLastModified() { $timestamp = $this->avatar->getFile($this->size)->getMTime(); if (!empty($timestamp)) { return (int)$timestamp; } return $timestamp; } }
pollopolea/core
apps/dav/lib/Avatars/AvatarNode.php
PHP
agpl-3.0
2,058
/* * AceEditorPreview.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.prefs.views; import com.google.gwt.dom.client.*; import com.google.gwt.dom.client.Style.BorderStyle; import com.google.gwt.dom.client.Style.Unit; import org.rstudio.core.client.ExternalJavaScriptLoader; import org.rstudio.core.client.ExternalJavaScriptLoader.Callback; import org.rstudio.core.client.theme.ThemeFonts; import org.rstudio.core.client.widget.DynamicIFrame; import org.rstudio.core.client.widget.FontSizer; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceResources; public class AceEditorPreview extends DynamicIFrame { public AceEditorPreview(String code) { code_ = code; Style style = getStyleElement().getStyle(); style.setBorderColor("#CCC"); style.setBorderWidth(1, Unit.PX); style.setBorderStyle(BorderStyle.SOLID); } @Override protected void onFrameLoaded() { isFrameLoaded_ = true; if (initialThemeUrl_ != null) setTheme(initialThemeUrl_); if (initialFontSize_ != null) setFontSize(initialFontSize_); final Document doc = getDocument(); final BodyElement body = doc.getBody(); body.getStyle().setMargin(0, Unit.PX); body.getStyle().setBackgroundColor("white"); StyleElement style = doc.createStyleElement(); style.setType("text/css"); style.setInnerText( ".ace_editor {\n" + "border: none !important;\n" + "}"); setFont(ThemeFonts.getFixedWidthFont()); body.appendChild(style); DivElement div = doc.createDivElement(); div.setId("editor"); div.getStyle().setWidth(100, Unit.PCT); div.getStyle().setHeight(100, Unit.PCT); div.setInnerText(code_); body.appendChild(div); FontSizer.injectStylesIntoDocument(doc); FontSizer.applyNormalFontSize(div); new ExternalJavaScriptLoader(doc, AceResources.INSTANCE.acejs().getSafeUri().asString()) .addCallback(new Callback() { public void onLoaded() { new ExternalJavaScriptLoader(doc, AceResources.INSTANCE.acesupportjs().getSafeUri().asString()) .addCallback(new Callback() { public void onLoaded() { body.appendChild(doc.createScriptElement( "var editor = ace.edit('editor');\n" + "editor.renderer.setHScrollBarAlwaysVisible(false);\n" + "editor.renderer.setTheme({});\n" + "editor.setHighlightActiveLine(false);\n" + "editor.renderer.setShowGutter(false);\n" + "var RMode = require('mode/r').Mode;\n" + "editor.getSession().setMode(new RMode(false, editor.getSession().getDocument()));")); } }); } }); } public void setTheme(String themeUrl) { if (!isFrameLoaded_) { initialThemeUrl_ = themeUrl; return; } if (currentStyleLink_ != null) currentStyleLink_.removeFromParent(); Document doc = getDocument(); currentStyleLink_ = doc.createLinkElement(); currentStyleLink_.setRel("stylesheet"); currentStyleLink_.setType("text/css"); currentStyleLink_.setHref(themeUrl); doc.getBody().appendChild(currentStyleLink_); } public void setFontSize(double fontSize) { if (!isFrameLoaded_) { initialFontSize_ = fontSize; return; } FontSizer.setNormalFontSize(getDocument(), fontSize); } public void setFont(String font) { final String STYLE_EL_ID = "__rstudio_font_family"; Document document = getDocument(); Element oldStyle = document.getElementById(STYLE_EL_ID); StyleElement style = document.createStyleElement(); style.setAttribute("type", "text/css"); style.setInnerText(".ace_editor, .ace_text-layer {\n" + "font-family: " + font + " !important;\n" + "}"); document.getBody().appendChild(style); if (oldStyle != null) oldStyle.removeFromParent(); style.setId(STYLE_EL_ID); } private LinkElement currentStyleLink_; private boolean isFrameLoaded_; private String initialThemeUrl_; private Double initialFontSize_; private final String code_; }
Sage-Bionetworks/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/prefs/views/AceEditorPreview.java
Java
agpl-3.0
4,967
class RemoveWrongIndexTwo < ActiveRecord::Migration def up remove_index :frm_topics, :slug add_index :frm_topics, :slug add_index :frm_topics, [:forum_id,:slug], unique: true end def down remove_index :frm_topics, :slug remove_index :frm_topics, [:forum_id,:slug] add_index :frm_topics, :slug, :unique => true end end
xdite/Airesis
db/migrate/20130920140838_remove_wrong_index_two.rb
Ruby
agpl-3.0
351
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import os import arrow import magic import hashlib import logging import requests from io import BytesIO from PIL import Image from flask import json from .image import get_meta from .video import get_meta as video_meta import base64 from superdesk.errors import SuperdeskApiError logger = logging.getLogger(__name__) def hash_file(afile, hasher, blocksize=65536): buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return hasher.hexdigest() def get_file_name(file): return hash_file(file, hashlib.sha256()) def download_file_from_url(url): rv = requests.get(url, timeout=15) if rv.status_code not in (200, 201): raise SuperdeskApiError.internalError('Failed to retrieve file from URL: %s' % url) mime = magic.from_buffer(rv.content, mime=True).decode('UTF-8') ext = mime.split('/')[1] name = 'stub.' + ext return BytesIO(rv.content), name, mime def download_file_from_encoded_str(encoded_str): content = encoded_str.split(';base64,') mime = content[0].split(':')[1] ext = content[0].split('/')[1] name = 'web_capture.' + ext content = base64.b64decode(content[1]) return BytesIO(content), name, mime def process_file_from_stream(content, content_type=None): content_type = content_type or content.content_type content = BytesIO(content.read()) if 'application/' in content_type: content_type = magic.from_buffer(content.getvalue(), mime=True).decode('UTF-8') content.seek(0) file_type, ext = content_type.split('/') try: metadata = process_file(content, file_type) except OSError: # error from PIL when image is supposed to be an image but is not. raise SuperdeskApiError.internalError('Failed to process file') file_name = get_file_name(content) content.seek(0) metadata = encode_metadata(metadata) metadata.update({'length': json.dumps(len(content.getvalue()))}) return file_name, content_type, metadata def encode_metadata(metadata): return dict((k.lower(), json.dumps(v)) for k, v in metadata.items()) def decode_metadata(metadata): return dict((k.lower(), decode_val(v)) for k, v in metadata.items()) def decode_val(string_val): """Format dates that elastic will try to convert automatically.""" val = json.loads(string_val) try: arrow.get(val, 'YYYY-MM-DD') # test if it will get matched by elastic return str(arrow.get(val)) except (Exception): return val def process_file(content, type): if type == 'image': return process_image(content, type) if type in ('audio', 'video'): return process_video(content, type) return {} def process_video(content, type): content.seek(0) meta = video_meta(content) content.seek(0) return meta def process_image(content, type): content.seek(0) meta = get_meta(content) content.seek(0) return meta def crop_image(content, file_name, cropping_data): if cropping_data: file_ext = os.path.splitext(file_name)[1][1:] if file_ext in ('JPG', 'jpg'): file_ext = 'jpeg' logger.debug('Opened image from stream, going to crop it s') content.seek(0) img = Image.open(content) cropped = img.crop(cropping_data) logger.debug('Cropped image from stream, going to save it') try: out = BytesIO() cropped.save(out, file_ext) out.seek(0) return (True, out) except Exception as io: logger.exception(io) return (False, content)
vied12/superdesk
server/superdesk/media/media_operations.py
Python
agpl-3.0
3,953
<?php namespace PPP\Wikidata\ValueFormatters; use Doctrine\Common\Cache\ArrayCache; use Mediawiki\Api\MediawikiApi; use PPP\Wikidata\Cache\PerSiteLinkCache; use PPP\Wikidata\ValueFormatters\JsonLd\Entity\JsonLdEntityFormatter; use PPP\Wikidata\ValueFormatters\JsonLd\Entity\JsonLdItemFormatter; use PPP\Wikidata\ValueFormatters\JsonLd\JsonLdFormatterTestBase; use PPP\Wikidata\Wikipedia\MediawikiArticle; use PPP\Wikidata\Wikipedia\MediawikiArticleImage; use PPP\Wikidata\Wikipedia\MediawikiArticleProvider; use ValueFormatters\FormatterOptions; use ValueFormatters\ValueFormatter; use Wikibase\DataModel\Entity\Item; use Wikibase\DataModel\Entity\ItemId; use Wikibase\DataModel\SiteLink; use Wikibase\DataModel\SiteLinkList; /** * @covers PPP\Wikidata\ValueFormatters\ExtendedJsonLdItemFormatter * * @licence AGPLv3+ * @author Thomas Pellissier Tanon */ class ExtendedJsonLdItemFormatterTest extends JsonLdFormatterTestBase { /** * @see JsonLdFormatterTestBase::validProvider */ public function validProvider() { $item = new Item( new ItemId('Q42'), null, new SiteLinkList(array(new SiteLink('enwiki', 'Douglas Adams'))) ); return array( array( $item, (object) array( '@type' => 'Thing', '@id' => 'http://www.wikidata.org/entity/Q42', 'name' => 'Q42', 'potentialAction' => array( (object) array( '@type' => 'ViewAction', 'name' => array( (object) array('@value' => 'View on Wikidata', '@language' => 'en'), (object) array('@value' => 'Voir sur Wikidata', '@language' => 'fr') ), 'image' => '//upload.wikimedia.org/wikipedia/commons/f/ff/Wikidata-logo.svg', 'target' => '//www.wikidata.org/entity/Q42' ), (object) array( '@type' => 'ViewAction', 'name' => array( (object) array('@value' => 'View on Wikipedia', '@language' => 'en'), (object) array('@value' => 'Voir sur Wikipédia', '@language' => 'fr') ), 'image' => '//upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/64px-Wikipedia-logo-v2.svg.png', 'target' => 'http://en.wikipedia.org/wiki/Douglas_Adams' ) ), 'image' => (object) array( '@type' => 'ImageObject', '@id' => 'http://commons.wikimedia.org/wiki/Image:Douglas_adams_portrait_cropped.jpg', 'contentUrl' => '//upload.wikimedia.org/wikipedia/commons/c/c0/Douglas_adams_portrait_cropped.jpg', 'name' => 'Douglas adams portrait cropped.jpg', 'width' => 100, 'height' => 200 ), '@reverse' => (object) array( 'about'=> (object) array( '@type' => 'Article', '@id'=> 'http://en.wikipedia.org/wiki/Douglas_Adams', 'inLanguage'=> 'en', 'headline'=> 'Fooo barr baz gaaaaaaa...', 'author'=> (object) array( '@type'=> 'Organization', '@id' => 'http://www.wikidata.org/entity/Q52', 'name' => 'Wikipedia' ), 'license'=> 'http://creativecommons.org/licenses/by-sa/3.0/' ) ) ), new FormatterOptions(array( JsonLdEntityFormatter::OPT_ENTITY_BASE_URI => 'http://www.wikidata.org/entity/', ValueFormatter::OPT_LANG => 'en' )) ), array( $item, (object) array( '@type' => 'Thing', '@id' => 'http://www.wikidata.org/entity/Q42', 'name' => 'Q42', 'potentialAction' => array( (object) array( '@type' => 'ViewAction', 'name' => array( (object) array('@value' => 'View on Wikidata', '@language' => 'en'), (object) array('@value' => 'Voir sur Wikidata', '@language' => 'fr') ), 'image' => '//upload.wikimedia.org/wikipedia/commons/f/ff/Wikidata-logo.svg', 'target' => '//www.wikidata.org/entity/Q42' ) ) ), new FormatterOptions(array( JsonLdEntityFormatter::OPT_ENTITY_BASE_URI => 'http://www.wikidata.org/entity/', ValueFormatter::OPT_LANG => 'ru' )) ) ); } /** * @see JsonLdFormatterTestBase::getInstance */ protected function getInstance(FormatterOptions $options = null) { $articleHeaderCache = new PerSiteLinkCache(new ArrayCache(), 'wphead'); $articleHeaderCache->save(new MediawikiArticle( new SiteLink('enwiki', 'Douglas Adams'), 'Fooo barr baz gaaaaaaa...', 'en', 'http://en.wikipedia.org/wiki/Douglas_Adams', new MediawikiArticleImage( '//upload.wikimedia.org/wikipedia/commons/c/c0/Douglas_adams_portrait_cropped.jpg', 100, 200, 'Douglas adams portrait cropped.jpg' ) )); return new ExtendedJsonLdItemFormatter( new JsonLdItemFormatter(new JsonLdEntityFormatter($options), $options), new MediawikiArticleProvider( array( 'enwiki' => new MediawikiApi('http://example.org') ), $articleHeaderCache ), $options ); } }
ProjetPP/PPP-Wikidata
tests/phpunit/ValueFormatters/ExtendedJsonLdItemFormatterTest.php
PHP
agpl-3.0
4,803
/*! jQuery UI - v1.10.3 - 2014-01-12 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.accordion.js, jquery.ui.progressbar.js, jquery.ui.slider.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.10.3", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent; }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.support.selectstart = "onselectstart" in document.createElement( "div" ); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); } }); $.extend( $.ui, { // $.ui.plugin is deprecated. Use $.widget() extensions instead. plugin: { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args ) { var i, set = instance.plugins[ name ]; if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }, // only used by resizable hasScroll: function( el, a ) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; } }); })( jQuery ); (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })( jQuery ); (function( $, undefined ) { var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); $.widget("ui.mouse", { version: "1.10.3", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown."+this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click."+this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("."+this.widgetName); if ( this._mouseMoveDelegate ) { $(document) .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if( mouseHandled ) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; $(document) .bind("mousemove."+this.widgetName, this._mouseMoveDelegate) .bind("mouseup."+this.widgetName, this._mouseUpDelegate); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); })(jQuery); (function( $, undefined ) { $.ui = $.ui || {}; var cachedScrollbarWidth, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[0]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ); return { element: withinElement, isWindow: isWindow, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[0].preventDefault ) { // force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !$.support.offsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem : elem }); } }); if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function () { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); }( jQuery ) ); (function( $, undefined ) { var uid = 0, hideProps = {}, showProps = {}; hideProps.height = hideProps.paddingTop = hideProps.paddingBottom = hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide"; showProps.height = showProps.paddingTop = showProps.paddingBottom = showProps.borderTopWidth = showProps.borderBottomWidth = "show"; $.widget( "ui.accordion", { version: "1.10.3", options: { active: 0, animate: {}, collapsible: false, event: "click", header: "> li > :first-child,> :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // callbacks activate: null, beforeActivate: null }, _create: function() { var options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ) // ARIA .attr( "role", "tablist" ); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } this._processPanels(); // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this._refresh(); }, _getCreateEventData: function() { return { header: this.active, panel: !this.active.length ? $() : this.active.next(), content: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icons = this.options.icons; if ( icons ) { $( "<span>" ) .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) .prependTo( this.headers ); this.active.children( ".ui-accordion-header-icon" ) .removeClass( icons.header ) .addClass( icons.activeHeader ); this.headers.addClass( "ui-accordion-icons" ); } }, _destroyIcons: function() { this.headers .removeClass( "ui-accordion-icons" ) .children( ".ui-accordion-header-icon" ) .remove(); }, _destroy: function() { var contents; // clean up main element this.element .removeClass( "ui-accordion ui-widget ui-helper-reset" ) .removeAttr( "role" ); // clean up headers this.headers .removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) .removeAttr( "role" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-controls" ) .removeAttr( "tabIndex" ) .each(function() { if ( /^ui-accordion/.test( this.id ) ) { this.removeAttribute( "id" ); } }); this._destroyIcons(); // clean up content panels contents = this.headers.next() .css( "display", "" ) .removeAttr( "role" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-labelledby" ) .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" ) .each(function() { if ( /^ui-accordion/.test( this.id ) ) { this.removeAttribute( "id" ); } }); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } // #5332 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels if ( key === "disabled" ) { this.headers.add( this.headers.next() ) .toggleClass( "ui-state-disabled", !!value ); } }, _keydown: function( event ) { /*jshint maxcomplexity:15*/ if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); toFocus.focus(); event.preventDefault(); } }, _panelKeyDown : function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().focus(); } }, refresh: function() { var options = this.options; this._processPanels(); // was collapsed or no panel if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { options.active = false; this.active = $(); // active false only when collapsible is true } else if ( options.active === false ) { this._activate( 0 ); // was active, but active panel is gone } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { // all remaining panel are disabled if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) { options.active = false; this.active = $(); // activate previous panel } else { this._activate( Math.max( 0, options.active - 1 ) ); } // was active, active panel still exists } else { // make sure active index is correct options.active = this.headers.index( this.active ); } this._destroyIcons(); this._refresh(); }, _processPanels: function() { this.headers = this.element.find( this.options.header ) .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" ); this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .filter(":not(.ui-accordion-content-active)") .hide(); }, _refresh: function() { var maxHeight, options = this.options, heightStyle = options.heightStyle, parent = this.element.parent(), accordionId = this.accordionId = "ui-accordion-" + (this.element.attr( "id" ) || ++uid); this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ) .removeClass( "ui-corner-all" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this.headers .attr( "role", "tab" ) .each(function( i ) { var header = $( this ), headerId = header.attr( "id" ), panel = header.next(), panelId = panel.attr( "id" ); if ( !headerId ) { headerId = accordionId + "-header-" + i; header.attr( "id", headerId ); } if ( !panelId ) { panelId = accordionId + "-panel-" + i; panel.attr( "id", panelId ); } header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); }) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr({ "aria-selected": "false", tabIndex: -1 }) .next() .attr({ "aria-expanded": "false", "aria-hidden": "true" }) .hide(); // make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr({ "aria-selected": "true", tabIndex: 0 }) .next() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } this._createIcons(); this._setupEvents( options.event ); if ( heightStyle === "fill" ) { maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.headers.each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.headers.next() .each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each(function() { maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); }) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler({ target: active, currentTarget: active, preventDefault: $.noop }); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = { keydown: "_keydown" }; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.headers.add( this.headers.next() ) ); this._on( this.headers, events ); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._hoverable( this.headers ); this._focusable( this.headers ); }, _eventHandler: function( event ) { var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // when the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // switch classes // corner classes on the previously active header stay after the animation active.removeClass( "ui-accordion-header-active ui-state-active" ); if ( options.icons ) { active.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.activeHeader ) .addClass( options.icons.header ); } if ( !clickedIsActive ) { clicked .removeClass( "ui-corner-all" ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); if ( options.icons ) { clicked.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.header ) .addClass( options.icons.activeHeader ); } clicked .next() .addClass( "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); toHide.prev().attr( "aria-selected", "false" ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.headers.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow .attr({ "aria-expanded": "true", "aria-hidden": "false" }) .prev() .attr({ "aria-selected": "true", tabIndex: 0 }); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } }); toShow .hide() .animate( showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { adjust += fx.now; } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } }); }, _toggleComplete: function( data ) { var toHide = data.oldPanel; toHide .removeClass( "ui-accordion-content-active" ) .prev() .removeClass( "ui-corner-top" ) .addClass( "ui-corner-all" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[0].className = toHide.parent()[0].className; } this._trigger( "activate", null, data ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "ui.progressbar", { version: "1.10.3", options: { max: 100, value: 0, change: null, complete: null }, min: 0, _create: function() { // Constrain initial value this.oldValue = this.options.value = this._constrainedValue(); this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ // Only set static values, aria-valuenow and aria-valuemax are // set inside _refreshValue() role: "progressbar", "aria-valuemin": this.min }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this._refreshValue(); }, _destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); }, value: function( newValue ) { if ( newValue === undefined ) { return this.options.value; } this.options.value = this._constrainedValue( newValue ); this._refreshValue(); }, _constrainedValue: function( newValue ) { if ( newValue === undefined ) { newValue = this.options.value; } this.indeterminate = newValue === false; // sanitize value if ( typeof newValue !== "number" ) { newValue = 0; } return this.indeterminate ? false : Math.min( this.options.max, Math.max( this.min, newValue ) ); }, _setOptions: function( options ) { // Ensure "value" option is set after other values (like max) var value = options.value; delete options.value; this._super( options ); this.options.value = this._constrainedValue( value ); this._refreshValue(); }, _setOption: function( key, value ) { if ( key === "max" ) { // Don't allow a max less than min value = Math.max( this.min, value ); } this._super( key, value ); }, _percentage: function() { return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min ); }, _refreshValue: function() { var value = this.options.value, percentage = this._percentage(); this.valueDiv .toggle( this.indeterminate || value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate ); if ( this.indeterminate ) { this.element.removeAttr( "aria-valuenow" ); if ( !this.overlayDiv ) { this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv ); } } else { this.element.attr({ "aria-valuemax": this.options.max, "aria-valuenow": value }); if ( this.overlayDiv ) { this.overlayDiv.remove(); this.overlayDiv = null; } } if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } if ( value === this.options.max ) { this._trigger( "complete" ); } } }); })( jQuery ); (function( $, undefined ) { // number of pages in a slider // (how many times can you page up/down to go through the whole range) var numPages = 5; $.widget( "ui.slider", $.ui.mouse, { version: "1.10.3", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null, // callbacks change: null, slide: null, start: null, stop: null }, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this._refresh(); this._setOption( "disabled", this.options.disabled ); this._animateOff = false; }, _refresh: function() { this._createRange(); this._createHandles(); this._setupEvents(); this._refreshValue(); }, _createHandles: function() { var i, handleCount, options = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", handles = []; handleCount = ( options.values && options.values.length ) || 1; if ( existingHandles.length > handleCount ) { existingHandles.slice( handleCount ).remove(); existingHandles = existingHandles.slice( 0, handleCount ); } for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); }, _createRange: function() { var options = this.options, classes = ""; if ( options.range ) { if ( options.range === true ) { if ( !options.values ) { options.values = [ this._valueMin(), this._valueMin() ]; } else if ( options.values.length && options.values.length !== 2 ) { options.values = [ options.values[0], options.values[0] ]; } else if ( $.isArray( options.values ) ) { options.values = options.values.slice(0); } } if ( !this.range || !this.range.length ) { this.range = $( "<div></div>" ) .appendTo( this.element ); classes = "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header ui-corner-all"; } else { this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) // Handle range switching from true to min/max .css({ "left": "", "bottom": "" }); } this.range.addClass( classes + ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); } else { this.range = $([]); } }, _setupEvents: function() { var elements = this.handles.add( this.range ).filter( "a" ); this._off( elements ); this._on( elements, this._handleEvents ); this._hoverable( elements ); this._focusable( elements ); }, _destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if (( distance > thisDistance ) || ( distance === thisDistance && (i === that._lastChangedValue || that.values(i) === o.min ))) { distance = thisDistance; closestHandle = $( this ); index = i; } }); allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal, true ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } //store the last changed value index for reference when handles overlap this._lastChangedValue = index; this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( key === "range" && this.options.range === true ) { if ( value === "min" ) { this.options.value = this._values( 0 ); this.options.values = null; } else if ( value === "max" ) { this.options.value = this._values( this.options.values.length-1 ); this.options.values = null; } } if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "min": case "max": this._animateOff = true; this._refreshValue(); this._animateOff = false; break; case "range": this._animateOff = true; this._refresh(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else if ( this.options.values && this.options.values.length ) { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } else { return []; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } }, _handleEvents: { keydown: function( event ) { /*jshint maxcomplexity:25*/ var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, click: function( event ) { event.preventDefault(); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).removeClass( "ui-state-active" ); } } } }); }(jQuery));
nccgroup/typofinder
TypoMagic/js/jquery-ui-1.10.3.custom.js
JavaScript
agpl-3.0
78,447
/* * matrix-appservice-email - Matrix Bridge to E-mail * Copyright (C) 2017 Kamax Sarl * * https://www.kamax.io/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.kamax.matrix.bridge.email.controller; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.kamax.matrix.MatrixErrorInfo; import io.kamax.matrix.bridge.email.exception.*; import io.kamax.matrix.bridge.email.model.matrix.MatrixTransactionPush; import io.kamax.matrix.bridge.email.model.matrix.RoomQuery; import io.kamax.matrix.bridge.email.model.matrix.UserQuery; import io.kamax.matrix.bridge.email.model.matrix._MatrixApplicationService; import io.kamax.matrix.event._MatrixEvent; import io.kamax.matrix.json.MatrixJsonEventFactory; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.PUT; @RestController public class ApplicationServiceController { private Logger log = LoggerFactory.getLogger(ApplicationServiceController.class); @Autowired private _MatrixApplicationService as; private JsonParser jsonParser = new JsonParser(); @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ExceptionHandler({InvalidMatrixIdException.class, InvalidBodyContentException.class}) @ResponseBody MatrixErrorInfo handleBadRequest(HttpServletRequest request, MatrixException e) { log.error("Error when processing {} {}", request.getMethod(), request.getServletPath(), e); return new MatrixErrorInfo(e.getErrorCode()); } @ResponseStatus(value = HttpStatus.UNAUTHORIZED) @ExceptionHandler(NoHomeserverTokenException.class) @ResponseBody MatrixErrorInfo handleUnauthorized(MatrixException e) { return new MatrixErrorInfo(e.getErrorCode()); } @ResponseStatus(value = HttpStatus.FORBIDDEN) @ExceptionHandler(InvalidHomeserverTokenException.class) @ResponseBody MatrixErrorInfo handleForbidden(MatrixException e) { return new MatrixErrorInfo(e.getErrorCode()); } @ResponseStatus(value = HttpStatus.NOT_FOUND) @ExceptionHandler({RoomNotFoundException.class, UserNotFoundException.class}) @ResponseBody MatrixErrorInfo handleNotFound(MatrixException e) { return new MatrixErrorInfo(e.getErrorCode()); } @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Throwable.class) @ResponseBody MatrixErrorInfo handleGeneric(HttpServletRequest request, Throwable t) { log.error("Error when processing {} {}", request.getMethod(), request.getServletPath(), t); return new MatrixErrorInfo(t); } @RequestMapping(value = "/rooms/{roomAlias:.+}", method = GET) public Object getRoom( @RequestParam(name = "access_token", required = false) String accessToken, @PathVariable String roomAlias) { log.info("Room {} was requested by HS", roomAlias); as.queryRoom(new RoomQuery(roomAlias, accessToken)); return EmptyJsonResponse.get(); } @RequestMapping(value = "/users/{mxId:.+}", method = GET) public Object getUser( @RequestParam(name = "access_token", required = false) String accessToken, @PathVariable String mxId) { log.info("User {} was requested by HS", mxId); as.queryUser(new UserQuery(as.getId(mxId), accessToken)); return EmptyJsonResponse.get(); } @RequestMapping(value = "/transactions/{txnId:.+}", method = PUT) public Object getTransaction( HttpServletRequest request, @RequestParam(name = "access_token", required = false) String accessToken, @PathVariable String txnId) throws IOException { log.info("Processing {}", request.getServletPath()); String json = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding()); try { JsonObject rootObj = jsonParser.parse(json).getAsJsonObject(); JsonArray eventsJson = rootObj.get("events").getAsJsonArray(); List<_MatrixEvent> events = new ArrayList<>(); for (JsonElement event : eventsJson) { events.add(MatrixJsonEventFactory.get(event.getAsJsonObject())); } MatrixTransactionPush transaction = new MatrixTransactionPush(); transaction.setCredentials(accessToken); transaction.setId(txnId); transaction.setEvents(events); as.push(transaction); return EmptyJsonResponse.get(); } catch (IllegalStateException e) { throw new InvalidBodyContentException(e); } } }
kamax-io/matrix-appservice-email
src/main/java/io/kamax/matrix/bridge/email/controller/ApplicationServiceController.java
Java
agpl-3.0
5,750
/* * RapidMiner * * Copyright (C) 2001-2011 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.test; import com.rapidminer.tools.LogService; import junit.framework.AssertionFailedError; import junit.framework.TestCase; /** * Extends the JUnit test case by a method for asserting equality of doubles * with respect to Double.NaN * * @author Simon Fischer */ public class RapidMinerTestCase extends TestCase { public RapidMinerTestCase() { super(); } public RapidMinerTestCase(String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); LogService.getGlobal().setVerbosityLevel(LogService.WARNING); } public void assertEqualsNaN(String message, double expected, double actual) { if (Double.isNaN(expected)) { if (!Double.isNaN(actual)) { throw new AssertionFailedError(message + " expected: <" + expected + "> but was: <" + actual + ">"); } } else { assertEquals(message, expected, actual, 0.000000001); } } }
aborg0/rapidminer-vega
src/com/rapidminer/test/RapidMinerTestCase.java
Java
agpl-3.0
1,838
package query import ( "Yearning-go/src/handler/commom" "Yearning-go/src/lib" "Yearning-go/src/model" "github.com/cookieY/yee" "net/http" "time" ) func FetchQueryRecord(c yee.Context) (err error) { u := new(commom.PageInfo) if err = c.Bind(u); err != nil { c.Logger().Error(err.Error()) return } order := u.GetSQLQueryList( commom.AccordingToQueryPer(), commom.AccordingToWorkId(u.Find.Text), commom.AccordingToDate(u.Find.Picker), ) return c.JSON(http.StatusOK, commom.SuccessPayload(order)) } func FetchQueryOrder(c yee.Context) (err error) { u := new(commom.PageInfo) if err = c.Bind(u); err != nil { c.Logger().Error(err.Error()) return } user, _ := lib.JwtParse(c) order := u.GetSQLQueryList( commom.AccordingToUsername(u.Find.Text), commom.AccordingToAssigned(user), commom.AccordingToDate(u.Find.Picker), commom.AccordingToAllQueryOrderState(u.Find.Status), ) return c.JSON(http.StatusOK, commom.SuccessPayload(order)) } func FetchQueryRecordProfile(c yee.Context) (err error) { u := new(commom.ExecuteStr) if err = c.Bind(u); err != nil { c.Logger().Error(err.Error()) return } start, end := lib.Paging(u.Page, 20) var detail []model.CoreQueryRecord var count int model.DB().Model(&model.CoreQueryRecord{}).Where("work_id =?", u.WorkId).Count(&count).Offset(start).Limit(end).Find(&detail) return c.JSON(http.StatusOK, commom.SuccessPayload(commom.CommonList{Data: detail, Page: count})) } func QueryDeleteEmptyRecord(c yee.Context) (err error) { var j []model.CoreQueryOrder model.DB().Select("work_id").Where(`query_per =?`, 3).Find(&j) for _, i := range j { var k model.CoreQueryRecord if model.DB().Where("work_id =?", i.WorkId).First(&k).RecordNotFound() { model.DB().Where("work_id =?", i.WorkId).Delete(&model.CoreQueryOrder{}) } } return c.JSON(http.StatusOK, commom.SuccessPayLoadToMessage(commom.ORDER_IS_CLEAR)) } func QueryHandlerSets(c yee.Context) (err error) { u := new(commom.QueryOrder) var s model.CoreQueryOrder if err = c.Bind(u); err != nil { c.Logger().Error(err.Error()) return c.JSON(http.StatusOK, err.Error()) } found := !model.DB().Where("work_id=? AND query_per=?", u.WorkId, 2).First(&s).RecordNotFound() switch u.Tp { case "agreed": if found { model.DB().Model(model.CoreQueryOrder{}).Where("work_id =?", u.WorkId).Update(map[string]interface{}{"query_per": 1, "ex_date": time.Now().Format("2006-01-02 15:04")}) lib.MessagePush(u.WorkId, 8, "") } return c.JSON(http.StatusOK, commom.SuccessPayLoadToMessage(commom.ORDER_IS_AGREE)) case "reject": if found { model.DB().Model(model.CoreQueryOrder{}).Where("work_id =?", u.WorkId).Update(map[string]interface{}{"query_per": 0}) lib.MessagePush(u.WorkId, 9, "") } return c.JSON(http.StatusOK, commom.SuccessPayLoadToMessage(commom.ORDER_IS_REJECT)) case "stop": model.DB().Model(model.CoreQueryOrder{}).Where("work_id =?", u.WorkId).Update(map[string]interface{}{"query_per": 3}) return c.JSON(http.StatusOK, commom.SuccessPayLoadToMessage(commom.ORDER_IS_ALL_END)) case "cancel": model.DB().Model(model.CoreQueryOrder{}).Updates(&model.CoreQueryOrder{QueryPer: 3}) return c.JSON(http.StatusOK, commom.SuccessPayLoadToMessage(commom.ORDER_IS_ALL_CANCEL)) default: return } } func AuditOrRecordQueryOrderFetchApis(c yee.Context) (err error) { switch c.Params("tp") { case "list": return FetchQueryOrder(c) case "record": return FetchQueryRecord(c) case "profile": return FetchQueryRecordProfile(c) default: return c.JSON(http.StatusOK, commom.ERR_REQ_FAKE) } }
cookieY/Yearning
src/handler/order/query/query.go
GO
agpl-3.0
3,583
// 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/>. CKEDITOR.plugins.setLang('GeSHi', 'en', { langGeSHi : { title: 'GeSHi', label: 'Post syntax highlighted code', langLbl: 'Select language' } });
aarkerio/Centauro
webroot/js/ckeditor/plugins/GeSHi/lang/en.js
JavaScript
agpl-3.0
818
'use strict'; import Flickity from 'flickity-imagesloaded' export default function LessonHeader() { console.log("-- LessonHeader initialized") let photosSelector = '.LessonHeader__photos' let $photos = $(photosSelector) if ($photos.length > 0) { let photoSelector = '.LessonHeader__photo' let $status = $('.LessonHeader__photos__status') let $current = $status.find('.current') let $total = $status.find('.total') // Init flickity for all carousels let flkty = new Flickity(photosSelector, { cellAlign: 'left', cellSelector: photoSelector, contain: true, pageDots: false, prevNextButtons: false, wrapAround: true, imagesLoaded: true, percentPosition: false, }) document.addEventListener("turbolinks:request-start", function() { flkty.destroy() }) $total.html($(photoSelector).length) flkty.on( 'select', function() { $current.html(flkty.selectedIndex + 1) }) return flkty } }
fablabbcn/SCOPESdf
assets/javascripts/components/LessonHeader.js
JavaScript
agpl-3.0
973
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.tem.document.web.struts; import static org.apache.commons.lang.StringUtils.isBlank; import static org.kuali.kfs.module.tem.TemConstants.CLOSE_TA_QUESTION; import static org.kuali.kfs.module.tem.TemConstants.CONFIRM_CLOSE_QUESTION; import static org.kuali.kfs.module.tem.TemConstants.CONFIRM_CLOSE_QUESTION_TEXT; import static org.kuali.kfs.sys.KFSConstants.BLANK_SPACE; import static org.kuali.kfs.sys.KFSConstants.MAPPING_BASIC; import static org.kuali.kfs.sys.KFSConstants.NOTE_TEXT_PROPERTY_NAME; import org.kuali.kfs.module.tem.TemConstants.TravelDocTypes; import org.kuali.kfs.module.tem.document.TravelAuthorizationCloseDocument; import org.kuali.kfs.module.tem.document.TravelAuthorizationDocument; import org.kuali.kfs.module.tem.document.TravelDocument; import org.kuali.kfs.module.tem.document.service.TravelAuthorizationService; import org.kuali.kfs.module.tem.util.MessageUtils; import org.kuali.rice.krad.bo.Note; import org.kuali.rice.krad.exception.ValidationException; import org.kuali.rice.krad.service.DataDictionaryService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; /** * */ public class CloseQuestionHandler implements QuestionHandler<TravelDocument> { private DataDictionaryService dataDictionaryService; private TravelAuthorizationService travelAuthorizationService; @Override public <T> T handleResponse(final Inquisitive<TravelDocument,?> asker) throws Exception { if (asker.denied(CLOSE_TA_QUESTION)) { return (T) asker.back(); } else if (asker.confirmed(CONFIRM_CLOSE_QUESTION)) { return (T) asker.end(); // This is the case when the user clicks on "OK" in the end. // After we inform the user that the close has been rerouted, we'll redirect to the portal page. } TravelAuthorizationDocument document = (TravelAuthorizationDocument)asker.getDocument(); try { // Below used as a place holder to allow code to specify actionForward to return if not a 'success question' T returnActionForward = (T) ((StrutsInquisitor) asker).getMapping().findForward(MAPPING_BASIC); TravelAuthorizationForm form = (TravelAuthorizationForm) ((StrutsInquisitor) asker).getForm(); TravelAuthorizationCloseDocument tacDocument = travelAuthorizationService.closeAuthorization(document, form.getAnnotation(), GlobalVariables.getUserSession().getPrincipalName(), null); form.setDocTypeName(TravelDocTypes.TRAVEL_AUTHORIZATION_CLOSE_DOCUMENT); form.setDocument(tacDocument); if (ObjectUtils.isNotNull(returnActionForward)) { return returnActionForward; } else { return (T) asker.confirm(CLOSE_TA_QUESTION, MessageUtils.getMessage(CONFIRM_CLOSE_QUESTION_TEXT), true, "Could not get reimbursement total for travel id ", tacDocument.getTravelDocumentIdentifier().toString(),"",""); } } catch (ValidationException ve) { throw ve; } } /** * @see org.kuali.kfs.module.tem.document.web.struts.QuestionHandler#askQuestion(org.kuali.kfs.module.tem.document.web.struts.Inquisitive) */ @Override public <T> T askQuestion(final Inquisitive<TravelDocument,?> asker) throws Exception { T retval = (T) asker.confirm(CLOSE_TA_QUESTION, CONFIRM_CLOSE_QUESTION_TEXT, false); return retval; } /** * * @param notePrefix * @param reason * @return */ public String getReturnToFiscalOfficerNote(final String notePrefix, String reason) { String noteText = ""; // Have to check length on value entered. final String introNoteMessage = notePrefix + BLANK_SPACE; // Build out full message. noteText = introNoteMessage + reason; final int noteTextLength = noteText.length(); // Get note text max length from DD. final int noteTextMaxLength = dataDictionaryService.getAttributeMaxLength(Note.class, NOTE_TEXT_PROPERTY_NAME).intValue(); if (isBlank(reason) || (noteTextLength > noteTextMaxLength)) { // Figure out exact number of characters that the user can enter. int reasonLimit = noteTextMaxLength - noteTextLength; if (ObjectUtils.isNull(reason)) { // Prevent a NPE by setting the reason to a blank string. reason = ""; } } return noteText; } public void setDataDictionaryService(final DataDictionaryService dataDictionaryService) { this.dataDictionaryService = dataDictionaryService; } public void setTravelAuthorizationService(TravelAuthorizationService travelAuthorizationService) { this.travelAuthorizationService = travelAuthorizationService; } }
ua-eas/ua-kfs-5.3
work/src/org/kuali/kfs/module/tem/document/web/struts/CloseQuestionHandler.java
Java
agpl-3.0
5,866
/* JDBCAddressDAO.java * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Copyright Ⓒ 2014-2015 Universiteit Gent * * This file is part of the Degage Web Application * * Corresponding author (see also AUTHORS.txt) * * Kris Coolsaet * Department of Applied Mathematics, Computer Science and Statistics * Ghent University * Krijgslaan 281-S9 * B-9000 GENT Belgium * * The Degage Web Application is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Degage Web Application 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with the Degage Web Application (file LICENSE.txt in the * distribution). If not, see <http://www.gnu.org/licenses/>. */ package be.ugent.degage.db.jdbc; import be.ugent.degage.db.DataAccessException; import be.ugent.degage.db.dao.AddressDAO; import be.ugent.degage.db.models.Address; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * JDBC implementation of {@link AddressDAO} */ class JDBCAddressDAO extends AbstractDAO implements AddressDAO { public JDBCAddressDAO(JDBCDataAccessContext context){ super (context); } // TODO: avoid these static Address populateAddress(ResultSet rs) throws SQLException { if(rs.getObject("address_id") == null) return null; else return new Address( rs.getInt("address_id"), rs.getString("address_country"), rs.getString("address_zipcode"), rs.getString("address_city"), rs.getString("address_street"), rs.getString("address_number"), rs.getFloat("address_latitude"), rs.getFloat("address_longitude") ); } // TODO: avoid these static Address populateAddress(ResultSet rs, String tableName) throws SQLException { if(rs.getObject(tableName + ".address_id") == null) return null; else return new Address( rs.getInt(tableName + ".address_id"), rs.getString(tableName + ".address_country"), rs.getString(tableName + ".address_zipcode"), rs.getString(tableName + ".address_city"), rs.getString(tableName + ".address_street"), rs.getString(tableName + ".address_number"), rs.getFloat(tableName + ".address_latitude"), rs.getFloat(tableName + ".address_longitude") ); } public static final String ADDRESS_FIELDS = "address_id, address_city, address_zipcode, address_street, address_number, address_country, address_latitude, address_longitude "; private LazyStatement getAddressStatement = new LazyStatement( "SELECT " + ADDRESS_FIELDS + "FROM addresses WHERE address_id = ?"); @Override public Address getAddress(int id) throws DataAccessException { try { PreparedStatement ps = getAddressStatement.value(); // reused so should not be auto-closed ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if(rs.next()) { return populateAddress(rs); } else return null; } } catch (SQLException ex) { throw new DataAccessException("Could not fetch address by id.", ex); } } private LazyStatement createAddressStatement = new LazyStatement( "INSERT INTO addresses(address_city, address_zipcode, address_street, address_number, address_country, address_latitude, address_longitude) " + "VALUES (?,?,?,?,?)", "address_id" ); @Override public Address createAddress(String country, String zip, String city, String street, String num, float lat, float lng) throws DataAccessException { try { PreparedStatement ps = createAddressStatement.value(); // reused so should not be auto-closed ps.setString(1, city); ps.setString(2, zip); ps.setString(3, street); ps.setString(4, num); ps.setString(5, country); ps.setFloat(6, lat); ps.setFloat(7, lng); if(ps.executeUpdate() == 0) throw new DataAccessException("No rows were affected when creating address."); try (ResultSet keys = ps.getGeneratedKeys()) { keys.next(); //if this fails we want an exception anyway return new Address(keys.getInt(1), country, zip, city, street, num, lat, lng); } } catch (SQLException ex) { throw new DataAccessException("Failed to create address.", ex); } } private LazyStatement deleteAddressStatement = new LazyStatement( "DELETE FROM addresses WHERE address_id = ?" ); @Override public void deleteAddress(int addressId) throws DataAccessException { try { PreparedStatement ps = deleteAddressStatement.value(); // reused so should not be auto-closed ps.setInt(1, addressId); if(ps.executeUpdate() == 0) throw new DataAccessException("No rows were affected when deleting address with ID=" + addressId); } catch(SQLException ex){ throw new DataAccessException("Failed to execute address deletion query.", ex); } } // used to update addresses as part of updates of other tables static void updateLocation(Connection conn, String joinSQL, String idName, int id, Address location) { try (PreparedStatement ps = conn.prepareStatement( "UPDATE addresses " + joinSQL + " SET address_city = ?, address_zipcode = ?, address_street = ?, address_number = ?, address_country=?, address_latitude=?, address_longitude=? " + "WHERE " + idName + " = ?" )) { ps.setString(1, location.getCity()); ps.setString(2, location.getZip()); ps.setString(3, location.getStreet()); ps.setString(4, location.getNum()); ps.setString(5, location.getCountry()); ps.setFloat(6, location.getLat()); ps.setFloat(7, location.getLng()); ps.setInt(8, id); ps.executeUpdate(); } catch (SQLException ex) { throw new DataAccessException("Failed to update location.", ex); } } private LazyStatement updateAddressStatement = new LazyStatement( "UPDATE addresses SET address_city = ?, address_zipcode = ?, address_street = ?, " + "address_number = ?, address_country=?, " + "address_latitude = ?, address_longitude=? " + "WHERE address_id = ?" ); @Override public void updateAddress(Address address) throws DataAccessException { try { PreparedStatement ps = updateAddressStatement.value(); // reused so should not be auto-closed ps.setString(1, address.getCity()); ps.setString(2, address.getZip()); ps.setString(3, address.getStreet()); ps.setString(4, address.getNum()); ps.setString(5, address.getCountry()); ps.setFloat(6, address.getLat()); ps.setFloat(7, address.getLng()); ps.setInt(8, address.getId()); if(ps.executeUpdate() == 0) throw new DataAccessException("Address update affected 0 rows."); } catch(SQLException ex) { throw new DataAccessException("Failed to update address.", ex); } } }
kcoolsae/Degage
db/src/main/java/be/ugent/degage/db/jdbc/JDBCAddressDAO.java
Java
agpl-3.0
8,226
package alice.util; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * * @author Alessio Mercurio * * Custom abstract classloader used to addAt/remove dynamically URLs from it * needed by JavaLibrary. * */ public abstract class AbstractDynamicClassLoader extends ClassLoader { protected final ArrayList<URL> listURLs; protected final HashMap<String, Class<?>> classCache = new HashMap<>(); public AbstractDynamicClassLoader() { super(AbstractDynamicClassLoader.class.getClassLoader()); listURLs = new ArrayList<>(); } public AbstractDynamicClassLoader(URL... urls) { super(AbstractDynamicClassLoader.class.getClassLoader()); listURLs = new ArrayList<>(Arrays.asList(urls)); } public AbstractDynamicClassLoader(URL[] urls, ClassLoader parent) { super(parent); listURLs = new ArrayList<>(Arrays.asList(urls)); } @Override public Class<?> loadClass(String className) throws ClassNotFoundException { return findClass(className); } public void addURLs(URL... urls) { if(urls == null) throw new IllegalArgumentException("Array URLs must not be null."); for (URL url : urls) { if(!listURLs.contains(url)) listURLs.add(url); } } public void removeURL(URL url) throws IllegalArgumentException { if(!listURLs.contains(url)) throw new IllegalArgumentException("URL: " + url + "not found."); listURLs.remove(url); } public void removeURLs(URL... urls) throws IllegalArgumentException { if(urls == null) throw new IllegalArgumentException("Array URLs must not be null."); for (URL url : urls) { if(!listURLs.contains(url)) throw new IllegalArgumentException("URL: " + url + "not found."); listURLs.remove(url); } } public void removeAllURLs() { if(!listURLs.isEmpty()) listURLs.clear(); } public URL[] getURLs() { URL[] result = new URL[listURLs.size()]; listURLs.toArray(result); return result; } public Class<?>[] getLoadedClasses() { return classCache.values().toArray(new Class[0]); } }
automenta/narchy
logic/src/main/java/alice/util/AbstractDynamicClassLoader.java
Java
agpl-3.0
2,091
<?php /********************************************************************************* * The contents of this file are subject to the SugarCRM Professional Subscription * Agreement ("License") which can be viewed at * http://www.sugarcrm.com/crm/products/sugar-professional-eula.html * By installing or using this file, You have unconditionally agreed to the * terms and conditions of the License, and You may not use this file except in * compliance with the License. Under the terms of the license, You shall not, * among other things: 1) sublicense, resell, rent, lease, redistribute, assign * or otherwise transfer Your rights to the Software, and 2) use the Software * for timesharing or service bureau purposes such as hosting the Software for * commercial gain and/or for the benefit of a third party. Use of the Software * may be subject to applicable fees and any use of the Software without first * paying applicable fees is strictly prohibited. You do not have the right to * remove SugarCRM copyrights from the source code or user interface. * * All copies of the Covered Code must include on each user interface screen: * (i) the "Powered by SugarCRM" logo and * (ii) the SugarCRM copyright notice * in the same form as they appear in the distribution. See full license for * requirements. * * Your Warranty, Limitations of liability and Indemnity are expressly stated * in the License. Please refer to the License for the specific language * governing these rights and limitations under the License. Portions created * by SugarCRM are Copyright (C) 2004-2010 SugarCRM, Inc.; All Rights Reserved. ********************************************************************************/ $module_name = 'sugartalk_SMS'; $viewdefs[$module_name]['DetailView'] = array( 'templateMeta' => array('form' => array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE',)), 'maxColumns' => '1', 'widths' => array( array('label' => '10', 'field' => '30'), array('label' => '10', 'field' => '30') ), ), 'panels' => array ( array ( 'name', ), array ( 'assigned_user_name', ), ) ); ?>
MarStan/sugar_work
modules/sugartalk_SMS/metadata/wireless.detailviewdefs.php
PHP
agpl-3.0
2,329
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This file is part of Tanaguru. * * Tanaguru is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.service.mock; import java.util.Collection; import java.util.Set; import org.tanaguru.entity.audit.Audit; import org.tanaguru.entity.parameterization.Parameter; import org.tanaguru.entity.parameterization.ParameterElement; import org.tanaguru.entity.parameterization.ParameterFamily; import org.tanaguru.entity.parameterization.ParameterImpl; import org.tanaguru.entity.service.parameterization.ParameterDataService; import org.tanaguru.sdk.entity.dao.GenericDAO; import org.tanaguru.sdk.entity.factory.GenericFactory; /** * * @author jkowalczyk */ public class MockParameterDataService implements ParameterDataService{ @Override public Parameter create(ParameterElement pe, String string, Audit audit) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Parameter getParameter(ParameterElement pe, String string) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Parameter getParameter(Audit audit, String string) { Parameter param = new ParameterImpl(); param.setValue("1000"); return param; } @Override public Parameter getLevelParameter(String string) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Set<Parameter> getParameterSet(ParameterFamily pf, Audit audit) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Set<Parameter> getParameterSet(ParameterFamily pf, Collection<Parameter> clctn) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Set<Parameter> getDefaultParameterSet() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Parameter getDefaultParameter(ParameterElement pe) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Parameter getDefaultLevelParameter() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Set<Parameter> getParameterSetFromAudit(Audit audit) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String getReferentialKeyFromAudit(Audit audit) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String getLevelKeyFromAudit(Audit audit) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Set<Parameter> updateParameterSet(Set<Parameter> set, Set<Parameter> set1) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Set<Parameter> updateParameter(Set<Parameter> set, Parameter prmtr) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Parameter create() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void create(Parameter e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void delete(Parameter e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void delete(Long k) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void delete(Collection<Parameter> clctn) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Collection<Parameter> findAll() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Parameter read(Long k) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Parameter saveOrUpdate(Parameter e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Collection<Parameter> saveOrUpdate(Collection<Parameter> clctn) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void setEntityDao(GenericDAO<Parameter, Long> gdao) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void setEntityFactory(GenericFactory<Parameter> gf) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Parameter update(Parameter e) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
medsob/Tanaguru
engine/crawler/src/test/java/org/tanaguru/service/mock/MockParameterDataService.java
Java
agpl-3.0
7,102
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bimserver.models.ifc4; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Ifc Task Type Enum</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see org.bimserver.models.ifc4.Ifc4Package#getIfcTaskTypeEnum() * @model * @generated */ public enum IfcTaskTypeEnum implements Enumerator { /** * The '<em><b>NULL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NULL_VALUE * @generated * @ordered */ NULL(0, "NULL", "NULL"), /** * The '<em><b>DEMOLITION</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #DEMOLITION_VALUE * @generated * @ordered */ DEMOLITION(1, "DEMOLITION", "DEMOLITION"), /** * The '<em><b>DISMANTLE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #DISMANTLE_VALUE * @generated * @ordered */ DISMANTLE(2, "DISMANTLE", "DISMANTLE"), /** * The '<em><b>ATTENDANCE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ATTENDANCE_VALUE * @generated * @ordered */ ATTENDANCE(3, "ATTENDANCE", "ATTENDANCE"), /** * The '<em><b>USERDEFINED</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #USERDEFINED_VALUE * @generated * @ordered */ USERDEFINED(4, "USERDEFINED", "USERDEFINED"), /** * The '<em><b>RENOVATION</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #RENOVATION_VALUE * @generated * @ordered */ RENOVATION(5, "RENOVATION", "RENOVATION"), /** * The '<em><b>MAINTENANCE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #MAINTENANCE_VALUE * @generated * @ordered */ MAINTENANCE(6, "MAINTENANCE", "MAINTENANCE"), /** * The '<em><b>NOTDEFINED</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NOTDEFINED_VALUE * @generated * @ordered */ NOTDEFINED(7, "NOTDEFINED", "NOTDEFINED"), /** * The '<em><b>REMOVAL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #REMOVAL_VALUE * @generated * @ordered */ REMOVAL(8, "REMOVAL", "REMOVAL"), /** * The '<em><b>DISPOSAL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #DISPOSAL_VALUE * @generated * @ordered */ DISPOSAL(9, "DISPOSAL", "DISPOSAL"), /** * The '<em><b>MOVE</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #MOVE_VALUE * @generated * @ordered */ MOVE(10, "MOVE", "MOVE"), /** * The '<em><b>OPERATION</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #OPERATION_VALUE * @generated * @ordered */ OPERATION(11, "OPERATION", "OPERATION"), /** * The '<em><b>INSTALLATION</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #INSTALLATION_VALUE * @generated * @ordered */ INSTALLATION(12, "INSTALLATION", "INSTALLATION"), /** * The '<em><b>CONSTRUCTION</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #CONSTRUCTION_VALUE * @generated * @ordered */ CONSTRUCTION(13, "CONSTRUCTION", "CONSTRUCTION"), /** * The '<em><b>LOGISTIC</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #LOGISTIC_VALUE * @generated * @ordered */ LOGISTIC(14, "LOGISTIC", "LOGISTIC"); /** * The '<em><b>NULL</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>NULL</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NULL * @model * @generated * @ordered */ public static final int NULL_VALUE = 0; /** * The '<em><b>DEMOLITION</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>DEMOLITION</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #DEMOLITION * @model * @generated * @ordered */ public static final int DEMOLITION_VALUE = 1; /** * The '<em><b>DISMANTLE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>DISMANTLE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #DISMANTLE * @model * @generated * @ordered */ public static final int DISMANTLE_VALUE = 2; /** * The '<em><b>ATTENDANCE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>ATTENDANCE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #ATTENDANCE * @model * @generated * @ordered */ public static final int ATTENDANCE_VALUE = 3; /** * The '<em><b>USERDEFINED</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>USERDEFINED</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #USERDEFINED * @model * @generated * @ordered */ public static final int USERDEFINED_VALUE = 4; /** * The '<em><b>RENOVATION</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>RENOVATION</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #RENOVATION * @model * @generated * @ordered */ public static final int RENOVATION_VALUE = 5; /** * The '<em><b>MAINTENANCE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>MAINTENANCE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #MAINTENANCE * @model * @generated * @ordered */ public static final int MAINTENANCE_VALUE = 6; /** * The '<em><b>NOTDEFINED</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>NOTDEFINED</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NOTDEFINED * @model * @generated * @ordered */ public static final int NOTDEFINED_VALUE = 7; /** * The '<em><b>REMOVAL</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>REMOVAL</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #REMOVAL * @model * @generated * @ordered */ public static final int REMOVAL_VALUE = 8; /** * The '<em><b>DISPOSAL</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>DISPOSAL</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #DISPOSAL * @model * @generated * @ordered */ public static final int DISPOSAL_VALUE = 9; /** * The '<em><b>MOVE</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>MOVE</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #MOVE * @model * @generated * @ordered */ public static final int MOVE_VALUE = 10; /** * The '<em><b>OPERATION</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>OPERATION</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #OPERATION * @model * @generated * @ordered */ public static final int OPERATION_VALUE = 11; /** * The '<em><b>INSTALLATION</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>INSTALLATION</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #INSTALLATION * @model * @generated * @ordered */ public static final int INSTALLATION_VALUE = 12; /** * The '<em><b>CONSTRUCTION</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>CONSTRUCTION</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #CONSTRUCTION * @model * @generated * @ordered */ public static final int CONSTRUCTION_VALUE = 13; /** * The '<em><b>LOGISTIC</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>LOGISTIC</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #LOGISTIC * @model * @generated * @ordered */ public static final int LOGISTIC_VALUE = 14; /** * An array of all the '<em><b>Ifc Task Type Enum</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final IfcTaskTypeEnum[] VALUES_ARRAY = new IfcTaskTypeEnum[] { NULL, DEMOLITION, DISMANTLE, ATTENDANCE, USERDEFINED, RENOVATION, MAINTENANCE, NOTDEFINED, REMOVAL, DISPOSAL, MOVE, OPERATION, INSTALLATION, CONSTRUCTION, LOGISTIC, }; /** * A public read-only list of all the '<em><b>Ifc Task Type Enum</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<IfcTaskTypeEnum> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Ifc Task Type Enum</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcTaskTypeEnum get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { IfcTaskTypeEnum result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Ifc Task Type Enum</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcTaskTypeEnum getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { IfcTaskTypeEnum result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Ifc Task Type Enum</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcTaskTypeEnum get(int value) { switch (value) { case NULL_VALUE: return NULL; case DEMOLITION_VALUE: return DEMOLITION; case DISMANTLE_VALUE: return DISMANTLE; case ATTENDANCE_VALUE: return ATTENDANCE; case USERDEFINED_VALUE: return USERDEFINED; case RENOVATION_VALUE: return RENOVATION; case MAINTENANCE_VALUE: return MAINTENANCE; case NOTDEFINED_VALUE: return NOTDEFINED; case REMOVAL_VALUE: return REMOVAL; case DISPOSAL_VALUE: return DISPOSAL; case MOVE_VALUE: return MOVE; case OPERATION_VALUE: return OPERATION; case INSTALLATION_VALUE: return INSTALLATION; case CONSTRUCTION_VALUE: return CONSTRUCTION; case LOGISTIC_VALUE: return LOGISTIC; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private IfcTaskTypeEnum(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //IfcTaskTypeEnum
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc4/IfcTaskTypeEnum.java
Java
agpl-3.0
15,449
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2020 Asqatasun.org * * This file is part of Asqatasun. * * Asqatasun is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.elementchecker.lang; import javax.annotation.Nonnull; import org.jsoup.nodes.Element; import org.asqatasun.entity.audit.TestSolution; import org.asqatasun.processor.SSPHandler; import static org.asqatasun.rules.keystore.RemarkMessageStore.*; /** * This class checks whether the lang declaration is valid and relevant */ public class LangDeclarationValidityChecker extends LangChecker { /** check declaration validity */ private final boolean checkDeclarationValidity; /** check declaration relevancy */ private final boolean checkDeclarationRelevancy; /** * Default constructor * @param checkDeclarationValidity * @param checkDeclarationRelevancy */ public LangDeclarationValidityChecker( @Nonnull boolean checkDeclarationValidity, @Nonnull boolean checkDeclarationRelevancy) { super(null, IRRELEVANT_LANG_DECL_MSG, SUSPECTED_IRRELEVANT_LANG_DECL_MSG, SUSPECTED_RELEVANT_LANG_DECL_MSG); this.checkDeclarationValidity = checkDeclarationValidity; this.checkDeclarationRelevancy = checkDeclarationRelevancy; } @Override protected TestSolution doCheckLanguage(Element element, SSPHandler sspHandler) { return checkLanguageDeclarationValidity(element, sspHandler); } /** * * @param element * @param sspHandler * @return */ public TestSolution checkLanguageDeclarationValidity(Element element, SSPHandler sspHandler) { String langDefinition = extractLangDefinitionFromElement(element, sspHandler); String effectiveLang = extractEffectiveLang(langDefinition); TestSolution declarationValidity = checkLanguageDeclarationValidity( element, langDefinition, effectiveLang, checkDeclarationValidity); if (checkDeclarationValidity && declarationValidity.equals(TestSolution.FAILED)) { return TestSolution.FAILED; } if (checkDeclarationRelevancy) { if (declarationValidity.equals(TestSolution.FAILED)) { return TestSolution.NOT_APPLICABLE; } String extractedText = extractTextFromElement(element, true); if (isTextTestable(extractedText)) { return checkLanguageRelevancy( element, effectiveLang, null, extractedText, TestSolution.PASSED, TestSolution.FAILED); } } return TestSolution.PASSED; } }
Asqatasun/Asqatasun
rules/rules-commons/src/main/java/org/asqatasun/rules/elementchecker/lang/LangDeclarationValidityChecker.java
Java
agpl-3.0
3,622
require 'test_helper' class GamesControllerTest < ActionController::TestCase setup do @game = games(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:games) end test "should get new" do get :new assert_response :success end test "should create game" do assert_difference('Game.count') do post :create, game: { max_players_per_team: @game.max_players_per_team, max_teams_per_match: @game.max_teams_per_match, min_players_per_team: @game.min_players_per_team, min_teams_per_match: @game.min_teams_per_match, name: @game.name, parent_id: @game.parent_id, scoring_method: @game.scoring_method } end assert_redirected_to game_path(assigns(:game)) end test "should show game" do get :show, id: @game assert_response :success end test "should get edit" do get :edit, id: @game assert_response :success end test "should update game" do patch :update, id: @game, game: { max_players_per_team: @game.max_players_per_team, max_teams_per_match: @game.max_teams_per_match, min_players_per_team: @game.min_players_per_team, min_teams_per_match: @game.min_teams_per_match, name: @game.name, parent_id: @game.parent_id, scoring_method: @game.scoring_method } assert_redirected_to game_path(assigns(:game)) end test "should destroy game" do assert_difference('Game.count', -1) do delete :destroy, id: @game end assert_redirected_to games_path end end
LukeShu/leaguer
test/controllers/games_controller_test.rb
Ruby
agpl-3.0
1,507
<?php /** * AvailableBudgetController.php * Copyright (c) 2019 james@firefly-iii.org * * This file is part of Firefly III (https://github.com/firefly-iii). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Budget; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\AvailableBudget; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Redirector; use Illuminate\View\View; use Log; use ValueError; /** * * Class AvailableBudgetController */ class AvailableBudgetController extends Controller { /** @var AvailableBudgetRepositoryInterface */ private $abRepository; /** @var CurrencyRepositoryInterface */ private $currencyRepos; /** * AmountController constructor. */ public function __construct() { parent::__construct(); $this->middleware( function ($request, $next) { app('view')->share('title', (string)trans('firefly.budgets')); app('view')->share('mainTitleIcon', 'fa-pie-chart'); $this->abRepository = app(AvailableBudgetRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class); return $next($request); } ); } /** * Create will always assume the user's default currency, if it's not set. * * This method will check if there is no AB, and refuse to continue if it exists. * * @param Request $request * @param Carbon $start * @param Carbon $end * @param TransactionCurrency|null $currency * * @return Factory|RedirectResponse|Redirector|View */ public function create(Request $request, Carbon $start, Carbon $end, ?TransactionCurrency $currency = null) { $currency = $currency ?? app('amount')->getDefaultCurrency(); $collection = $this->abRepository->get($start, $end); $filtered = $collection->filter( static function (AvailableBudget $budget) use ($currency) { return $currency->id === $budget->transaction_currency_id; } ); if ($filtered->count() > 0) { /** @var AvailableBudget $first */ $first = $filtered->first(); return redirect(route('available-budgets.edit', [$first->id])); } $page = (int)($request->get('page') ?? 1); return view('budgets.available-budgets.create', compact('start', 'end', 'page', 'currency')); } /** * createAlternative will show a list of enabled currencies so the user can pick one. * * @param Request $request * @param Carbon $start * @param Carbon $end * * @return Factory|View */ public function createAlternative(Request $request, Carbon $start, Carbon $end) { $currencies = $this->currencyRepos->get(); $availableBudgets = $this->abRepository->get($start, $end); // remove already budgeted currencies: $currencies = $currencies->filter( static function (TransactionCurrency $currency) use ($availableBudgets) { /** @var AvailableBudget $budget */ foreach ($availableBudgets as $budget) { if ($budget->transaction_currency_id === $currency->id) { return false; } } return true; } ); $page = (int)($request->get('page') ?? 1); return view('budgets.available-budgets.create-alternative', compact('start', 'end', 'page', 'currencies')); } /** * @param Request $request * * @return RedirectResponse|Redirector */ public function delete(Request $request) { $id = (int)$request->get('id'); if (0 !== $id) { $availableBudget = $this->abRepository->findById($id); if (null !== $availableBudget) { $this->abRepository->destroyAvailableBudget($availableBudget); session()->flash('success', trans('firefly.deleted_ab')); } } return redirect(route('budgets.index')); } /** * @param AvailableBudget $availableBudget * * @param Carbon $start * @param Carbon $end * * @return Factory|View */ public function edit(AvailableBudget $availableBudget, Carbon $start, Carbon $end) { $availableBudget->amount = number_format((float)$availableBudget->amount, $availableBudget->transactionCurrency->decimal_places, '.', ''); return view('budgets.available-budgets.edit', compact('availableBudget', 'start', 'end')); } /** * @param Request $request * * @return RedirectResponse|Redirector */ public function store(Request $request) { // make dates. try { $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); } catch (InvalidDateException $e) { $start = session()->get('start'); $end = session()->get('end'); Log::info($e->getMessage()); } // validate amount $amount = (string)$request->get('amount'); if ('' === $amount) { session()->flash('error', trans('firefly.invalid_amount')); return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')])); } if (bccomp($amount, '0') <= 0) { session()->flash('error', trans('firefly.invalid_amount')); return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')])); } // find currency $currency = $this->currencyRepos->find((int)$request->get('currency_id')); if (null === $currency) { session()->flash('error', trans('firefly.invalid_currency')); return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')])); } $start->startOfDay(); $end->endOfDay(); // find existing AB $existing = $this->abRepository->find($currency, $start, $end); if (null === $existing) { $this->abRepository->store( [ 'amount' => $amount, 'currency_id' => $currency->id, 'start' => $start, 'end' => $end, ] ); } if (null !== $existing) { // update amount: $this->abRepository->update($existing, ['amount' => $amount]); } session()->flash('success', trans('firefly.set_ab')); return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')])); } /** * @param Request $request * @param AvailableBudget $availableBudget * * @param Carbon $start * @param Carbon $end * * @return RedirectResponse|Redirector */ public function update(Request $request, AvailableBudget $availableBudget, Carbon $start, Carbon $end) { // validate amount $amount = (string)$request->get('amount'); if ('' === $amount) { session()->flash('error', trans('firefly.invalid_amount')); return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')])); } try { if (bccomp($amount, '0') <= 0) { session()->flash('error', trans('firefly.invalid_amount')); return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')])); } } catch (ValueError $e) { Log::error(sprintf('Value "%s" is not a number: %s', $amount, $e->getMessage())); session()->flash('error', trans('firefly.invalid_amount')); return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')])); } $this->abRepository->update($availableBudget, ['amount' => $amount]); session()->flash('success', trans('firefly.updated_ab')); return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')])); } }
firefly-iii/firefly-iii
app/Http/Controllers/Budget/AvailableBudgetController.php
PHP
agpl-3.0
9,393
using Merp.Registry.CommandStack.Commands; using Xunit; using SharpTestsEx; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Merp.Registry.CommandStack.Tests.Commands { public class RegisterCompanyCommandFixture { [Fact] public void Ctor_should_properly_initialise_instance() { var userId = Guid.NewGuid(); var companyId = Guid.Empty; var companyName = "Mastreeno ltd"; var nationalIdentificationNumber = "FAKE"; var vatNumber = "123"; var address = "Via Torino 51"; var city = "Milan"; var postalCode = "20123"; var province = "MI"; var country = "Italy"; var mainContactId = Guid.NewGuid(); var administrativeContactId = Guid.NewGuid(); var phoneNumber = "0123456789"; var faxNumber = "012345679"; var websiteAddress = "www.info.com"; var emailAddress = "user@info.com"; var command = new RegisterCompanyCommand(userId, companyName, nationalIdentificationNumber, vatNumber, address, postalCode, city, province, country, address, postalCode, city, province, country, address, postalCode, city, province, country, mainContactId, administrativeContactId, phoneNumber, faxNumber, websiteAddress, emailAddress); Assert.Equal(companyId, command.CompanyId); Assert.Equal(companyName, command.CompanyName); Assert.Equal(nationalIdentificationNumber, command.NationalIdentificationNumber); Assert.Equal(vatNumber, command.VatNumber); Assert.Equal(address, command.LegalAddressAddress); Assert.Equal(city, command.LegalAddressCity); Assert.Equal(postalCode, command.LegalAddressPostalCode); Assert.Equal(province, command.LegalAddressProvince); Assert.Equal(country, command.LegalAddressCountry); Assert.Equal(mainContactId, command.MainContactId); Assert.Equal(administrativeContactId, command.AdministrativeContactId); Assert.Equal(phoneNumber, command.PhoneNumber); Assert.Equal(faxNumber, command.FaxNumber); Assert.Equal(websiteAddress, command.WebsiteAddress); Assert.Equal(emailAddress, command.EmailAddress); } [Fact] public void Ctor_should_throw_on_null_companyName() { var userId = Guid.NewGuid(); var companyId = Guid.Empty; string companyName = null; var nationalIdentificationNumber = "FAKE"; var vatNumber = "123"; var address = "Via Torino 51"; var city = "Milan"; var postalCode = "20123"; var province = "MI"; var country = "Italy"; var mainContactId = Guid.NewGuid(); var administrativeContactId = Guid.NewGuid(); var phoneNumber = "0123456789"; var faxNumber = "012345679"; var websiteAddress = "www.info.com"; var emailAddress = "user@info.com"; Executing.This( () => new RegisterCompanyCommand(userId, companyName, nationalIdentificationNumber, vatNumber, address, postalCode, city, province, country, address, postalCode, city, province, country, address, postalCode, city, province, country, mainContactId, administrativeContactId, phoneNumber, faxNumber, websiteAddress, emailAddress) ) .Should() .Throw<ArgumentException>() .And .ValueOf .ParamName .Should() .Be .EqualTo("companyName"); } [Fact] public void Ctor_should_throw_on_empty_companyName() { var userId = Guid.NewGuid(); var companyId = Guid.Empty; var companyName = string.Empty; var nationalIdentificationNumber = "FAKE"; var vatNumber = "123"; var address = "Via Torino 51"; var city = "Milan"; var postalCode = "20123"; var province = "MI"; var country = "Italy"; var mainContactId = Guid.NewGuid(); var administrativeContactId = Guid.NewGuid(); var phoneNumber = "0123456789"; var faxNumber = "012345679"; var websiteAddress = "www.info.com"; var emailAddress = "user@info.com"; Executing.This( () => new RegisterCompanyCommand(userId, companyName, nationalIdentificationNumber, vatNumber, address, postalCode, city, province, country, address, postalCode, city, province, country, address, postalCode, city, province, country, mainContactId, administrativeContactId, phoneNumber, faxNumber, websiteAddress, emailAddress) ) .Should() .Throw<ArgumentException>() .And .ValueOf .ParamName .Should() .Be .EqualTo("companyName"); } [Fact] public void Ctor_should_throw_on_null_vatNumber() { var userId = Guid.NewGuid(); var companyId = Guid.Empty; var companyName = "Mastreeno ltd"; var nationalIdentificationNumber = "FAKE"; string vatNumber = null; var address = "Via Torino 51"; var city = "Milan"; var postalCode = "20123"; var province = "MI"; var country = "Italy"; var mainContactId = Guid.NewGuid(); var administrativeContactId = Guid.NewGuid(); var phoneNumber = "0123456789"; var faxNumber = "012345679"; var websiteAddress = "www.info.com"; var emailAddress = "user@info.com"; Executing.This( () => new RegisterCompanyCommand(userId, companyName, nationalIdentificationNumber, vatNumber, address, postalCode, city, province, country, address, postalCode, city, province, country, address, postalCode, city, province, country, mainContactId, administrativeContactId, phoneNumber, faxNumber, websiteAddress, emailAddress) ) .Should() .Throw<ArgumentException>() .And .ValueOf .ParamName .Should() .Be .EqualTo("vatNumber"); } [Fact] public void Ctor_should_throw_on_empty_vatNumber() { var userId = Guid.NewGuid(); var companyId = Guid.Empty; var companyName = "Mastreeno ltd"; var nationalIdentificationNumber = "FAKE"; var vatNumber = string.Empty; var address = "Via Torino 51"; var city = "Milan"; var postalCode = "20123"; var province = "MI"; var country = "Italy"; var mainContactId = Guid.NewGuid(); var administrativeContactId = Guid.NewGuid(); var phoneNumber = "0123456789"; var faxNumber = "012345679"; var websiteAddress = "www.info.com"; var emailAddress = "user@info.com"; Executing.This( () => new RegisterCompanyCommand(userId, companyName, nationalIdentificationNumber, vatNumber, address, postalCode, city, province, country, address, postalCode, city, province, country, address, postalCode, city, province, country, mainContactId, administrativeContactId, phoneNumber, faxNumber, websiteAddress, emailAddress) ) .Should() .Throw<ArgumentException>() .And .ValueOf .ParamName .Should() .Be .EqualTo("vatNumber"); } } }
mastreeno/Merp
test/Merp.Registry.CommandStack.Tests/Commands/RegisterCompanyCommandFixture.cs
C#
agpl-3.0
7,890
define([], function () { return function (distributor) { var container = document.createElement("ul") container.classList.add("filters") var div = document.createElement("div") function render(el) { el.appendChild(div) } function filtersChanged(filters) { while (container.firstChild) container.removeChild(container.firstChild) filters.forEach( function (d) { var li = document.createElement("li") container.appendChild(li) d.render(li) var button = document.createElement("button") button.textContent = "" button.onclick = function () { distributor.removeFilter(d) } li.appendChild(button) }) if (container.parentNode === div && filters.length === 0) div.removeChild(container) else if (filters.length > 0) div.appendChild(container) } return { render: render, filtersChanged: filtersChanged } } })
srauscher/hopglass
lib/filters/filtergui.js
JavaScript
agpl-3.0
1,004
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ /* eslint-disable no-magic-numbers, camelcase */ import { DISCLOSURE_TYPE, DISCLOSURE_STEP, ROLES } from '../coi-constants'; import hashCode from '../hash'; export function createProject(sourceIdentifier) { return { title: 'TEST TITLE', typeCode: 1, sourceSystem: 'KC-PD', sourceIdentifier, sourceStatus: '1', sponsors: [ { sponsorCode: '000340', sponsorName: 'NIH', sourceSystem: 'KC-PD', sourceIdentifier } ], startDate: '2017-01-01', endDate: '2017-1-31' }; } export async function insertProject(knex, project) { const id = await knex('project').insert({ title: project.title, type_cd: project.typeCode, source_system: project.sourceSystem, source_identifier: project.sourceIdentifier, source_status: project.sourceStatus, start_date: new Date(project.startDate), end_date: new Date(project.endDate) }, 'id'); await knex('project_sponsor').insert({ project_id: id[0], source_identifier: project.sourceIdentifier, source_system: project.sourceSystem, sponsor_cd: project.sponsors[0].sponsorCode, sponsor_name: project.sponsors[0].sponsorName }); return id[0]; } export function createPerson(personId, roleCode, active) { return { personId, sourcePersonType: 'EMPLOYEE', roleCode, active }; } export async function insertProjectPerson(knex, projectPerson, projectId, dispositionTypeCd, isNew) { const id = await knex('project_person') .insert({ project_id: projectId, person_id: projectPerson.personId, source_person_type: projectPerson.sourcePersonType, role_cd: projectPerson.roleCode, active: projectPerson.active, disposition_type_cd: dispositionTypeCd, new: isNew !== undefined ? isNew : true },'id'); return id[0]; } export function createDisclosure(statusCd) { return { typeCd: DISCLOSURE_TYPE.ANNUAL, statusCd, startDate: new Date(), configId: 1 }; } export async function insertDisclosure(knex, disclosure, user_id) { const id = await knex('disclosure').insert({ type_cd: disclosure.typeCd, status_cd: disclosure.statusCd, user_id, start_date: new Date(disclosure.startDate), config_id: disclosure.configId, submitted_by: user_id }, 'id'); return id[0]; } export function createComment(disclosureId, user) { return { disclosureId, topicSection: DISCLOSURE_STEP.QUESTIONNAIRE, topicId: 1, text: 'blah', userId: hashCode(user), author: user, date: new Date(), piVisible: true, reviewerVisible: true }; } export async function insertComment(knex, disclosure_id, user, text) { const id = await knex('review_comment').insert({ disclosure_id, text: text || 'I like this.', topic_section: DISCLOSURE_STEP.QUESTIONNAIRE, topic_id: 1, date: new Date(), user_id: hashCode(user), user_role: ROLES.USER, author: user, pi_visible: false, reviewer_visible: true }, 'id'); return id[0]; } export async function getComment(knex, id) { const comments = await knex('review_comment') .select( 'id', 'disclosure_id as disclosureId', 'topic_section as topicSection', 'topic_id as topicId', 'text', 'user_id as userId', 'author', 'date', 'pi_visible as piVisible', 'reviewer_visible as reviewerVisible', 'user_role as userRole', 'editable', 'current' ) .where('id', id); return comments[0]; } export function createDeclaration(disclosureId, finEntityId, projectId) { return { disclosureId, finEntityId, projectId }; } export async function insertDeclaration(knex, declaration) { const id = await knex('declaration').insert({ disclosure_id: declaration.disclosureId, fin_entity_id: declaration.finEntityId, project_id: declaration.projectId }, 'id'); return id[0]; } export function createEntity(disclosureId, status, active) { return { disclosureId, status, active }; } export async function insertEntity(knex, entity) { const id = await knex('fin_entity') .insert({ disclosure_id: entity.disclosureId, status: entity.status, active: entity.active }, 'id'); return id[0]; } export function randomInteger(max = 1000000) { return Math.floor(Math.random() * max); } export async function asyncThrows(fn, ...params) { let errorThrown = false; try { await fn(...params); } catch (err) { errorThrown = true; } return errorThrown; } export async function cleanUp(knex, tableName, id, idColumnName = 'id') { await knex(tableName) .del() .where({ [idColumnName]: id }); }
kuali/research-coi
test/test-utils.js
JavaScript
agpl-3.0
5,482
# # Copyright (C) 2014 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas 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 Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # module Auditors def self.stream(&block) ::EventStream::Stream.new(&block).tap do |stream| stream.on_insert do |record| Auditors.logger.info "AUDITOR #{identifier} #{record.to_json}" end end end def self.logger Rails.logger end end
Unow/canvas-lms
app/models/auditors.rb
Ruby
agpl-3.0
944
#!/usr/bin/python """ Copyright 2012 Paul Willworth <ioscode@gmail.com> This file is part of Galaxy Harvester. Galaxy Harvester is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Galaxy Harvester 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>. """ import os import sys import cgi import Cookie import dbSession import dbShared import MySQLdb import ghShared import ghLists from jinja2 import Environment, FileSystemLoader # Get current url try: url = os.environ['SCRIPT_NAME'] except KeyError: url = '' uiTheme = '' form = cgi.FieldStorage() # Get Cookies useCookies = 1 cookies = Cookie.SimpleCookie() try: cookies.load(os.environ['HTTP_COOKIE']) except KeyError: useCookies = 0 if useCookies: try: currentUser = cookies['userID'].value except KeyError: currentUser = '' try: loginResult = cookies['loginAttempt'].value except KeyError: loginResult = 'success' try: sid = cookies['gh_sid'].value except KeyError: sid = form.getfirst('gh_sid', '') try: uiTheme = cookies['uiTheme'].value except KeyError: uiTheme = '' else: currentUser = '' loginResult = form.getfirst('loginAttempt', '') sid = form.getfirst('gh_sid', '') # Get a session logged_state = 0 linkappend = '' disableStr = '' # escape input to prevent sql injection sid = dbShared.dbInsertSafe(sid) if loginResult == None: loginResult = 'success' sess = dbSession.getSession(sid, 2592000) if (sess != ''): logged_state = 1 currentUser = sess if (uiTheme == ''): uiTheme = dbShared.getUserAttr(currentUser, 'themeName') if (useCookies == 0): linkappend = 'gh_sid=' + sid else: disableStr = ' disabled="disabled"' if (uiTheme == ''): uiTheme = 'crafter' pictureName = dbShared.getUserAttr(currentUser, 'pictureName') print 'Content-type: text/html\n' env = Environment(loader=FileSystemLoader('templates')) env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL template = env.get_template('waypointmaps.html') print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, galaxyList=ghLists.getGalaxyList(), planetList=ghLists.getPlanetList())
clreinki/GalaxyHarvester
waypointMaps.py
Python
agpl-3.0
2,719
import os import sys import nose from subprocess import CalledProcessError, check_output as run from functools import partial GJSLINT_COMMAND = 'gjslint' GJSLINT_OPTIONS = ['--strict'] JS_BASE_FOLDER = os.path.join('skylines', 'public', 'js') JS_FILES = [ 'baro.js', 'fix-table.js', 'flight.js', 'general.js', 'map.js', 'phase-table.js', 'topbar.js', 'tracking.js', 'units.js', ] def test_js_files(): for filename in JS_FILES: f = partial(run_gjslint, filename) f.description = 'gjslint {}'.format(filename) yield f def run_gjslint(filename): path = os.path.join(JS_BASE_FOLDER, filename) args = [GJSLINT_COMMAND] args.extend(GJSLINT_OPTIONS) args.append(path) try: run(args) except CalledProcessError, e: print e.output raise AssertionError('gjslint has found errors.') except OSError: raise OSError('Failed to run gjslint. Please check that you have ' 'installed it properly.') if __name__ == "__main__": sys.argv.append(__name__) nose.run()
dkm/skylines
skylines/tests/test_gjslint.py
Python
agpl-3.0
1,110
<?php namespace PlentyConnector\Connector\IdentityService; use Assert\Assertion; use PlentyConnector\Connector\IdentityService\Exception\NotFoundException; use PlentyConnector\Connector\IdentityService\Storage\IdentityStorageInterface; use PlentyConnector\Connector\ValidatorService\ValidatorServiceInterface; use PlentyConnector\Connector\ValueObject\Identity\Identity; use Ramsey\Uuid\Uuid; /** * Class IdentityService. */ class IdentityService implements IdentityServiceInterface { /** * @var IdentityStorageInterface */ private $storage; /** * @var ValidatorServiceInterface */ private $validator; /** * IdentityService constructor. * * @param IdentityStorageInterface $storage * @param ValidatorServiceInterface $validator */ public function __construct( IdentityStorageInterface $storage, ValidatorServiceInterface $validator ) { $this->storage = $storage; $this->validator = $validator; } /** * {@inheritdoc} */ public function findOneOrThrow($adapterIdentifier, $adapterName, $objectType) { Assertion::string($adapterIdentifier); Assertion::notBlank($adapterIdentifier); Assertion::string($adapterName); Assertion::notBlank($adapterName); Assertion::string($objectType); Assertion::notBlank($objectType); $identity = $this->findOneBy([ 'objectType' => $objectType, 'adapterIdentifier' => $adapterIdentifier, 'adapterName' => $adapterName, ]); if (null === $identity) { throw new NotFoundException(sprintf('Could not find identity for %s with identifier %s in %s.', $objectType, $adapterIdentifier, $adapterName)); } $this->validator->validate($identity); return $identity; } /** * {@inheritdoc} */ public function findOneOrCreate($adapterIdentifier, $adapterName, $objectType) { Assertion::string($adapterIdentifier); Assertion::notBlank($adapterIdentifier); Assertion::string($adapterName); Assertion::notBlank($adapterName); Assertion::string($objectType); Assertion::notBlank($objectType); $identity = $this->findOneBy([ 'objectType' => $objectType, 'adapterIdentifier' => $adapterIdentifier, 'adapterName' => $adapterName, ]); if (null === $identity) { $objectIdentifier = Uuid::uuid4()->toString(); $identity = $this->create( $objectIdentifier, $objectType, (string) $adapterIdentifier, $adapterName ); } $this->validator->validate($identity); return $identity; } /** * {@inheritdoc} */ public function findOneBy(array $criteria = []) { Assertion::isArray($criteria); $identity = $this->storage->findOneBy($criteria); $this->validator->validate($identity); return $identity; } /** * {@inheritdoc} */ public function create($objectIdentifier, $objectType, $adapterIdentifier, $adapterName) { $params = compact( 'objectIdentifier', 'objectType', 'adapterIdentifier', 'adapterName' ); /** * @var Identity $identity */ $identity = Identity::fromArray($params); $this->storage->persist($identity); $this->validator->validate($identity); return $identity; } /** * {@inheritdoc} */ public function findBy(array $criteria = []) { Assertion::isArray($criteria); $identities = $this->storage->findBy($criteria); array_walk($identities, function (Identity $identity) { $this->validator->validate($identity); }); return $identities; } /** * {@inheritdoc} */ public function remove(Identity $identity) { $this->validator->validate($identity); $this->storage->remove($identity); } /** * {@inheritdoc} */ public function exists(array $criteria = []) { $identity = $this->findOneBy($criteria); return (bool) $identity; } /** * @param $objectIdentifier * @param $objectType * @param $adapterName * * @return bool */ public function isMapppedIdentity($objectIdentifier, $objectType, $adapterName) { $identities = $this->findBy([ 'objectIdentifier' => $objectIdentifier, 'objectType' => $objectType, ]); $otherIdentities = array_filter($identities, function (Identity $identity) use ($adapterName) { return $identity->getAdapterName() !== $adapterName; }); if (empty($otherIdentities)) { return false; } return true; } }
jochenmanz/plentymarkets-shopware-connector
Connector/IdentityService/IdentityService.php
PHP
agpl-3.0
5,023
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (C) 2014 Didotech srl (<http://www.didotech.com>). # # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import sale_order from . import purchase_order
iw3hxn/LibrERP
sale_direct_buy/models/__init__.py
Python
agpl-3.0
1,069
<?php /* * @author Anakeen * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License * @package FDL */ /** * generate interface for the rdition of document * * @author Anakeen 2003 * @version $Id: editcard.php,v 1.76 2008/11/10 16:53:06 eric Exp $ * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License * @package FDL * @subpackage */ /** */ include_once ("FDL/Class.Doc.php"); include_once ("FDL/Class.DocAttr.php"); include_once ("FDL/editutil.php"); function editcard(&$action) { $docid = GetHttpVars("id", 0); // document to edit $classid = GetHttpVars("classid", 0); // use when new doc or change class $zonebodycard = GetHttpVars("zone"); // define view action $usefor = GetHttpVars("usefor"); // default values for a document $vid = GetHttpVars("vid"); // special controlled view $mskid = GetHttpVars("mskid"); // special mask $dbaccess = $action->GetParam("FREEDOM_DB"); editmode($action); if (!is_numeric($classid)) $classid = getFamIdFromName($dbaccess, $classid); if (($usefor == "D") && ($zonebodycard == "")) $zonebodycard = "FDL:EDITBODYCARD"; // always default view for default document if ($docid == 0) { // new document if ($classid > 0) { $doc = createDoc($dbaccess, $classid, true, ($usefor != "D")); } } else { // modify document $doc = new_Doc($dbaccess, $docid); $docid = $doc->id; if ($doc->isConfidential()) { redirect($action, "FDL", "FDL_CONFIDENTIAL&&id=" . $doc->id); } $classid = $doc->fromid; } $usefor = GetHttpVars("usefor"); // default values for a document $vid = GetHttpVars("vid"); // special controlled view $mskid = GetHttpVars("mskid"); // special mask $dbaccess = $action->GetParam("FREEDOM_DB"); editmode($action); if (!is_numeric($classid)) $classid = getFamIdFromName($dbaccess, $classid); if (($usefor == "D") && ($zonebodycard == "")) $zonebodycard = "FDL:EDITBODYCARD"; // always default view for default document if ($docid == 0) { // new document if ($classid > 0) { $doc = createDoc($dbaccess, $classid, true, ($usefor != "D")); if (!$doc) $action->exitError(sprintf(_("no privilege to create this kind (%d) of document") , $classid)); $fdoc = new DocFam($dbaccess, $classid); if ($fdoc->control('icreate') != "") $action->exitError(sprintf(_("no privilege to create interactivaly this kind (%s) of document") , $fdoc->title)); } } else { // modify document $doc = new_Doc($dbaccess, $docid); $docid = $doc->id; if ($doc->isConfidential()) { redirect($action, "FDL", "FDL_CONFIDENTIAL&&id=" . $doc->id); } $fdoc = new DocFam($dbaccess, $classid); } if (($usefor == "D") || ($usefor == "Q")) { // special edit $zonebodycard = "FDL:EDITBODYCARD"; switch ($usefor) { case "D": $doc->usefor = 'D'; $doc->setDefaultValues($fdoc->getDefValues() , false); $doc->state = ''; break; case "Q": $doc->usefor = 'Q'; $doc->setDefaultValues($fdoc->getParams() , false); $doc->state = ''; break; } } else { // normal edit if ($doc->cvid > 0) { if (!$vid) $vid = $doc->getDefaultView(true, "id"); if ($vid) setHttpVar("vid", $vid); // special controlled view $cvdoc = new_Doc($dbaccess, $doc->cvid); $cvdoc->set($doc); } if (($vid != "") && ($doc->cvid > 0)) { $err = $cvdoc->control(trim($vid)); // control special view if ($err != "") $action->exitError("CV:" . $cvdoc->title . "\n" . $err); $tview = $cvdoc->getView($vid); $doc->setMask($tview["CV_MSKID"]); if ($zonebodycard == "") $zonebodycard = $tview["CV_ZVIEW"]; } if (($vid == "") && ($mskid != "")) { $mdoc = new_Doc($dbaccess, $mskid); if ($mdoc->isAlive() && ($mdoc->control('view') == "")) $doc->setMask($mdoc->id); } if (GetHttpVars("viewconstraint") == "Y") { // from modcard function if constraint error include_once ("FDL/modcard.php"); setPostVars($doc); // HTTP VARS comes from previous edition } $msg = $doc->preEdition(); if ($zonebodycard == "") { if ((!$docid) && $doc->defaultcreate != "") $zonebodycard = $doc->defaultcreate; else $zonebodycard = $doc->defaultedit; } } if ($zonebodycard == "") $zonebodycard = "FDL:EDITBODYCARD"; $action->lay->Set("classid", $classid); $action->lay->Set("usefor", $usefor); if ($usefor == "D") { $doc->SetWriteVisibility(); // contruct js functions $jsfile = $action->GetLayoutFile("editcard.js"); $jslay = new Layout($jsfile, $action); $jslay->Set("attrnid", '[]'); $jslay->Set("attrntitle", '[]'); $jslay->SetBlockData("RATTR", $tjsa); $action->parent->AddJsCode($jslay->gen()); $action->lay->Set("ZONEBODYCARD", $doc->viewDoc($zonebodycard)); } else { if ($doc->id == 0) { if (fdl_setHttpVars($doc)) $doc->refresh(); } setRefreshAttributes($action, $doc); $action->lay->Set("ZONEBODYCARD", $doc->viewDoc($zonebodycard)); setNeededAttributes($action, $doc); } $action->lay->set("maxFileUpload", ini_get("max_file_uploads")); $action->lay->Set("NOFORM", (preg_match("/[A-Z]+:[^:]+:U/", $zonebodycard, $reg))); // compute modify condition js } function setNeededAttributes(&$action, &$doc) { $attrn = $doc->GetNeededAttributes($doc->usefor == 'Q'); if (count($attrn) == 0) { $sattrNid = "[]"; $sattrNtitle = "[]"; } else { while (list($k, $v) = each($attrn)) { $attrNid[] = $v->id; $attrNtitle[] = addslashes($v->getLabel()); } $sattrNid = "['" . implode("','", $attrNid) . "']"; $sattrNtitle = "['" . implode("','", $attrNtitle) . "']"; } //compute constraint for enable/disable input $tjsa = array(); if ($doc->usefor != "D") { /* if (GetHttpVars("viewconstraint")!="Y") $doc->Refresh(); else { $err=$doc->SpecRefresh(); // to use addParamRefresh $err.=$doc->SpecRefreshGen(true); } */ $ka = 0; foreach ($doc->paramRefresh as $k => $v) { $tjsa[] = array( "jstain" => "['" . implode("','", $v["in"]) . "']", "jstaout" => "['" . implode("','", $v["out"]) . "']", "jska" => "$ka" ); $ka++; } } // contruct js functions $jsfile = $action->GetLayoutFile("editcard.js"); $jslay = new Layout($jsfile, $action); $jslay->Set("attrnid", $sattrNid); $jslay->Set("attrntitle", $sattrNtitle); $jslay->SetBlockData("RATTR", $tjsa); $action->parent->AddJsCode($jslay->gen()); } function setRefreshAttributes(&$action, &$doc) { if ($doc->usefor != "D") { if ($doc->usefor == "Q") { // parameters $doc->SpecRefreshGen(true); } else { $doc->Refresh(); } } } function moreone($v) { return (strlen($v) > 1); } function cmp_cvorder2($a, $b) { if ($a["cv_order"] == $b["cv_order"]) { return 0; } return ($a["cv_order"] < $b["cv_order"]) ? -1 : 1; } /** * set values from http var in case of creation of doc * values are set only if not set before * * @param Doc $doc current document to edit * @return bool true if , at least, one value is modified */ function fdl_setHttpVars(&$doc) { global $_GET, $_POST, $ZONE_ARGS; $ismod = false; $http = array(); foreach ($_POST as $k => $v) { $http[$k] = $v; } foreach ($_GET as $k => $v) { $http[$k] = $v; } if (is_array($ZONE_ARGS)) { foreach ($ZONE_ARGS as $k => $v) { $http[$k] = $v; } } foreach ($http as $k => $v) { $oa = $doc->getAttribute($k); if ($oa) { if ($doc->getValue($k) == "") { if ($oa->inArray() && (!is_array($v))) $v = $doc->_val2array(str_replace('\n', "\n", $v)); $doc->setValue($k, $v); // print "<br>Set $k to ";print_r($v); $ismod = true; } } } return $ismod; } ?>
Eric-Brison/dynacase-core
Zone/Fdl/editcard.php
PHP
agpl-3.0
8,796