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
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # 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 openerp import fields, models class Tag(models.Model): _inherit = 'myo.tag' pharmacy_ids = fields.Many2many( 'myo.pharmacy', 'myo_pharmacy_tag_rel', 'tag_id', 'pharmacy_id', 'Pharmacies' ) class Pharmacy(models.Model): _inherit = 'myo.pharmacy' tag_ids = fields.Many2many( 'myo.tag', 'myo_pharmacy_tag_rel', 'pharmacy_id', 'tag_id', 'Tags' )
MostlyOpen/odoo_addons
myo_pharmacy/models/tag.py
Python
agpl-3.0
1,365
<?php namespace Plenty\Modules\ItemSet\Models; /** * The ItemSetConfig model. */ abstract class ItemSetConfig { const CREATED_AT = 'createdAt'; const UPDATED_AT = 'updatedAt'; public $setId; public $rebate; /** * Returns this model as an array. */ public function toArray( ):array { return []; } }
plentymarkets/plugin-hack-api
Modules/ItemSet/Models/ItemSetConfig.php
PHP
agpl-3.0
326
<?php # AST_LISTS_stats.php # # Copyright (C) 2014 Matt Florell <vicidial@gmail.com> LICENSE: AGPLv2 # # This is a list inventory report, not a calling report. This report will show # statistics for all of the lists in the selected campaigns # # CHANGES # 130926-0721 - First build based upon LISTS campaign report # 130927-2154 - Added summary and full download options # 140108-0714 - Added webserver and hostname to report logging # 140328-0005 - Converted division calculations to use MathZDC function # $startMS = microtime(); header ("Content-type: text/html; charset=utf-8"); require("dbconnect_mysqli.php"); require("functions.php"); $PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER']; $PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW']; $PHP_SELF=$_SERVER['PHP_SELF']; if (isset($_GET["group"])) {$group=$_GET["group"];} elseif (isset($_POST["group"])) {$group=$_POST["group"];} if (isset($_GET["list"])) {$list=$_GET["list"];} elseif (isset($_POST["list"])) {$list=$_POST["list"];} if (isset($_GET["DB"])) {$DB=$_GET["DB"];} elseif (isset($_POST["DB"])) {$DB=$_POST["DB"];} if (isset($_GET["submit"])) {$submit=$_GET["submit"];} elseif (isset($_POST["submit"])) {$submit=$_POST["submit"];} if (isset($_GET["SUBMIT"])) {$SUBMIT=$_GET["SUBMIT"];} elseif (isset($_POST["SUBMIT"])) {$SUBMIT=$_POST["SUBMIT"];} if (isset($_GET["file_download"])) {$file_download=$_GET["file_download"];} elseif (isset($_POST["file_download"])) {$file_download=$_POST["file_download"];} if (isset($_GET["report_display_type"])) {$report_display_type=$_GET["report_display_type"];} elseif (isset($_POST["report_display_type"])) {$report_display_type=$_POST["report_display_type"];} if (isset($_GET["campaigns_or_lists_rpt"])) {$campaigns_or_lists_rpt=$_GET["campaigns_or_lists_rpt"];} elseif (isset($_POST["campaigns_or_lists_rpt"])) {$campaigns_or_lists_rpt=$_POST["campaigns_or_lists_rpt"];} $report_name = 'Lists Statuses Report'; $db_source = 'M'; $JS_text="<script language='Javascript'>\n"; $JS_onload="onload = function() {\n"; ############################################# ##### START SYSTEM_SETTINGS LOOKUP ##### $stmt = "SELECT use_non_latin,outbound_autodial_active,slave_db_server,reports_use_slave_db FROM system_settings;"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $qm_conf_ct = mysqli_num_rows($rslt); if ($qm_conf_ct > 0) { $row=mysqli_fetch_row($rslt); $non_latin = $row[0]; $outbound_autodial_active = $row[1]; $slave_db_server = $row[2]; $reports_use_slave_db = $row[3]; } ##### END SETTINGS LOOKUP ##### ########################################### if ($non_latin < 1) { $PHP_AUTH_USER = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_USER); $PHP_AUTH_PW = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_PW); } else { $PHP_AUTH_PW = preg_replace("/'|\"|\\\\|;/","",$PHP_AUTH_PW); $PHP_AUTH_USER = preg_replace("/'|\"|\\\\|;/","",$PHP_AUTH_USER); } $auth=0; $reports_auth=0; $admin_auth=0; $auth_message = user_authorization($PHP_AUTH_USER,$PHP_AUTH_PW,'REPORTS',1); if ($auth_message == 'GOOD') {$auth=1;} if ($auth > 0) { $stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 7 and view_reports > 0;"; if ($DB) {echo "|$stmt|\n";} $rslt=mysql_to_mysqli($stmt, $link); $row=mysqli_fetch_row($rslt); $admin_auth=$row[0]; $stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 6 and view_reports > 0;"; if ($DB) {echo "|$stmt|\n";} $rslt=mysql_to_mysqli($stmt, $link); $row=mysqli_fetch_row($rslt); $reports_auth=$row[0]; if ($reports_auth < 1) { $VDdisplayMESSAGE = "You are not allowed to view reports"; Header ("Content-type: text/html; charset=utf-8"); echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; exit; } if ( ($reports_auth > 0) and ($admin_auth < 1) ) { $ADD=999999; $reports_only_user=1; } } else { $VDdisplayMESSAGE = "Login incorrect, please try again"; if ($auth_message == 'LOCK') { $VDdisplayMESSAGE = "Too many login attempts, try again in 15 minutes"; Header ("Content-type: text/html; charset=utf-8"); echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n"; exit; } Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\""); Header("HTTP/1.0 401 Unauthorized"); echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$PHP_AUTH_PW|$auth_message|\n"; exit; } ##### BEGIN log visit to the vicidial_report_log table ##### $LOGip = getenv("REMOTE_ADDR"); $LOGbrowser = getenv("HTTP_USER_AGENT"); $LOGscript_name = getenv("SCRIPT_NAME"); $LOGserver_name = getenv("SERVER_NAME"); $LOGserver_port = getenv("SERVER_PORT"); $LOGrequest_uri = getenv("REQUEST_URI"); $LOGhttp_referer = getenv("HTTP_REFERER"); if (preg_match("/443/i",$LOGserver_port)) {$HTTPprotocol = 'https://';} else {$HTTPprotocol = 'http://';} if (($LOGserver_port == '80') or ($LOGserver_port == '443') ) {$LOGserver_port='';} else {$LOGserver_port = ":$LOGserver_port";} $LOGfull_url = "$HTTPprotocol$LOGserver_name$LOGserver_port$LOGrequest_uri"; $LOGhostname = php_uname('n'); if (strlen($LOGhostname)<1) {$LOGhostname='X';} if (strlen($LOGserver_name)<1) {$LOGserver_name='X';} $stmt="SELECT webserver_id FROM vicidial_webservers where webserver='$LOGserver_name' and hostname='$LOGhostname' LIMIT 1;"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {echo "$stmt\n";} $webserver_id_ct = mysqli_num_rows($rslt); if ($webserver_id_ct > 0) { $row=mysqli_fetch_row($rslt); $webserver_id = $row[0]; } else { ##### insert webserver entry $stmt="INSERT INTO vicidial_webservers (webserver,hostname) values('$LOGserver_name','$LOGhostname');"; if ($DB) {echo "$stmt\n";} $rslt=mysql_to_mysqli($stmt, $link); $affected_rows = mysqli_affected_rows($link); $webserver_id = mysqli_insert_id($link); } $stmt="INSERT INTO vicidial_report_log set event_date=NOW(), user='$PHP_AUTH_USER', ip_address='$LOGip', report_name='$report_name', browser='$LOGbrowser', referer='$LOGhttp_referer', notes='$LOGserver_name:$LOGserver_port $LOGscript_name |$group[0], $query_date, $end_date, $shift, $file_download, $report_display_type|', url='$LOGfull_url', webserver='$webserver_id';"; if ($DB) {echo "|$stmt|\n";} $rslt=mysql_to_mysqli($stmt, $link); $report_log_id = mysqli_insert_id($link); ##### END log visit to the vicidial_report_log table ##### if ( (strlen($slave_db_server)>5) and (preg_match("/$report_name/",$reports_use_slave_db)) ) { mysqli_close($link); $use_slave_server=1; $db_source = 'S'; require("dbconnect.php"); $MAIN.="<!-- Using slave server $slave_db_server $db_source -->\n"; } $stmt="SELECT user_group from vicidial_users where user='$PHP_AUTH_USER';"; if ($DB) {$MAIN.="|$stmt|\n";} $rslt=mysql_to_mysqli($stmt, $link); $row=mysqli_fetch_row($rslt); $LOGuser_group = $row[0]; $stmt="SELECT allowed_campaigns,allowed_reports from vicidial_user_groups where user_group='$LOGuser_group';"; if ($DB) {$MAIN.="|$stmt|\n";} $rslt=mysql_to_mysqli($stmt, $link); $row=mysqli_fetch_row($rslt); $LOGallowed_campaigns = $row[0]; $LOGallowed_reports = $row[1]; if ( (!preg_match("/$report_name/",$LOGallowed_reports)) and (!preg_match("/ALL REPORTS/",$LOGallowed_reports)) ) { Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\""); Header("HTTP/1.0 401 Unauthorized"); echo "You are not allowed to view this report: |$PHP_AUTH_USER|$report_name|\n"; exit; } $NOW_DATE = date("Y-m-d"); $NOW_TIME = date("Y-m-d H:i:s"); $STARTtime = date("U"); $LOGallowed_campaignsSQL=''; $whereLOGallowed_campaignsSQL=''; if ( (!preg_match('/\-ALL/i', $LOGallowed_campaigns)) ) { $rawLOGallowed_campaignsSQL = preg_replace("/ -/",'',$LOGallowed_campaigns); $rawLOGallowed_campaignsSQL = preg_replace("/ /","','",$rawLOGallowed_campaignsSQL); $LOGallowed_campaignsSQL = "and campaign_id IN('$rawLOGallowed_campaignsSQL')"; $whereLOGallowed_campaignsSQL = "where campaign_id IN('$rawLOGallowed_campaignsSQL')"; } $regexLOGallowed_campaigns = " $LOGallowed_campaigns "; ########### if (!isset($list)) {$list = '';} $i=0; $list_string='|'; $list_ct = count($list); while($i < $list_ct) { $list_string .= "$list[$i]|"; $i++; } $stmt="select list_id, list_name, campaign_id from vicidial_lists $whereLOGallowed_campaignsSQL order by list_id;"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $lists_to_print = mysqli_num_rows($rslt); $i=0; while ($i < $lists_to_print) { $row=mysqli_fetch_row($rslt); $lists[$i] = $row[0]; $list_names[$i] = $row[1]; $list_campaigns[$i] = $row[2]; if (preg_match('/\-ALL/',$list_string) ) {$list[$i] = $lists[$i];} $i++; } $i=0; $list_string='|'; $list_ct = count($list); while($i < $list_ct) { $list_string .= "$list[$i]|"; $list_SQL .= "'$list[$i]',"; $listQS .= "&list[]=$list[$i]"; $i++; } $list_id_str=substr($list_SQL,0,-1); $group_SQL = "$LOGallowed_campaignsSQL"; $group_SQLand = "$LOGallowed_campaignsSQL"; ####################### # Get lists to query to avoid using a nested query $lists_id_str=""; $list_stmt="SELECT list_id from vicidial_lists where active IN('Y','N') $group_SQLand"; $list_rslt=mysql_to_mysqli($list_stmt, $link); while ($lrow=mysqli_fetch_row($list_rslt)) { $lists_id_str.="'$lrow[0]',"; } $lists_id_str=substr($lists_id_str,0,-1); $stmt="select vsc_id,vsc_name from vicidial_status_categories;"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {echo "$stmt\n";} $statcats_to_print = mysqli_num_rows($rslt); $i=0; while ($i < $statcats_to_print) { $row=mysqli_fetch_row($rslt); $vsc_id[$i] = $row[0]; $vsc_name[$i] = $row[1]; $category_statuses=""; $status_stmt="select distinct status from vicidial_statuses where category='$row[0]' UNION select distinct status from vicidial_campaign_statuses where category='$row[0]' $group_SQLand"; if ($DB) {echo "$status_stmt\n";} $status_rslt=mysql_to_mysqli($status_stmt, $link); while ($status_row=mysqli_fetch_row($status_rslt)) { $category_statuses.="'$status_row[0]',"; } $category_statuses=substr($category_statuses, 0, -1); $category_stmt="select count(*) from vicidial_list where status in ($category_statuses) and list_id IN($lists_id_str)"; if ($DB) {echo "$category_stmt\n";} $category_rslt=mysql_to_mysqli($category_stmt, $link); $category_row=mysqli_fetch_row($category_rslt); $vsc_count[$i] = $category_row[0]; $i++; } ### BEGIN gather all statuses that are in status flags ### $human_answered_statuses=''; $sale_statuses=''; $dnc_statuses=''; $customer_contact_statuses=''; $not_interested_statuses=''; $unworkable_statuses=''; $stmt="select status,human_answered,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,status_name from vicidial_statuses;"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $statha_to_print = mysqli_num_rows($rslt); $i=0; while ($i < $statha_to_print) { $row=mysqli_fetch_row($rslt); $temp_status = $row[0]; $statname_list["$temp_status"] = "$row[9]"; if ($row[1]=='Y') {$human_answered_statuses .= "'$temp_status',";} if ($row[2]=='Y') {$sale_statuses .= "'$temp_status',";} if ($row[3]=='Y') {$dnc_statuses .= "'$temp_status',";} if ($row[4]=='Y') {$customer_contact_statuses .= "'$temp_status',";} if ($row[5]=='Y') {$not_interested_statuses .= "'$temp_status',";} if ($row[6]=='Y') {$unworkable_statuses .= "'$temp_status',";} if ($row[7]=='Y') {$scheduled_callback_statuses .= "'$temp_status',";} if ($row[8]=='Y') {$completed_statuses .= "'$temp_status',";} $i++; } $stmt="select status,human_answered,sale,dnc,customer_contact,not_interested,unworkable,scheduled_callback,completed,status_name from vicidial_campaign_statuses where selectable IN('Y','N') $group_SQLand;"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $statha_to_print = mysqli_num_rows($rslt); $i=0; while ($i < $statha_to_print) { $row=mysqli_fetch_row($rslt); $temp_status = $row[0]; $statname_list["$temp_status"] = "$row[9]"; if ( ($row[1]=='Y') and (!preg_match("/'$temp_status'/",$human_answered_statuses)) ) {$human_answered_statuses .= "'$temp_status',";} if ($row[2]=='Y') {$sale_statuses .= "'$temp_status',";} if ($row[3]=='Y') {$dnc_statuses .= "'$temp_status',";} if ($row[4]=='Y') {$customer_contact_statuses .= "'$temp_status',";} if ($row[5]=='Y') {$not_interested_statuses .= "'$temp_status',";} if ($row[6]=='Y') {$unworkable_statuses .= "'$temp_status',";} if ($row[7]=='Y') {$scheduled_callback_statuses .= "'$temp_status',";} if ($row[8]=='Y') {$completed_statuses .= "'$temp_status',";} $i++; } if (strlen($human_answered_statuses)>2) {$human_answered_statuses = substr("$human_answered_statuses", 0, -1);} else {$human_answered_statuses="''";} if (strlen($sale_statuses)>2) {$sale_statuses = substr("$sale_statuses", 0, -1);} else {$sale_statuses="''";} if (strlen($dnc_statuses)>2) {$dnc_statuses = substr("$dnc_statuses", 0, -1);} else {$dnc_statuses="''";} if (strlen($customer_contact_statuses)>2) {$customer_contact_statuses = substr("$customer_contact_statuses", 0, -1);} else {$customer_contact_statuses="''";} if (strlen($not_interested_statuses)>2) {$not_interested_statuses = substr("$not_interested_statuses", 0, -1);} else {$not_interested_statuses="''";} if (strlen($unworkable_statuses)>2) {$unworkable_statuses = substr("$unworkable_statuses", 0, -1);} else {$unworkable_statuses="''";} if (strlen($scheduled_callback_statuses)>2) {$scheduled_callback_statuses = substr("$scheduled_callback_statuses", 0, -1);} else {$scheduled_callback_statuses="''";} if (strlen($completed_statuses)>2) {$completed_statuses = substr("$completed_statuses", 0, -1);} else {$completed_statuses="''";} $HEADER.="<HTML>\n"; $HEADER.="<HEAD>\n"; $HEADER.="<STYLE type=\"text/css\">\n"; $HEADER.="<!--\n"; $HEADER.=" .green {color: white; background-color: green}\n"; $HEADER.=" .red {color: white; background-color: red}\n"; $HEADER.=" .blue {color: white; background-color: blue}\n"; $HEADER.=" .purple {color: white; background-color: purple}\n"; $HEADER.="-->\n"; $HEADER.=" </STYLE>\n"; $HEADER.="<link rel=\"stylesheet\" href=\"horizontalbargraph.css\">\n"; $HEADER.="<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\">\n"; $HEADER.="<TITLE>$report_name</TITLE></HEAD><BODY BGCOLOR=WHITE marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>\n"; $short_header=1; $MAIN.="<TABLE CELLPADDING=4 CELLSPACING=0><TR><TD>"; $MAIN.="<FORM ACTION=\"$PHP_SELF\" METHOD=GET name=vicidial_report id=vicidial_report>\n"; $MAIN.="<TABLE CELLSPACING=3><TR><TD VALIGN=TOP>"; $MAIN.="<INPUT TYPE=HIDDEN NAME=DB VALUE=\"$DB\">\n"; $MAIN.="</TD>"; $MAIN.="<TD VALIGN=TOP> Lists:<BR>"; $MAIN.="<SELECT SIZE=5 NAME=list[] multiple>\n"; if (preg_match('/\-\-ALL\-\-/',$list_string)) {$MAIN.="<option value=\"--ALL--\" selected>-- ALL LISTS --</option>\n";} else {$MAIN.="<option value=\"--ALL--\">-- ALL LISTS --</option>\n";} $o=0; while ($lists_to_print > $o) { if (preg_match("/$lists[$o]\|/i",$list_string)) {$MAIN.="<option selected value=\"$lists[$o]\">$lists[$o] - $list_names[$o]</option>\n";} else {$MAIN.="<option value=\"$lists[$o]\">$lists[$o] - $list_names[$o]</option>\n";} $o++; } $MAIN.="</SELECT><BR><a href=\"AST_LISTS_campaign_stats.php?DB=$DB\">SWITCH TO CAMPAIGNS</a>\n"; $MAIN.="</TD>"; $MAIN.="<TD VALIGN=TOP>"; #$MAIN.="Display as:<BR/>"; #$MAIN.="<select name='report_display_type'>"; #if ($report_display_type) {$MAIN.="<option value='$report_display_type' selected>$report_display_type</option>";} #$MAIN.="<option value='TEXT'>TEXT</option><option value='HTML'>HTML</option></select>&nbsp; "; $MAIN.="<BR><BR><BR>\n"; $MAIN.="<INPUT type=submit NAME=SUBMIT VALUE=SUBMIT>\n"; $MAIN.="</TD><TD VALIGN=TOP> &nbsp; &nbsp; &nbsp; &nbsp; "; $MAIN.="<FONT FACE=\"ARIAL,HELVETICA\" COLOR=BLACK SIZE=2>"; if (strlen($group[0]) > 1) { $MAIN.=" <a href=\"./admin.php?ADD=34&campaign_id=$group[0]\">MODIFY</a> | \n"; $MAIN.=" <a href=\"./admin.php?ADD=999999\">REPORTS</a> </FONT>\n"; } else { $MAIN.=" <a href=\"./admin.php?ADD=10\">CAMPAIGNS</a> | \n"; $MAIN.=" <a href=\"./admin.php?ADD=999999\">REPORTS</a> </FONT>\n"; } $MAIN.="</TD></TR></TABLE>"; $MAIN.="</FORM>\n\n"; $MAIN.="<PRE><FONT SIZE=2>\n\n"; if (strlen($list[0]) < 1) { $MAIN.="\n\n"; $MAIN.="PLEASE SELECT A LIST OR LISTS ABOVE AND CLICK SUBMIT\n"; } else { $totalOUToutput = ''; $totalOUToutput .= "List Status Stats $NOW_TIME <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n"; $totalOUToutput .= "\n"; $list_stmt="select vicidial_list.list_id,list_name,active, count(*) from vicidial_list, vicidial_lists where vicidial_lists.list_id in ($list_id_str) and vicidial_lists.list_id=vicidial_list.list_id group by vicidial_list.list_id, list_name, active order by list_id, list_name asc;"; $list_rslt=mysql_to_mysqli($list_stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $listids_to_print = mysqli_num_rows($list_rslt); $CSV_text1="\"\",\"LIST ID SUMMARY\"\n"; $CSV_text1.="\"LIST ID\",\"LIST NAME\",\"TOTAL LEADS\",\"ACTIVE/INACTIVE\"\n"; $CSV_text2=""; $CSV_text3=""; $CSV_textALL=""; $i=0; $totalOUToutput .= "---------- TOTAL LIST ID SUMMARY <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n"; $totalOUToutput .= "+------------------------------------------+------------+----------+\n"; $totalOUToutput .= "| LIST | LEADS | ACTIVE |\n"; $totalOUToutput .= "+------------------------------------------+------------+----------+\n"; $CSV_textSUMMARY.="\"LIST ID SUMMARY\"\n"; $CSV_textSUMMARY.="\"LIST\",\"LEADS\",\"ACTIVE\"\n"; $OUToutput=''; $OUToutput .= "\n"; $OUToutput .= "---------- INDIVIDUAL LIST ID SUMMARIES\n"; while ($i < $listids_to_print) { $list_row=mysqli_fetch_row($list_rslt); $LISTIDlists[$i] = $list_row[0]; $LISTIDlist_names[$i] = $list_row[1]; if ($list_row[2]=="Y") {$active_txt="ACTIVE";} else {$active_txt="INACTIVE";} $active_txt=sprintf("%-8s", $active_txt); $LISTIDcalls[$i] = $list_row[3]; $TOTALleads =$list_row[3]; $totalTOTALleads+=$TOTALleads; $LISTIDcount = sprintf("%10s", $LISTIDcalls[$i]);while(strlen($LISTIDcount)>10) {$LISTIDcount = substr("$LISTIDcount", 0, -1);} $LISTIDname = sprintf("%-40s", "$LISTIDlists[$i] - $LISTIDlist_names[$i]");while(strlen($LISTIDname)>40) {$LISTIDname = substr("$LISTIDname", 0, -1);} $totalOUToutput .= "| $LISTIDname | $LISTIDcount | $active_txt |\n"; $CSV_textSUMMARY.="\"$LISTIDname\",\"$LISTIDcount\",\"$active_txt\"\n"; $OUToutput .= "\n"; $OUToutput .= "---------- LIST ID SUMMARY <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=1\">DOWNLOAD LIST SUMMARIES</a>\n"; $OUToutput .= "+--------------------------------------------------------+\n"; $OUToutput .= "| LIST ID: ".sprintf("%-30s", $list_row[0])." ".sprintf("%-8s", $active_txt)." |\n"; $OUToutput .= "| LIST NAME: ".sprintf("%-30s", $list_row[1])." ".sprintf("%8s", "")." |\n"; $OUToutput .= "| TOTAL LEADS: ".sprintf("%-30s", $list_row[3])." ".sprintf("%8s", "")." |\n"; $OUToutput .= "+--------------------------------------------------------+\n"; $CSV_text1.="\"$list_row[0]\",\"$list_row[1]\",\"$list_row[3]\",\"$active_txt\"\n"; $CSV_textALL.="\"LIST ID #$list_row[0] SUMMARY\",\"\"\n"; $CSV_textALL.="\"LIST NAME\",\"TOTAL LEADS\",\"ACTIVE/INACTIVE\"\n"; $CSV_textALL.="\"$list_row[1]\",\"$list_row[3]\",\"$active_txt\"\n"; # $list_id_SQL .= "'$row[0]',"; # if ($row[0]>$max_calls) {$max_calls=$row[3];} $i++; $list_id=$list_row[0]; ############################## ######### STATUS FLAGS STATS $HA_count=0; $HA_percent=0; $SALE_count=0; $SALE_percent=0; $DNC_count=0; $DNC_percent=0; $CC_count=0; $CC_percent=0; $NI_count=0; $NI_percent=0; $UW_count=0; $UW_percent=0; $SC_count=0; $SC_percent=0; $COMP_count=0; $COMP_percent=0; $stmt="select count(*) from vicidial_list where status IN($human_answered_statuses) and list_id='$list_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $HA_results = mysqli_num_rows($rslt); if ($HA_results > 0) { $row=mysqli_fetch_row($rslt); $HA_count = $row[0]; $flag_count+=$row[0]; $category_totals["HA"]+=$HA_count; if ($HA_count>$max_calls) {$max_calls=$HA_count;} $HA_percent = ( MathZDC($HA_count, $TOTALleads) * 100); } $stmt="select count(*) from vicidial_list where status IN($sale_statuses) and list_id='$list_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $SALE_results = mysqli_num_rows($rslt); if ($SALE_results > 0) { $row=mysqli_fetch_row($rslt); $SALE_count = $row[0]; $flag_count+=$row[0]; $category_totals["SALE"]+=$SALE_count; if ($SALE_count>$max_calls) {$max_calls=$SALE_count;} $SALE_percent = ( MathZDC($SALE_count, $TOTALleads) * 100); } $stmt="select count(*) from vicidial_list where status IN($dnc_statuses) and list_id='$list_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $DNC_results = mysqli_num_rows($rslt); if ($DNC_results > 0) { $row=mysqli_fetch_row($rslt); $DNC_count = $row[0]; $flag_count+=$row[0]; $category_totals["DNC"]+=$DNC_count; if ($DNC_count>$max_calls) {$max_calls=$DNC_count;} $DNC_percent = ( MathZDC($DNC_count, $TOTALleads) * 100); } $stmt="select count(*) from vicidial_list where status IN($customer_contact_statuses) and list_id='$list_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $CC_results = mysqli_num_rows($rslt); if ($CC_results > 0) { $row=mysqli_fetch_row($rslt); $CC_count = $row[0]; $flag_count+=$row[0]; $category_totals["CC"]+=$CC_count; if ($C_count>$max_calls) {$max_calls=$CC_count;} $CC_percent = ( MathZDC($CC_count, $TOTALleads) * 100); } $stmt="select count(*) from vicidial_list where status IN($not_interested_statuses) and list_id='$list_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $NI_results = mysqli_num_rows($rslt); if ($NI_results > 0) { $row=mysqli_fetch_row($rslt); $NI_count = $row[0]; $flag_count+=$row[0]; $category_totals["NI"]+=$NI_count; if ($NI_count>$max_calls) {$max_calls=$NI_count;} $NI_percent = ( MathZDC($NI_count, $TOTALleads) * 100); } $stmt="select count(*) from vicidial_list where status IN($unworkable_statuses) and list_id='$list_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $UW_results = mysqli_num_rows($rslt); if ($UW_results > 0) { $row=mysqli_fetch_row($rslt); $UW_count = $row[0]; $flag_count+=$row[0]; $category_totals["UW"]+=$UW_count; if ($UW_count>$max_calls) {$max_calls=$UW_count;} $UW_percent = ( MathZDC($UW_count, $TOTALleads) * 100); } $stmt="select count(*) from vicidial_list where status IN($scheduled_callback_statuses) and list_id='$list_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $SC_results = mysqli_num_rows($rslt); if ($SC_results > 0) { $row=mysqli_fetch_row($rslt); $SC_count = $row[0]; $flag_count+=$row[0]; $category_totals["SC"]+=$SC_count; if ($SC_count>$max_calls) {$max_calls=$SC_count;} $SC_percent = ( MathZDC($SC_count, $TOTALleads) * 100); } $stmt="select count(*) from vicidial_list where status IN($completed_statuses) and list_id='$list_id';"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $COMP_results = mysqli_num_rows($rslt); if ($COMP_results > 0) { $row=mysqli_fetch_row($rslt); $COMP_count = $row[0]; $flag_count+=$row[0]; $category_totals["COMP"]+=$COMP_count; if ($COMP_count>$max_calls) {$max_calls=$COMP_count;} $COMP_percent = ( MathZDC($COMP_count, $TOTALleads) * 100); } $HA_percent = sprintf("%6.2f", "$HA_percent"); while(strlen($HA_percent)>6) {$HA_percent = substr("$HA_percent", 0, -1);} $SALE_percent = sprintf("%6.2f", "$SALE_percent"); while(strlen($SALE_percent)>6) {$SALE_percent = substr("$SALE_percent", 0, -1);} $DNC_percent = sprintf("%6.2f", "$DNC_percent"); while(strlen($DNC_percent)>6) {$DNC_percent = substr("$DNC_percent", 0, -1);} $CC_percent = sprintf("%6.2f", "$CC_percent"); while(strlen($CC_percent)>6) {$CC_percent = substr("$CC_percent", 0, -1);} $NI_percent = sprintf("%6.2f", "$NI_percent"); while(strlen($NI_percent)>6) {$NI_percent = substr("$NI_percent", 0, -1);} $UW_percent = sprintf("%6.2f", "$UW_percent"); while(strlen($UW_percent)>6) {$UW_percent = substr("$UW_percent", 0, -1);} $SC_percent = sprintf("%6.2f", "$SC_percent"); while(strlen($SC_percent)>6) {$SC_percent = substr("$SC_percent", 0, -1);} $COMP_percent = sprintf("%6.2f", "$COMP_percent"); while(strlen($COMP_percent)>6) {$COMP_percent = substr("$COMP_percent", 0, -1);} $HA_count = sprintf("%10s", "$HA_count"); while(strlen($HA_count)>10) {$HA_count = substr("$HA_count", 0, -1);} $SALE_count = sprintf("%10s", "$SALE_count"); while(strlen($SALE_count)>10) {$SALE_count = substr("$SALE_count", 0, -1);} $DNC_count = sprintf("%10s", "$DNC_count"); while(strlen($DNC_count)>10) {$DNC_count = substr("$DNC_count", 0, -1);} $CC_count = sprintf("%10s", "$CC_count"); while(strlen($CC_count)>10) {$CC_count = substr("$CC_count", 0, -1);} $NI_count = sprintf("%10s", "$NI_count"); while(strlen($NI_count)>10) {$NI_count = substr("$NI_count", 0, -1);} $UW_count = sprintf("%10s", "$UW_count"); while(strlen($UW_count)>10) {$UW_count = substr("$UW_count", 0, -1);} $SC_count = sprintf("%10s", "$SC_count"); while(strlen($SC_count)>10) {$SC_count = substr("$SC_count", 0, -1);} $COMP_count = sprintf("%10s", "$COMP_count"); while(strlen($COMP_count)>10) {$COMP_count = substr("$COMP_count", 0, -1);} $OUToutput .= "\n"; $OUToutput .= "---------- STATUS FLAGS BREAKDOWN: (and % of total leads in list) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=2\">DOWNLOAD FLAG BREAKDOWNS</a>\n"; $OUToutput .= "+------------------+------------+----------+\n"; $OUToutput .= "| Human Answer | $HA_count | $HA_percent% |\n"; $OUToutput .= "| Sale | $SALE_count | $SALE_percent% |\n"; $OUToutput .= "| DNC | $DNC_count | $DNC_percent% |\n"; $OUToutput .= "| Customer Contact | $CC_count | $CC_percent% |\n"; $OUToutput .= "| Not Interested | $NI_count | $NI_percent% |\n"; $OUToutput .= "| Unworkable | $UW_count | $UW_percent% |\n"; $OUToutput .= "| Sched Callbacks | $SC_count | $SC_percent% |\n"; $OUToutput .= "| Completed | $COMP_count | $COMP_percent% |\n"; $OUToutput .= "+------------------+------------+----------+\n"; $OUToutput .= "\n"; $CSV_text_block = "\"STATUS FLAGS SUMMARY FOR LIST ID #$list_id:\"\n"; $CSV_text_block .= "\"Human Answer\",\"$HA_count\",\"$HA_percent%\"\n"; $CSV_text_block .= "\"Sale\",\"$SALE_count\",\"$SALE_percent%\"\n"; $CSV_text_block .= "\"DNC\",\"$DNC_count\",\"$DNC_percent%\"\n"; $CSV_text_block .= "\"Customer Contact\",\"$CC_count\",\"$CC_percent%\"\n"; $CSV_text_block .= "\"Not Interested\",\"$NI_count\",\"$NI_percent%\"\n"; $CSV_text_block .= "\"Unworkable\",\"$UW_count\",\"$UW_percent%\"\n"; $CSV_text_block .= "\"Scheduled Callbacks\",\"$SC_count\",\"$SC_percent%\"\n"; $CSV_text_block .= "\"Completed\",\"$COMP_count\",\"$COMP_percent%\"\n\n"; $CSV_text2.=$CSV_text_block; $CSV_textALL.="\n".$CSV_text_block; $stmt="select status, count(*) From vicidial_list where list_id='$list_id' group by status order by status asc"; $rslt=mysql_to_mysqli($stmt, $link); if ($DB) {$MAIN.="$stmt\n";} $OUToutput .= "---------- STATUS BREAKDOWN: (and % of total leads in list) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=3\">DOWNLOAD STAT BREAKDOWNS</a>\n"; $OUToutput .= "+--------+--------------------------------+----------+---------+\n"; $OUToutput .= "| STATUS | STATUS NAME | COUNT | LEAD % |\n"; $OUToutput .= "+--------+--------------------------------+----------+---------+\n"; $CSV_text3.="\"\",\"STATUS BREAKDOWN FOR LIST ID #$list_id:\"\n"; $CSV_text3.="\"STATUS\",\"STATUS NAME\",\"COUNT\",\"LEAD %\"\n"; $CSV_textALL.="\"STATUS BREAKDOWN FOR LIST ID #$list_id:\",\"\"\n"; $CSV_textALL.="\"STATUS\",\"STATUS NAME\",\"COUNT\",\"LEAD %\"\n"; while ($row=mysqli_fetch_row($rslt)) { $OUToutput .= "| ".sprintf("%6s", $row[0])." | ".sprintf("%30s", $statname_list["$row[0]"])." | ".sprintf("%8s", $row[1])." | ".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."% |\n"; $CSV_text3.="\"$row[0]\",\"".$statname_list["$row[0]"]."\",\"$row[1]\",\"".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."%\"\n"; $CSV_textALL.="\"$row[0]\",\"".$statname_list["$row[0]"]."\",\"$row[1]\",\"".sprintf("%6.2f", ( MathZDC($row[1], $TOTALleads) * 100))."%\"\n"; } $OUToutput .= "+-----------------------------------------+----------+---------+\n"; $OUToutput .= "| | ".sprintf("%8s", $TOTALleads)." | 100.00% |\n"; $OUToutput .= "+-----------------------------------------+----------+---------+\n"; $CSV_text3.="\"\",\"\",\"$TOTALleads\",\"100.00%\"\n\n\n"; $CSV_textALL.="\"\",\"\",\"$TOTALleads\",\"100.00%\"\n\n\n"; $OUToutput .= "\n"; $OUToutput .= "\n"; $OUToutput .= "\n"; } $total_HA_percent = sprintf("%6.2f", ( MathZDC($category_totals["HA"], $totalTOTALleads) * 100)); while(strlen($total_HA_percent)>6) {$total_HA_percent = substr("$total_HA_percent", 0, -1);} $total_SALE_percent = sprintf("%6.2f", ( MathZDC($category_totals["SALE"], $totalTOTALleads) * 100)); while(strlen($total_SALE_percent)>6) {$total_SALE_percent = substr("$total_SALE_percent", 0, -1);} $total_DNC_percent = sprintf("%6.2f", ( MathZDC($category_totals["DNC"], $totalTOTALleads) * 100)); while(strlen($total_DNC_percent)>6) {$total_DNC_percent = substr("$total_DNC_percent", 0, -1);} $total_CC_percent = sprintf("%6.2f", ( MathZDC($category_totals["CC"], $totalTOTALleads) * 100)); while(strlen($total_CC_percent)>6) {$total_CC_percent = substr("$total_CC_percent", 0, -1);} $total_NI_percent = sprintf("%6.2f", ( MathZDC($category_totals["NI"], $totalTOTALleads) * 100)); while(strlen($total_NI_percent)>6) {$total_NI_percent = substr("$total_NI_percent", 0, -1);} $total_UW_percent = sprintf("%6.2f", ( MathZDC($category_totals["UW"], $totalTOTALleads) * 100)); while(strlen($total_UW_percent)>6) {$total_UW_percent = substr("$total_UW_percent", 0, -1);} $total_SC_percent = sprintf("%6.2f", ( MathZDC($category_totals["SC"], $totalTOTALleads) * 100)); while(strlen($total_SC_percent)>6) {$total_SC_percent = substr("$total_SC_percent", 0, -1);} $total_COMP_percent = sprintf("%6.2f", ( MathZDC($category_totals["COMP"], $totalTOTALleads) * 100)); while(strlen($total_COMP_percent)>6) {$total_COMP_percent = substr("$total_COMP_percent", 0, -1);} $total_HA_count = sprintf("%10s", $category_totals["HA"]); while(strlen($total_HA_count)>10) {$total_HA_count = substr("$total_HA_count", 0, -1);} $total_SALE_count = sprintf("%10s", $category_totals["SALE"]); while(strlen($total_SALE_count)>10) {$total_SALE_count = substr("$total_SALE_count", 0, -1);} $total_DNC_count = sprintf("%10s", $category_totals["DNC"]); while(strlen($total_DNC_count)>10) {$total_DNC_count = substr("$total_DNC_count", 0, -1);} $total_CC_count = sprintf("%10s", $category_totals["CC"]); while(strlen($total_CC_count)>10) {$total_CC_count = substr("$total_CC_count", 0, -1);} $total_NI_count = sprintf("%10s", $category_totals["NI"]); while(strlen($total_NI_count)>10) {$total_NI_count = substr("$total_NI_count", 0, -1);} $total_UW_count = sprintf("%10s", $category_totals["UW"]); while(strlen($total_UW_count)>10) {$total_UW_count = substr("$total_UW_count", 0, -1);} $total_SC_count = sprintf("%10s", $category_totals["SC"]); while(strlen($total_SC_count)>10) {$total_SC_count = substr("$total_SC_count", 0, -1);} $total_COMP_count = sprintf("%10s", $category_totals["COMP"]); while(strlen($total_COMP_count)>10) {$total_COMP_count = substr("$total_COMP_count", 0, -1);} $totalOUToutput .= "+------------------------------------------+------------+----------+\n"; $totalOUToutput .= "| TOTAL | ".sprintf("%10s", $totalTOTALleads)." |\n"; $totalOUToutput .= "+------------------------------------------+------------+\n"; $CSV_textSUMMARY .= "\"TOTAL\",\"$totalTOTALleads\"\n"; $totalOUToutput .= "\n"; $totalOUToutput .= "\n"; $totalOUToutput .= "---------- TOTAL STATUS FLAGS SUMMARY: (and % of leads in selected lists) <a href=\"$PHP_SELF?DB=$DB$listQS&SUBMIT=$SUBMIT&file_download=ALL\">DOWNLOAD FULL REPORT</a>\n"; $totalOUToutput .= "+------------------+------------+----------+\n"; $totalOUToutput .= "| Human Answer | $total_HA_count | $total_HA_percent% |\n"; $totalOUToutput .= "| Sale | $total_SALE_count | $total_SALE_percent% |\n"; $totalOUToutput .= "| DNC | $total_DNC_count | $total_DNC_percent% |\n"; $totalOUToutput .= "| Customer Contact | $total_CC_count | $total_CC_percent% |\n"; $totalOUToutput .= "| Not Interested | $total_NI_count | $total_NI_percent% |\n"; $totalOUToutput .= "| Unworkable | $total_UW_count | $total_UW_percent% |\n"; $totalOUToutput .= "| Sched Callbacks | $total_SC_count | $total_SC_percent% |\n"; $totalOUToutput .= "| Completed | $total_COMP_count | $total_COMP_percent% |\n"; $totalOUToutput .= "+------------------+------------+----------+\n"; $totalOUToutput .= "\n\n\n"; $CSV_textSUMMARY .= "\n\"STATUS FLAGS SUMMARY:\"\n"; $CSV_textSUMMARY .= "\"Human Answer\",\"$total_HA_count\",\"$total_HA_percent%\"\n"; $CSV_textSUMMARY .= "\"Sale\",\"$total_SALE_count\",\"$total_SALE_percent%\"\n"; $CSV_textSUMMARY .= "\"DNC\",\"$total_DNC_count\",\"$total_DNC_percent%\"\n"; $CSV_textSUMMARY .= "\"Customer Contact\",\"$total_CC_count\",\"$total_CC_percent%\"\n"; $CSV_textSUMMARY .= "\"Not Interested\",\"$total_NI_count\",\"$total_NI_percent%\"\n"; $CSV_textSUMMARY .= "\"Unworkable\",\"$total_UW_count\",\"$total_UW_percent%\"\n"; $CSV_textSUMMARY .= "\"Scheduled Callbacks\",\"$total_SC_count\",\"$total_SC_percent%\"\n"; $CSV_textSUMMARY .= "\"Completed\",\"$total_COMP_count\",\"$total_COMP_percent%\"\n\n\n\n"; $CSV_textALL=$CSV_textSUMMARY.$CSV_textALL; if ($report_display_type=="HTML") { $MAIN.=$GRAPH; } else { $MAIN.="$totalOUToutput$OUToutput"; } $ENDtime = date("U"); $RUNtime = ($ENDtime - $STARTtime); $MAIN.="\nRun Time: $RUNtime seconds|$db_source\n"; $MAIN.="</PRE>\n"; $MAIN.="</TD></TR></TABLE>\n"; $MAIN.="</BODY></HTML>\n"; } if ($file_download>0 || $file_download=="ALL") { $FILE_TIME = date("Ymd-His"); $CSVfilename = "AST_LISTS_stats_$US$FILE_TIME.csv"; $CSV_var="CSV_text".$file_download; $CSV_text=preg_replace('/^ +/', '', $$CSV_var); $CSV_text=preg_replace('/\n +,/', ',', $CSV_text); $CSV_text=preg_replace('/ +\"/', '"', $CSV_text); $CSV_text=preg_replace('/\" +/', '"', $CSV_text); // We'll be outputting a TXT file header('Content-type: application/octet-stream'); // It will be called LIST_101_20090209-121212.txt header("Content-Disposition: attachment; filename=\"$CSVfilename\""); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); ob_clean(); flush(); echo "$CSV_text"; } else { $JS_onload.="}\n"; $JS_text.=$JS_onload; $JS_text.="</script>\n"; echo $HEADER; echo $JS_text; require("admin_header.php"); echo $MAIN; } if ($db_source == 'S') { mysqli_close($link); $use_slave_server=0; $db_source = 'M'; require("dbconnect.php"); } $endMS = microtime(); $startMSary = explode(" ",$startMS); $endMSary = explode(" ",$endMS); $runS = ($endMSary[0] - $startMSary[0]); $runM = ($endMSary[1] - $startMSary[1]); $TOTALrun = ($runS + $runM); $stmt="UPDATE vicidial_report_log set run_time='$TOTALrun' where report_log_id='$report_log_id';"; if ($DB) {echo "|$stmt|\n";} $rslt=mysql_to_mysqli($stmt, $link); exit; ?>
patrickcmartins/goautodialtraduzido
vicidial/AST_LISTS_stats.php
PHP
agpl-3.0
37,059
package org.cbioportal.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.cbioportal.model.AlterationCountByGene; import org.cbioportal.model.AlterationEnrichment; import org.cbioportal.model.CopyNumberCountByGene; import org.cbioportal.model.MolecularProfileCaseIdentifier; import org.cbioportal.service.CopyNumberEnrichmentService; import org.cbioportal.service.DiscreteCopyNumberService; import org.cbioportal.service.exception.MolecularProfileNotFoundException; import org.cbioportal.service.util.AlterationEnrichmentUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CopyNumberEnrichmentServiceImpl implements CopyNumberEnrichmentService { @Autowired private DiscreteCopyNumberService discreteCopyNumberService; @Autowired private AlterationEnrichmentUtil alterationEnrichmentUtil; @Override public List<AlterationEnrichment> getCopyNumberEnrichments( Map<String, List<MolecularProfileCaseIdentifier>> molecularProfileCaseSets, List<Integer> alterationTypes, String enrichmentType) throws MolecularProfileNotFoundException { Map<String, List<? extends AlterationCountByGene>> copyNumberCountByGeneAndGroup = new HashMap<>(); if (enrichmentType.equals("SAMPLE")) { copyNumberCountByGeneAndGroup = molecularProfileCaseSets .entrySet() .stream() .collect(Collectors.toMap( entry -> entry.getKey(), entry -> { //set value of each group to list of CopyNumberCountByGene List<String> molecularProfileIds = new ArrayList<>(); List<String> sampleIds = new ArrayList<>(); entry.getValue().forEach(molecularProfileCase -> { molecularProfileIds.add(molecularProfileCase.getMolecularProfileId()); sampleIds.add(molecularProfileCase.getCaseId()); }); return discreteCopyNumberService .getSampleCountInMultipleMolecularProfiles( molecularProfileIds, sampleIds, null, alterationTypes, false); })); } else { copyNumberCountByGeneAndGroup = molecularProfileCaseSets.entrySet().stream() .collect(Collectors.toMap( entry -> entry.getKey(), entry -> { //set value of each group to list of CopyNumberCountByGene Map<String, List<MolecularProfileCaseIdentifier>> molecularProfileCaseIdentifiersMap = entry .getValue().stream() .collect(Collectors.groupingBy(MolecularProfileCaseIdentifier::getMolecularProfileId)); return molecularProfileCaseIdentifiersMap .entrySet() .stream() .flatMap(molecularProfileCaseIdentifiers -> { String molecularProfileId = molecularProfileCaseIdentifiers.getKey(); List<String> caseIds = molecularProfileCaseIdentifiers .getValue() .stream() .map(MolecularProfileCaseIdentifier::getCaseId) .collect(Collectors.toList()); return discreteCopyNumberService .getPatientCountByGeneAndAlterationAndPatientIds( molecularProfileId, caseIds, null, alterationTypes) .stream(); }) .collect(Collectors.toList()); })); } return alterationEnrichmentUtil .createAlterationEnrichments( copyNumberCountByGeneAndGroup, molecularProfileCaseSets, enrichmentType); } }
d3b-center/pedcbioportal
service/src/main/java/org/cbioportal/service/impl/CopyNumberEnrichmentServiceImpl.java
Java
agpl-3.0
5,177
# - coding: utf-8 -*- ############################################################################## # # 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/>. # ############################################################################## import models # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
odoo-arg/odoo_l10n_ar
l10n_ar/wizard/__init__.py
Python
agpl-3.0
951
//package com.x.processplatform.assemble.designer.jaxrs.projection; // //import com.x.base.core.container.EntityManagerContainer; //import com.x.base.core.container.factory.EntityManagerContainerFactory; //import com.x.base.core.project.exception.ExceptionAccessDenied; //import com.x.base.core.project.exception.ExceptionEntityNotExist; //import com.x.base.core.project.http.ActionResult; //import com.x.base.core.project.http.EffectivePerson; //import com.x.base.core.project.jaxrs.WrapBoolean; //import com.x.processplatform.assemble.designer.Business; //import com.x.processplatform.core.entity.element.Application; //import com.x.processplatform.core.entity.element.Projection; // //class ActionEnable extends BaseAction { // // ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception { // try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { // ActionResult<Wo> result = new ActionResult<>(); // // Business business = new Business(emc); // // Projection projection = emc.flag(flag, Projection.class); // // if (null == projection) { // throw new ExceptionEntityNotExist(flag, Projection.class); // } // // Application application = emc.flag(projection.getApplication(), Application.class); // // if (null == application) { // throw new ExceptionEntityNotExist(projection.getApplication(), Application.class); // } // // if (!business.editable(effectivePerson, application)) { // throw new ExceptionAccessDenied(effectivePerson.getDistinguishedName()); // } // // emc.beginTransaction(Projection.class); // projection.setEnable(true); // emc.commit(); // Wo wo = new Wo(); // wo.setValue(true); // result.setData(wo); // return result; // } // } // // public static class Wo extends WrapBoolean { // // } // //}
o2oa/o2oa
o2server/x_processplatform_assemble_designer/src/main/java/com/x/processplatform/assemble/designer/jaxrs/projection/ActionEnable.java
Java
agpl-3.0
1,828
define("imcms-templates-tab-builder", [ "imcms-bem-builder", "imcms-components-builder", "imcms-templates-rest-api", "imcms-document-types", "imcms-i18n-texts", "imcms-page-info-tab" ], function (BEM, components, templatesRestApi, docTypes, texts, PageInfoTab) { texts = texts.pageInfo.appearance; const tabData = {}; const TemplatesTab = function (name, docType) { PageInfoTab.apply(this, arguments); }; TemplatesTab.prototype = Object.create(PageInfoTab.prototype); TemplatesTab.prototype.tabElementsFactory = () => { const $templateSelectContainer = components.selects.selectContainer("<div>", { name: "template", text: texts.template }), $templateSelect = $templateSelectContainer.getSelect(), $defaultChildTemplateSelectContainer = components.selects.selectContainer("<div>", { name: "childTemplate", text: texts.defaultChildTemplate }), $defaultChildTemplateSelect = $defaultChildTemplateSelectContainer.getSelect(); tabData.$templateSelect = $templateSelect; tabData.$defaultChildTemplateSelect = $defaultChildTemplateSelect; templatesRestApi.read(null) .done(templates => { const templatesDataMapped = templates.map(template => ({ text: template.name, "data-value": template.name })); components.selects.addOptionsToSelect(templatesDataMapped, $templateSelect); components.selects.addOptionsToSelect(templatesDataMapped, $defaultChildTemplateSelect); }); return [ $templateSelectContainer, $defaultChildTemplateSelectContainer ]; }; TemplatesTab.prototype.fillTabDataFromDocument = document => { if (document.template) { tabData.$templateSelect.selectValue(document.template.templateName); tabData.$defaultChildTemplateSelect.selectValue(document.template.childrenTemplateName); } }; TemplatesTab.prototype.saveData = function (documentDTO) { if (!this.isDocumentTypeSupported(documentDTO.type)) { return documentDTO; } documentDTO.template.templateName = tabData.$templateSelect.getSelectedValue(); documentDTO.template.childrenTemplateName = tabData.$defaultChildTemplateSelect.getSelectedValue(); return documentDTO; }; TemplatesTab.prototype.clearTabData = () => { tabData.$templateSelect.selectFirst(); tabData.$defaultChildTemplateSelect.selectFirst(); }; return new TemplatesTab(texts.name, docTypes.TEXT); } );
imCodePartnerAB/imcms
src/main/webapp/imcms/js/builders/components/page_info_tabs/imcms-templates-tab-builder.js
JavaScript
agpl-3.0
2,976
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ import { CSS, React } from "smc-webapp/app-framework"; import { FOCUSED_COLOR } from "../util"; import { SlateElement, register, useFocused, useSelected, useSlateStatic, } from "./register"; export interface Hashtag extends SlateElement { type: "hashtag"; content: string; } // Looks like antd tag but scales (and a lot simpler). const STYLE = { padding: "0 7px", color: "#1b95e0", borderRadius: "5px", cursor: "pointer", } as CSS; register({ slateType: "hashtag", fromSlate: ({ node }) => `#${node.content}`, Element: ({ attributes, children, element }) => { if (element.type != "hashtag") throw Error("bug"); const focused = useFocused(); const selected = useSelected(); const editor = useSlateStatic(); const border = focused && selected ? `1px solid ${FOCUSED_COLOR}` : "1px solid #d9d9d9"; const backgroundColor = focused && selected ? "#1990ff" : "#fafafa"; const color = focused && selected ? "white" : undefined; return ( <span {...attributes}> <span style={{ ...STYLE, border, backgroundColor, color }} onClick={() => editor.search.focus("#" + element.content)} > #{element.content} </span> {children} </span> ); }, toSlate: ({ token }) => { return { type: "hashtag", isVoid: true, isInline: true, content: token.content, children: [{ text: " " }], markup: token.markup, }; }, });
sagemathinc/smc
src/smc-webapp/editors/slate/elements/hashtag.tsx
TypeScript
agpl-3.0
1,639
<?php App::uses('AppModel', 'Model'); class Galaxy extends AppModel { public $useTable = 'galaxies'; public $recursive = -1; public $actsAs = array( 'Containable', ); public $validate = array( ); public $hasMany = array( 'GalaxyCluster' => array('dependent' => true) ); public function beforeValidate($options = array()) { parent::beforeValidate(); return true; } public function beforeDelete($cascade = true) { $this->GalaxyCluster->deleteAll(array('GalaxyCluster.galaxy_id' => $this->id)); } private function __load_galaxies($force = false) { $dir = new Folder(APP . 'files' . DS . 'misp-galaxy' . DS . 'galaxies'); $files = $dir->find('.*\.json'); $galaxies = array(); foreach ($files as $file) { $file = new File($dir->pwd() . DS . $file); $galaxies[] = json_decode($file->read(), true); $file->close(); } $galaxyTypes = array(); foreach ($galaxies as $galaxy) { $galaxyTypes[$galaxy['type']] = $galaxy['type']; } $temp = $this->find('all', array( 'fields' => array('uuid', 'version', 'id', 'icon'), 'recursive' => -1 )); $existingGalaxies = array(); foreach ($temp as $k => $v) { $existingGalaxies[$v['Galaxy']['uuid']] = $v['Galaxy']; } foreach ($galaxies as $k => $galaxy) { if (isset($existingGalaxies[$galaxy['uuid']])) { if ( $force || $existingGalaxies[$galaxy['uuid']]['version'] < $galaxy['version'] || (!empty($galaxy['icon']) && ($existingGalaxies[$galaxy['uuid']]['icon'] != $galaxy['icon'])) ) { $galaxy['id'] = $existingGalaxies[$galaxy['uuid']]['id']; $this->save($galaxy); } } else { $this->create(); $this->save($galaxy); } } return $this->find('list', array('recursive' => -1, 'fields' => array('type', 'id'))); } public function update($force = false) { $galaxies = $this->__load_galaxies($force); $dir = new Folder(APP . 'files' . DS . 'misp-galaxy' . DS . 'clusters'); $files = $dir->find('.*\.json'); $cluster_packages = array(); foreach ($files as $file) { $file = new File($dir->pwd() . DS . $file); $cluster_package = json_decode($file->read(), true); $file->close(); if (!isset($galaxies[$cluster_package['type']])) { continue; } $template = array( 'source' => isset($cluster_package['source']) ? $cluster_package['source'] : '', 'authors' => json_encode(isset($cluster_package['authors']) ? $cluster_package['authors'] : array(), true), 'collection_uuid' => isset($cluster_package['uuid']) ? $cluster_package['uuid'] : '', 'galaxy_id' => $galaxies[$cluster_package['type']], 'type' => $cluster_package['type'], 'tag_name' => 'misp-galaxy:' . $cluster_package['type'] . '="' ); $elements = array(); $temp = $this->GalaxyCluster->find('all', array( 'conditions' => array( 'GalaxyCluster.galaxy_id' => $galaxies[$cluster_package['type']] ), 'recursive' => -1, 'fields' => array('version', 'id', 'value', 'uuid') )); $existingClusters = array(); foreach ($temp as $k => $v) { $existingClusters[$v['GalaxyCluster']['value']] = $v; } $clusters_to_delete = array(); // Delete all existing outdated clusters foreach ($cluster_package['values'] as $k => $cluster) { if (empty($cluster['value'])) { continue; } if (isset($cluster['version'])) { } elseif (!empty($cluster_package['version'])) { $cluster_package['values'][$k]['version'] = $cluster_package['version']; } else { $cluster_package['values'][$k]['version'] = 0; } if (!empty($existingClusters[$cluster['value']])) { if ($force || $existingClusters[$cluster['value']]['GalaxyCluster']['version'] < $cluster_package['values'][$k]['version']) { $clusters_to_delete[] = $existingClusters[$cluster['value']]['GalaxyCluster']['id']; } else { unset($cluster_package['values'][$k]); } } } if (!empty($clusters_to_delete)) { $this->GalaxyCluster->GalaxyElement->deleteAll(array('GalaxyElement.galaxy_cluster_id' => $clusters_to_delete), false, false); $this->GalaxyCluster->delete($clusters_to_delete, false, false); } // create all clusters foreach ($cluster_package['values'] as $cluster) { if (empty($cluster['version'])) { $cluster['version'] = 1; } $template['version'] = $cluster['version']; $this->GalaxyCluster->create(); $cluster_to_save = $template; if (isset($cluster['description'])) { $cluster_to_save['description'] = $cluster['description']; unset($cluster['description']); } $cluster_to_save['value'] = $cluster['value']; $cluster_to_save['tag_name'] = $cluster_to_save['tag_name'] . $cluster['value'] . '"'; if (!empty($cluster['uuid'])) { $cluster_to_save['uuid'] = $cluster['uuid']; } unset($cluster['value']); if (empty($cluster_to_save['description'])) { $cluster_to_save['description'] = ''; } $result = $this->GalaxyCluster->save($cluster_to_save, false); $galaxyClusterId = $this->GalaxyCluster->id; if (isset($cluster['meta'])) { foreach ($cluster['meta'] as $key => $value) { if (is_array($value)) { foreach ($value as $v) { $elements[] = array( $galaxyClusterId, $key, $v ); } } else { $elements[] = array( $this->GalaxyCluster->id, $key, $value ); } } } } $db = $this->getDataSource(); $fields = array('galaxy_cluster_id', 'key', 'value'); if (!empty($elements)) { $db->insertMulti('galaxy_elements', $fields, $elements); } } return true; } private function __attachClusterToEvent($user, $target_id, $cluster_id) { } public function attachCluster($user, $target_type, $target_id, $cluster_id) { $connectorModel = Inflector::camelize($target_type) . 'Tag'; $cluster = $this->GalaxyCluster->find('first', array('recursive' => -1, 'conditions' => array('id' => $cluster_id), 'fields' => array('tag_name', 'id', 'value'))); $this->Tag = ClassRegistry::init('Tag'); if ($target_type === 'event') { $target = $this->Tag->EventTag->Event->fetchEvent($user, array('eventid' => $target_id, 'metadata' => 1)); } elseif ($target_type === 'attribute') { $target = $this->Tag->AttributeTag->Attribute->fetchAttributes($user, array('conditions' => array('Attribute.id' => $target_id), 'flatten' => 1)); } elseif ($target_type === 'tag_collection') { $target = $this->Tag->TagCollectionTag->TagCollection->fetchTagCollection($user, array('conditions' => array('TagCollection.id' => $target_id))); } if (empty($target)) { throw new NotFoundException(__('Invalid %s.', $target_type)); } $target = $target[0]; $tag_id = $this->Tag->captureTag(array('name' => $cluster['GalaxyCluster']['tag_name'], 'colour' => '#0088cc', 'exportable' => 1), $user); $existingTag = $this->Tag->$connectorModel->find('first', array('conditions' => array($target_type . '_id' => $target_id, 'tag_id' => $tag_id))); if (!empty($existingTag)) { return 'Cluster already attached.'; } $this->Tag->$connectorModel->create(); $toSave = array($target_type . '_id' => $target_id, 'tag_id' => $tag_id); if ($target_type === 'attribute') { $event = $this->Tag->EventTag->Event->find('first', array( 'conditions' => array( 'Event.id' => $target['Attribute']['event_id'] ), 'recursive' => -1 )); $toSave['event_id'] = $target['Attribute']['event_id']; } $result = $this->Tag->$connectorModel->save($toSave); if ($result) { if ($target_type !== 'tag_collection') { if ($target_type === 'event') { $event = $target; } $this->Tag->EventTag->Event->insertLock($user, $event['Event']['id']); $event['Event']['published'] = 0; $date = new DateTime(); $event['Event']['timestamp'] = $date->getTimestamp(); $this->Tag->EventTag->Event->save($event); } $this->Log = ClassRegistry::init('Log'); $this->Log->create(); $this->Log->save(array( 'org' => $user['Organisation']['name'], 'model' => ucfirst($target_type), 'model_id' => $target_id, 'email' => $user['email'], 'action' => 'galaxy', 'title' => 'Attached ' . $cluster['GalaxyCluster']['value'] . ' (' . $cluster['GalaxyCluster']['id'] . ') to ' . $target_type . ' (' . $target_id . ')', 'change' => '' )); return 'Cluster attached.'; } return 'Could not attach the cluster'; } public function detachCluster($user, $target_type, $target_id, $cluster_id) { $cluster = $this->GalaxyCluster->find('first', array( 'recursive' => -1, 'conditions' => array('id' => $cluster_id), 'fields' => array('tag_name', 'id', 'value') )); $this->Tag = ClassRegistry::init('Tag'); if ($target_type === 'event') { $target = $this->Tag->EventTag->Event->fetchEvent($user, array('eventid' => $target_id, 'metadata' => 1)); if (empty($target)) { throw new NotFoundException(__('Invalid %s.', $target_type)); } $target = $target[0]; $event = $target; $event_id = $target['Event']['id']; $org_id = $event['Event']['org_id']; $orgc_id = $event['Event']['orgc_id']; } elseif ($target_type === 'attribute') { $target = $this->Tag->AttributeTag->Attribute->fetchAttributes($user, array('conditions' => array('Attribute.id' => $target_id), 'flatten' => 1)); if (empty($target)) { throw new NotFoundException(__('Invalid %s.', $target_type)); } $target = $target[0]; $event_id = $target['Attribute']['event_id']; $event = $this->Tag->EventTag->Event->fetchEvent($user, array('eventid' => $event_id, 'metadata' => 1)); if (empty($event)) { throw new NotFoundException(__('Invalid event')); } $event = $event[0]; $org_id = $event['Event']['org_id']; $orgc_id = $event['Event']['org_id']; } elseif ($target_type === 'tag_collection') { $target = $this->Tag->TagCollectionTag->TagCollection->fetchTagCollection($user, array('conditions' => array('TagCollection.id' => $target_id))); if (empty($target)) { throw new NotFoundException(__('Invalid %s.', $target_type)); } $target = $target[0]; $org_id = $target['org_id']; $orgc_id = $org_id; } if (!$user['Role']['perm_site_admin'] && !$user['Role']['perm_sync']) { if ( ($scope === 'tag_collection' && !$user['Role']['perm_tag_editor']) || ($scope !== 'tag_collection' && !$user['Role']['perm_tagger']) || ($user['org_id'] !== $org_id && $user['org_id'] !== $orgc_id) ) { throw new MethodNotAllowedException('Invalid ' . Inflector::humanize($targe_type) . '.'); } } $tag_id = $this->Tag->captureTag(array('name' => $cluster['GalaxyCluster']['tag_name'], 'colour' => '#0088cc', 'exportable' => 1), $user); if ($target_type == 'attribute') { $existingTargetTag = $this->Tag->AttributeTag->find('first', array( 'conditions' => array('AttributeTag.tag_id' => $tag_id, 'AttributeTag.attribute_id' => $target_id), 'recursive' => -1, 'contain' => array('Tag') )); } elseif ($target_type == 'event') { $existingTargetTag = $this->Tag->EventTag->find('first', array( 'conditions' => array('EventTag.tag_id' => $tag_id, 'EventTag.event_id' => $target_id), 'recursive' => -1, 'contain' => array('Tag') )); } elseif ($target_type == 'tag_collection') { $existingTargetTag = $this->Tag->TagCollectionTag->TagCollection->find('first', array( 'conditions' => array('tag_id' => $tag_id, 'tag_collection_id' => $target_id), 'recursive' => -1, 'contain' => array('Tag') )); } if (empty($existingTargetTag)) { return 'Cluster not attached.'; } else { if ($target_type == 'event') { $result = $this->Tag->EventTag->delete($existingTargetTag['EventTag']['id']); } elseif ($target_type == 'attribute') { $result = $this->Tag->AttributeTag->delete($existingTargetTag['AttributeTag']['id']); } elseif ($target_type == 'tag_collection') { $result = $this->Tag->TagCollectionTag->delete($existingTargetTag['TagCollectionTag']['id']); } if ($result) { if ($target_type !== 'tag_collection') { $this->Tag->EventTag->Event->insertLock($user, $event['Event']['id']); $event['Event']['published'] = 0; $date = new DateTime(); $event['Event']['timestamp'] = $date->getTimestamp(); $this->Tag->EventTag->Event->save($event); } $this->Log = ClassRegistry::init('Log'); $this->Log->create(); $this->Log->save(array( 'org' => $user['Organisation']['name'], 'model' => ucfirst($target_type), 'model_id' => $target_id, 'email' => $user['email'], 'action' => 'galaxy', 'title' => 'Detached ' . $cluster['GalaxyCluster']['value'] . ' (' . $cluster['GalaxyCluster']['id'] . ') to ' . $target_type . ' (' . $target_id . ')', 'change' => '' )); return 'Cluster detached'; } else { return 'Could not detach cluster'; } } } public function getMitreAttackGalaxyId($type="mitre-enterprise-attack-attack-pattern") { $galaxy = $this->find('first', array( 'recursive' => -1, 'fields' => 'id', 'conditions' => array('Galaxy.type' => $type), )); return empty($galaxy) ? 0 : $galaxy['Galaxy']['id']; } public function getMitreAttackMatrix() { $killChainOrderEnterprise = array( 'initial-access', 'execution', 'persistence', 'privilege-escalation', 'defense-evasion', 'credential-access', 'discovery', 'lateral-movement', 'collection', 'exfiltration', 'command-and-control' ); $killChainOrderMobile = array( 'persistence', 'privilege-escalation', 'defense-evasion', 'credential-access', 'discovery', 'lateral-movement', 'effects', 'collection', 'exfiltration', 'command-and-control', 'general-network-based', 'cellular-network-based', 'could-based' ); $killChainOrderPre = array( 'priority-definition-planning', 'priority-definition-direction', 'target-selection', 'technical-information-gathering', 'people-information-gathering', 'organizational-information-gathering', 'technical-weakness-identification', 'people-weakness-identification', 'organizational-weakness-identification', 'adversary-opsec', 'establish-&-maintain-infrastructure', 'persona-development', 'build-capabilities', 'test-capabilities', 'stage-capabilities', 'app-delivery-via-authorized-app-store', 'app-delivery-via-other-means', 'exploit-via-cellular-network', 'exploit-via-internet', ); $killChainOrders = array( 'mitre-enterprise-attack-attack-pattern' => $killChainOrderEnterprise, 'mitre-mobile-attack-attack-pattern' => $killChainOrderMobile, 'mitre-pre-attack-attack-pattern' => $killChainOrderPre, ); $expectedDescription = 'ATT&CK Tactic'; $expectedNamespace = 'mitre-attack'; $conditions = array('Galaxy.description' => $expectedDescription, 'Galaxy.namespace' => $expectedNamespace); $contains = array( 'GalaxyCluster' => array('GalaxyElement'), ); $galaxies = $this->find('all', array( 'recursive' => -1, 'contain' => $contains, 'conditions' => $conditions, )); $mispUUID = Configure::read('MISP')['uuid']; $attackTactic = array( 'killChain' => $killChainOrders, 'attackTactic' => array(), 'attackTags' => array(), 'instance-uuid' => $mispUUID ); foreach ($galaxies as $galaxy) { $galaxyType = $galaxy['Galaxy']['type']; $clusters = $galaxy['GalaxyCluster']; $attackClusters = array(); // add cluster if kill_chain is present foreach ($clusters as $cluster) { if (empty($cluster['GalaxyElement'])) { continue; } $toBeAdded = false; $clusterType = $cluster['type']; $galaxyElements = $cluster['GalaxyElement']; foreach ($galaxyElements as $element) { if ($element['key'] == 'kill_chain') { $kc = explode(":", $element['value'])[2]; $attackClusters[$kc][] = $cluster; $toBeAdded = true; } if ($element['key'] == 'external_id') { $cluster['external_id'] = $element['value']; } } if ($toBeAdded) { array_push($attackTactic['attackTags'], $cluster['tag_name']); } } $attackTactic['attackTactic'][$galaxyType] = array( 'clusters' => $attackClusters, 'galaxy' => $galaxy['Galaxy'], ); } return $attackTactic; } }
Rafiot/MISP
app/Model/Galaxy.php
PHP
agpl-3.0
20,693
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.core.urlresolvers import reverse from mitxmako.shortcuts import render_to_response from courseware.access import has_access from courseware.courses import get_course_with_access from notes.utils import notes_enabled_for_course from static_replace import replace_static_urls @login_required def index(request, course_id, book_index, page=None): course = get_course_with_access(request.user, course_id, 'load') staff_access = has_access(request.user, course, 'staff') book_index = int(book_index) if book_index < 0 or book_index >= len(course.textbooks): raise Http404("Invalid book index value: {0}".format(book_index)) textbook = course.textbooks[book_index] table_of_contents = textbook.table_of_contents if page is None: page = textbook.start_page return render_to_response('staticbook.html', {'book_index': book_index, 'page': int(page), 'course': course, 'book_url': textbook.book_url, 'table_of_contents': table_of_contents, 'start_page': textbook.start_page, 'end_page': textbook.end_page, 'staff_access': staff_access}) def index_shifted(request, course_id, page): return index(request, course_id=course_id, page=int(page) + 24) @login_required def pdf_index(request, course_id, book_index, chapter=None, page=None): """ Display a PDF textbook. course_id: course for which to display text. The course should have "pdf_textbooks" property defined. book index: zero-based index of which PDF textbook to display. chapter: (optional) one-based index into the chapter array of textbook PDFs to display. Defaults to first chapter. Specifying this assumes that there are separate PDFs for each chapter in a textbook. page: (optional) one-based page number to display within the PDF. Defaults to first page. """ course = get_course_with_access(request.user, course_id, 'load') staff_access = has_access(request.user, course, 'staff') book_index = int(book_index) if book_index < 0 or book_index >= len(course.pdf_textbooks): raise Http404("Invalid book index value: {0}".format(book_index)) textbook = course.pdf_textbooks[book_index] def remap_static_url(original_url, course): input_url = "'" + original_url + "'" output_url = replace_static_urls( input_url, getattr(course, 'data_dir', None), course_namespace=course.location ) # strip off the quotes again... return output_url[1:-1] if 'url' in textbook: textbook['url'] = remap_static_url(textbook['url'], course) # then remap all the chapter URLs as well, if they are provided. if 'chapters' in textbook: for entry in textbook['chapters']: entry['url'] = remap_static_url(entry['url'], course) return render_to_response('static_pdfbook.html', {'book_index': book_index, 'course': course, 'textbook': textbook, 'chapter': chapter, 'page': page, 'staff_access': staff_access}) @login_required def html_index(request, course_id, book_index, chapter=None): """ Display an HTML textbook. course_id: course for which to display text. The course should have "html_textbooks" property defined. book index: zero-based index of which HTML textbook to display. chapter: (optional) one-based index into the chapter array of textbook HTML files to display. Defaults to first chapter. Specifying this assumes that there are separate HTML files for each chapter in a textbook. """ course = get_course_with_access(request.user, course_id, 'load') staff_access = has_access(request.user, course, 'staff') notes_enabled = notes_enabled_for_course(course) book_index = int(book_index) if book_index < 0 or book_index >= len(course.html_textbooks): raise Http404("Invalid book index value: {0}".format(book_index)) textbook = course.html_textbooks[book_index] def remap_static_url(original_url, course): input_url = "'" + original_url + "'" output_url = replace_static_urls( input_url, getattr(course, 'data_dir', None), course_namespace=course.location ) # strip off the quotes again... return output_url[1:-1] if 'url' in textbook: textbook['url'] = remap_static_url(textbook['url'], course) # then remap all the chapter URLs as well, if they are provided. if 'chapters' in textbook: for entry in textbook['chapters']: entry['url'] = remap_static_url(entry['url'], course) return render_to_response('static_htmlbook.html', {'book_index': book_index, 'course': course, 'textbook': textbook, 'chapter': chapter, 'staff_access': staff_access, 'notes_enabled': notes_enabled})
elimence/edx-platform
lms/djangoapps/staticbook/views.py
Python
agpl-3.0
5,555
# -*- coding: utf-8 -*- # Copyright (c) 2012-2015 CoNWeT Lab., Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud 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. # Wirecloud 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 Wirecloud. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import locale from optparse import make_option from django.contrib.auth.models import User, Group from django.core.management.base import BaseCommand, CommandError from django.utils.translation import override, ugettext as _ from wirecloud.catalogue.views import add_packaged_resource from wirecloud.commons.utils.template import TemplateParser from wirecloud.commons.utils.wgt import WgtFile from wirecloud.platform.localcatalogue.utils import install_resource_to_user, install_resource_to_group, install_resource_to_all_users class Command(BaseCommand): args = '<file.wgt>...' help = 'Adds one or more packaged mashable application components into the catalogue' option_list = BaseCommand.option_list + ( make_option('--redeploy', action='store_true', dest='redeploy', help='Replace mashable application components files with the new ones.', default=False), make_option('-u', '--users', action='store', type='string', dest='users', help='Comma separated list of users that will obtain access to the uploaded mashable application components', default=''), make_option('-g', '--groups', action='store', type='string', dest='groups', help='Comma separated list of groups that will obtain access rights to the uploaded mashable application components', default=''), make_option('-p', '--public', action='store_true', dest='public', help='Allow any user to access the mashable application components.', default=False), ) def _handle(self, *args, **options): if len(args) < 1: raise CommandError(_('Wrong number of arguments')) self.verbosity = int(options.get('verbosity', 1)) users = [] groups = [] redeploy = options['redeploy'] public = options['public'] users_string = options['users'].strip() groups_string = options['groups'].strip() if redeploy is False and public is False and users_string == '' and groups_string == '': raise CommandError(_('You must use at least one of the following flags: --redeploy, --users, --groups or --public ')) if not options['redeploy']: if users_string != '': for username in users_string.split(','): users.append(User.objects.get(username=username)) if groups_string != '': for groupname in groups_string.split(','): groups.append(Group.objects.get(name=groupname)) for file_name in args: try: f = open(file_name, 'rb') wgt_file = WgtFile(f) except: self.log(_('Failed to read from %(file_name)s') % {'file_name': file_name}, level=1) continue try: template_contents = wgt_file.get_template() template = TemplateParser(template_contents) if options['redeploy']: add_packaged_resource(f, None, wgt_file=wgt_file, template=template, deploy_only=True) else: for user in users: install_resource_to_user(user, file_contents=wgt_file) for group in groups: install_resource_to_group(group, file_contents=wgt_file) if public: install_resource_to_all_users(file_contents=wgt_file) wgt_file.close() f.close() self.log(_('Successfully imported \"%(name)s\" from \"%(file_name)s\"') % {'name': template.get_resource_processed_info()['title'], 'file_name': file_name}, level=1) except: self.log(_('Failed to import the mashable application component from %(file_name)s') % {'file_name': file_name}, level=1) def handle(self, *args, **options): try: default_locale = locale.getdefaultlocale()[0][:2] except TypeError: default_locale = None with override(default_locale): return self._handle(*args, **options) def log(self, msg, level=2): """ Small log helper """ if self.verbosity >= level: self.stdout.write(msg)
rockneurotiko/wirecloud
src/wirecloud/catalogue/management/commands/addtocatalogue.py
Python
agpl-3.0
5,256
<?php if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) { define("SERVER_NAME",$_SERVER['HTTP_X_FORWARDED_HOST']); } else { define("SERVER_NAME",$_SERVER['HTTP_HOST']); //.(($_SERVER['SERVER_PORT']!="80")? ":".$_SERVER['SERVER_PORT']:"")); } require_once(dirname(__FILE__)."/../../../../../../clases/class.i.php"); require_once(dirname(__FILE__)."/../../../../../../clases/class.i_image.php"); $ret = array(); $ret['error'] = false; $cats = array(); $imgs = array(); //$cache = dirname(__FILE__)."/../../../../../../../cache/tinyCache/"; $legacyPath = '/../../../../../../../tinyCache/'; if (is_dir($legacyPath)) { $cache = $legacyPath; } else { $cache = '/../../../../../../../cache/tinyCache/'; } $cache = dirname(__FILE__).$cache; $aPasa = array('.','..'); $imgok= array('image/jpg','image/gif','image/png'); $value = i::clean($_GET['val']); switch($_GET['w']){ case "all": if ($gestor = opendir($cache)) { while (false !== ($a= readdir($gestor))) { if(in_array($a,$aPasa)) continue; if (!is_dir($cache.$a)) continue; $cats[] = $a; } closedir($gestor); if (sizeof($cats)<=0){ mkdir($cache."general", 0777); chmod($cache."general", 0777); $cats[] = "general"; } }else{ $ret['error'] = "imposible abrir el directorio ".$cache; } case "images": if (!isset($_GET['c'])) $c = $cats[0]; else $c = $_GET['c']; if ($gestor = opendir($cache.$c)) { while (false !== ($a= readdir($gestor))) { if(in_array($a,$aPasa)) continue; if (!is_file($cache.$c.'/'.$a)||!in_array(i::mime_content_type($cache.$c.'/'.$a),$imgok)) continue; $imgs[] = $a; } closedir($gestor); } break; case "newCat": if (trim($value)!=""){ if ($gestor = opendir($cache)) { while (false !== ($a= readdir($gestor))) { if(in_array($a,$aPasa)) continue; if (!is_dir($cache.$a)) continue; $cats[] = $a; } closedir($gestor); if (!in_array($value,$cats)){ mkdir($cache.$value, 0777); chmod($cache.$value, 0777); $ret['result'] = "Categoría insertada con éxito."; }else{ $ret['error'] = "Entrada repetida"; } }else{ $ret['error'] = "imposible abrir el directorio ".$cache; } }else{ $ret['error'] = 'Debes introducir un nombre'; } break; case "delCat": if (is_dir($cache.$value)){ i::rmrf($cache . $value); $ret['result'] = "Categoría borrada con éxito."; }else{ $ret['error'] = 'Error'; } break; } $ret['categories'] = $cats; $ret['images'] = $imgs; $ret['path'] = i::base_url()."../../../../../../../cache/tinyCache/".$c."/"; // $ret['svname'] = "http://".SERVER_NAME; $ret['svname'] = ""; echo json_encode($ret); exit(); ?>
irontec/Mintzatu
public/karma/modules/tablon/scripts/tiny_mce/plugins/advimage/ajax_gallery.php
PHP
agpl-3.0
2,902
/** * Copyright (C) 2009-2013 FoundationDB, 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/>. */ package com.foundationdb.server.store.statistics; import com.foundationdb.ais.model.Index; import com.foundationdb.ais.model.IndexColumn; import com.foundationdb.server.service.session.Session; import com.foundationdb.server.service.tree.KeyCreator; import com.foundationdb.server.store.IndexVisitor; import com.foundationdb.server.store.Store; import java.util.ArrayList; import java.util.List; public class IndexStatisticsVisitor<K extends Comparable<? super K>, V> extends IndexVisitor<K,V> { public interface VisitorCreator<K extends Comparable<? super K>, V> { IndexStatisticsGenerator<K,V> multiColumnVisitor(Index index); IndexStatisticsGenerator<K,V> singleColumnVisitor(Session session, IndexColumn indexColumn); } public IndexStatisticsVisitor(Session session, Index index, long indexRowCount, long expectedSampleCount, VisitorCreator<K,V> creator) { this.index = index; this.indexRowCount = indexRowCount; this.expectedSampleCount = expectedSampleCount; this.multiColumnVisitor = creator.multiColumnVisitor(index); this.nIndexColumns = index.getKeyColumns().size(); this.singleColumnVisitors = new ArrayList<>(nIndexColumns-1); // Single column 0 is handled as leading column of multi-column. for (int f = 1; f < nIndexColumns; f++) { singleColumnVisitors.add( creator.singleColumnVisitor(session, index.getKeyColumns().get(f)) ); } } public void init(int bucketCount) { multiColumnVisitor.init(bucketCount, expectedSampleCount); for (int c = 1; c < nIndexColumns; c++) { singleColumnVisitors.get(c-1).init(bucketCount, expectedSampleCount); } } public void finish(int bucketCount) { multiColumnVisitor.finish(bucketCount); for (int c = 1; c < nIndexColumns; c++) { singleColumnVisitors.get(c-1).finish(bucketCount); } } protected void visit(K key, V value) { multiColumnVisitor.visit(key, value); for (int c = 1; c < nIndexColumns; c++) { singleColumnVisitors.get(c-1).visit(key, value); } } public IndexStatistics getIndexStatistics() { IndexStatistics indexStatistics = new IndexStatistics(index); // The multi-column visitor has the sampled row count. The single-column visitors // have the count of distinct sampled keys for that column. int sampledCount = multiColumnVisitor.rowCount(); indexStatistics.setRowCount(indexRowCount); indexStatistics.setSampledCount(sampledCount); multiColumnVisitor.getIndexStatistics(indexStatistics); for (int c = 1; c < nIndexColumns; c++) { singleColumnVisitors.get(c-1).getIndexStatistics(indexStatistics); } return indexStatistics; } private final Index index; private final long indexRowCount, expectedSampleCount; private final IndexStatisticsGenerator<K,V> multiColumnVisitor; private final List<IndexStatisticsGenerator<K,V>> singleColumnVisitors; private final int nIndexColumns; }
AydinSakar/sql-layer
src/main/java/com/foundationdb/server/store/statistics/IndexStatisticsVisitor.java
Java
agpl-3.0
4,030
/* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltcore.messaging; import java.io.IOException; import java.nio.ByteBuffer; public class VoltMessageFactory { // Identify each message final public static byte AGREEMENT_TASK_ID = 1; final public static byte BINARY_PAYLOAD_ID = 2; final public static byte FAILURE_SITE_UPDATE_ID = 3; final public static byte HEARTBEAT_ID = 4; final public static byte HEARTBEAT_RESPONSE_ID = 5; final public static byte RECOVERY_ID = 6; // DON'T JUST ADD A MESSAGE TYPE WITHOUT READING THIS! // VoltDbMessageFactory is going to use this to generate non-core message IDs. // Update the max value if you add a new message type above, or you // will be sad, and I will have no sympathy. --izzy final public static byte VOLTCORE_MESSAGE_ID_MAX = 6; public VoltMessage createMessageFromBuffer(ByteBuffer buffer, long sourceHSId) throws IOException { byte type = buffer.get(); // instantiate a new message instance according to the id VoltMessage message = instantiate_local(type); if (message == null) { message = instantiate(type); } message.m_sourceHSId = sourceHSId; message.initFromBuffer(buffer.slice().asReadOnlyBuffer()); return message; } /** * Overridden by subclasses to create message types unknown by voltcore * @param messageType * @return */ protected VoltMessage instantiate_local(byte messageType) { return null; } private VoltMessage instantiate(byte messageType) { // instantiate a new message instance according to the id VoltMessage message = null; switch (messageType) { case HEARTBEAT_ID: message = new HeartbeatMessage(); break; case HEARTBEAT_RESPONSE_ID: message = new HeartbeatResponseMessage(); break; case FAILURE_SITE_UPDATE_ID: message = new FailureSiteUpdateMessage(); break; case RECOVERY_ID: message = new RecoveryMessage(); break; case AGREEMENT_TASK_ID: message = new AgreementTaskMessage(); break; case BINARY_PAYLOAD_ID: message = new BinaryPayloadMessage(); break; default: org.voltdb.VoltDB.crashLocalVoltDB("Unrecognized message type " + messageType, true, null); } return message; } }
kobronson/cs-voltdb
src/frontend/org/voltcore/messaging/VoltMessageFactory.java
Java
agpl-3.0
3,216
<?php return array( 'plural' => function($n) { return (($n==1) ? 0 : (($n>=2 && $n<=4) ? 1 : 2)); }, 'attachment' => 'příloha', 'When there is nothing to read, redirect me to this page' => 'Když není nic ke čtení, přesměruj mě na tuto stránku', 'There is nothing new to read, enjoy your favorites articles!' => 'Není tu nic nového ke čtení, užijte si vaše oblíbené články!', 'There is nothing new to read, enjoy your previous readings!' => 'Není tu nic nového ke čtení, užijte si vaše starší články!', 'Immediately' => 'Hned', '(error occurred during the last check)' => '(během poslední kontroly nastala chyba)', 'The feed id is required' => 'Id zdroje je vyžadováno', 'The title is required' => 'Název je vyžadován', 'The site url is required' => 'URL stránky je vyžadováno', 'The feed url is required' => 'URL zdroje je vyžadováno', 'or' => 'nebo', 'edit' => 'upravit', 'cancel' => 'zrušit', 'Feed URL' => 'URL zdroje', 'Website URL' => 'URL stránky', 'Title' => 'Název', 'Edit subscription' => 'Upravit odběr', 'Unable to edit your subscription.' => 'Nelze upravit váš odběr.', 'Your subscription has been updated.' => 'Váš odběr byl aktualizován', 'Older items first' => 'Nejdřív starší články', 'Most recent first' => 'Nejdřív nejnovější', 'Default sorting order for items' => 'Výchozí pořadí článků', 'This subscription is empty, %sgo back to unread items%s' => 'Tento odběr je prázdný %svrátit se na nepřečtené články%s', 'sort by date %s(%s)%s' => 'řadit podle data %s(%s)%s', 'most recent first' => 'nejdříve nejnovější', 'older first' => 'nejdříve starší', 'Show only this subscription' => 'Zobrazovat pouze tento odběr', 'Go to unread' => 'Jít na nepřečtené', 'Go to bookmarks' => 'Jít na záložky', 'Go to history' => 'Jít na historii', 'Go to subscriptions' => 'Jít na odběry', 'Go to preferences' => 'Jít na nastavení', 'Bookmarklet' => 'Bookmarklet', 'Subscribe with Miniflux' => 'Odebírat Minifluxem', 'Drag and drop this link to your bookmarks' => 'Přetáhněte si tento odkaz mezi záložky', 'Download full content' => 'Stahovat celý obsah', 'Downloading full content is slower because Miniflux grab the content from the original website. You should use that for subscriptions that display only a summary. This feature doesn\'t work with all websites.' => 'Stahování celého obsahu je pomalejší, protože Miniflux získává obsah z původní webové stránky. Měli byste to používat jen pro odběry které zobrazují pouze shrnutí. Tato funkce nefunguje se všemi stránkami.', 'No message' => 'Žádné zprávy', 'flush messages' => 'smazat zprávy', 'API endpoint:' => 'Koncový bod:', 'API username:' => 'Uživatelské jméno:', 'API token:' => 'Heslo:', 'Generate new tokens' => 'Generovat nové heslo', 'Bookmark RSS Feed' => 'RSS záložek', 'updated just now' => 'aktualizováno právě teď', 'checked at' => 'zkontrolováno', 'never updated after creation' => 'nikdy neaktualizováno po vytvoření', 'Subscription disabled' => 'Odběr zakázán', 'content downloaded' => 'obsah stažen', 'in progress...' => 'probíhá&hellip;', 'unable to fetch content' => 'nelze stáhnout obsah', 'Download content' => 'Stáhnout obsah', 'download content' => 'stáhnout obsah', 'Help' => 'Nápověda', 'Theme' => 'Vzhled', 'Items per page' => 'Článků na stránku', 'Previous page' => 'Předchozí stránka', 'Next page' => 'Další stránka', 'Do not fetch the content of articles' => 'Nestahovat obsah článků', 'Remove automatically read items' => 'Automaticky odstraňovat přečtené články', 'Never' => 'Nikdy', 'After %d day' => array('Po %d dni', 'Po %d dnech', 'Po %d dnech'), 'unread' => 'nepřečtené', 'Unread' => 'Nepřečtené', 'bookmark' => 'přidat do záložek', 'remove bookmark' => 'odstranit záložku', 'bookmarks' => 'záložky', 'Bookmarks' => 'Záložky', 'Bookmark item' => 'Přidat článek do záložek', 'No bookmark' => 'Žádné záložky', 'history' => 'historie', 'subscriptions' => 'odběry', 'Subscriptions' => 'Odběry', 'preferences' => 'nastavení', 'Preferences' => 'Nastavení', 'logout' => 'odhlásit', 'Username' => 'Přihlašovací jméno', 'Password' => 'Heslo', 'Confirmation' => 'Potvrzení', 'Language' => 'Jazyk', 'Save' => 'Uložit', 'Database size:' => 'Velikost databáze:', 'Optimize the database' => 'Optimalizovat databázi', '(VACUUM command)' => '(příkaz VACUUM)', 'Download the entire database' => 'Stáhnout celou databázi', '(Gzip compressed Sqlite file)' => '(Gzipem komprimovaný SQLite soubor)', 'Keyboard shortcuts' => 'Klávesové zkratky', 'Previous item' => 'Předchozí článek', 'Next item' => 'Další článek', 'Mark as read or unread' => 'Označit jako (ne)přečtené', 'Open original link' => 'Otevřít původní odkaz', 'Open item' => 'Otevřít článek', 'About' => 'O aplikaci', 'Miniflux version:' => 'Verze Miniflux:', 'Nothing to read' => 'Nic ke čtení', 'mark all as read' => 'označit vše jako přečtené', 'original link' => 'původní odkaz', 'mark as read' => 'označit jako přečtené', 'No history' => 'Žádná historie', 'mark as unread' => 'označit jako nepřečtené', 'History' => 'Historie', 'flush all items' => 'zahodit všechny články', 'Item not found' => 'Článek nenalezen', 'Next' => 'Další', 'Previous' => 'Předchozí', 'Sign in' => 'Přihlásit', 'feeds' => 'zdroje', 'add' => 'přidat', 'import' => 'importovat', 'export' => 'exportovat', 'OPML Import' => 'Importovat OPML', 'OPML file' => 'OPML soubor', 'Import' => 'Importovat', 'refresh all' => 'aktualizovat vše', 'No subscription' => 'Žádné zdroje', 'remove' => 'odstranit', 'Remove' => 'Odstranit', 'refresh' => 'aktualizovat', 'New subscription' => 'Nový odběr', 'Website or Feed URL' => 'URL stránky nebo zdroje', 'Add' => 'Přidat', 'http://website/' => 'http://webova-stranka/', 'Official website:' => 'Oficiální stránka:', 'Bad username or password' => 'Špatné přihlašovací jméno nebo heslo', 'Unable to update your preferences.' => 'Nelze aktualizovat nastavení.', 'Your preferences are updated.' => 'Nastavení aktualizována.', 'Unable to import your OPML file.' => 'Nelze importovat OPML soubor.', 'Your feeds have been imported.' => 'Zdroje byly importovány.', 'Unable to find a subscription.' => 'Nelze nalézt odběry.', 'Subscription added successfully.' => 'Odběr úspěšně přidán.', 'Your subscriptions are updated' => 'Odběry aktualizovány', 'Unable to remove this subscription.' => 'Nelze odstranit tento odběr.', 'This subscription has been removed successfully.' => 'Tento odběr byl úspěšně odstraněn.', 'The user name is required' => 'Přihlašovací jméno je vyžadováno', 'The maximum length is 50 characters' => 'Maximální délka je 50 znaků', 'The password is required' => 'Heslo je vyžadováno', 'The minimum length is 6 characters' => 'Minimální délka je 6 znaků', 'The confirmation is required' => 'Potvrzení je vyžadováno', 'Passwords don\'t match' => 'Hesla se neshodují', 'Do you really want to remove these items from your history?' => 'Opravdu chcete odstranit tyto články z historie?', 'Do you really want to remove this subscription: "%s"?' => 'Opravdu chcete odstranit tento odběr: "%s"?', 'Nothing to read, do you want to %supdate your subscriptions%s?' => 'Nic ke čtení, chcete %saktualizovat vaše odběry%s?', 'Show help' => 'Zobrazit nápovědu', 'Close help' => 'Zavřít nápovědu', '%d second ago' => array('před sekundou', 'před %d sekundami', 'před %d sekundami'), '%d minute ago' => array('před minutou', 'před %d minutami', 'před %d minutami'), '%d hour ago' => array('před hodinou', 'před %d hodinami', 'před %d hodinami'), '%d day ago' => array('včera', 'před %d dny', 'před %d dny'), '%d week ago' => array('minulý týden', 'před %d týdny', 'před %d týdny'), '%d month ago' => array('před měsícem', 'před %d měsíci', 'před %d měsíci'), 'Timezone' => 'Časová zóna', 'Update all subscriptions' => 'Aktualizovat všechny odběry', 'Auto-Update URL' => 'URL automatické aktualizace', 'Update Miniflux' => 'Aktualizovat Miniflux', 'Miniflux is updated!' => 'Miniflux je aktualizovaný!', 'Unable to update Miniflux, check the console for errors.' => 'Nelze aktualizovat Miniflux, zkontrolujte konzoli na chyby.', 'Don\'t forget to backup your database' => 'Nezapomeňte zálohovat vaši databázi', 'The name must have only alpha-numeric characters' => 'Jméno smí obsahovat pouze písmena a číslice', 'New database' => 'Nová databáze', 'Database name' => 'Jméno databáze', 'Default database' => 'Výchozí databáze', 'Select another database' => 'Vyberte jinou databázi', 'The database name is required' => 'Jméno databáze je vyžadováno', 'Database created successfully.' => 'Databáze úspěšně vytvořena.', 'Unable to create the new database.' => 'Nelze vytvořit novou databázi.', 'Add a new database (new user)' => 'Přidat novou databázi (nového uživatele)', 'Create' => 'Vytvořit', 'Unknown' => 'Neznámý', 'Remember Me' => 'Zapamatovat si mě', 'Display items on lists' => 'Zobrazovat články na seznamech', 'Summaries' => 'Shrnutí', 'Full contents' => 'Celý obsah', 'Force RTL mode (Right-to-left language)' => 'Vynutit režim zprava doleva', 'Activated' => 'Aktivováno', 'Remove this feed' => 'Odstranit tento zdroj', 'Miniflux' => 'Miniflux', 'mini%sflux%s' => 'mini%sflux%s', 'All' => 'Vše', 'Advanced' => 'Pokročilé', 'Documentation' => 'dokumentace', 'Installation instructions' => 'Instalační instrukce', 'Upgrade to a new version' => 'Aktualizovat na novou verzi', 'Cronjob' => 'Cronjob', 'Advanced configuration' => 'Pokročilá nastavení', 'Full article download' => 'stahování celého článku', 'Multiple users' => 'Více uživatelů', 'Themes' => 'Témata', 'Json-RPC API' => 'Json-RPC API', 'Fever API' => 'Fever API', 'Translations' => 'Překlady', 'Run Miniflux with Docker' => 'Spouštět Miniflux s Dockerem', 'FAQ' => 'ČKD', 'settings' => 'nastavení', 'help' => 'nápověda', 'api' => 'api', 'about' => 'o', 'This action will update Miniflux with the last development version, are you sure?' => 'Tato akce aktualizuje Miniflux na poslední vývojovou verzi. Jste si jistí?', 'database' => 'databáze', 'Console' => 'konzole', 'Miniflux API' => 'Miniflux API', 'menu' => 'nabídka', 'Default' => 'Výchozí', 'Value required' => 'Hodnota vyžadována', 'Must be an integer' => 'Musí být celé číslo', 'Remove automatically unread items' => 'Automaticky odstraňovat nepřečtené články', 'Toggle RTL mode' => 'Přepnout režim zprava doleva', 'external services' => 'externí služby', 'Send bookmarks to Pinboard' => 'Posílat záložky na Pinboard', 'Pinboard API token' => 'Pinboard API token', 'Pinboard tags' => 'Pinboard štítky', 'Instapaper username' => 'Instapaper uživatelské jméno', 'Instapaper password' => 'Instapaper heslo', 'Instapaper' => 'Instapaper', 'Pinboard' => 'Pinboard', 'Send bookmarks to Instapaper' => 'Posílat záložky na Instapaper', 'Authentication' => 'Autentikace', 'Reading' => 'Čtení', 'Application' => 'Aplikace', 'Enable image proxy' => 'Povolit proxy obrázků', 'Avoid mixed content warnings with HTTPS' => 'Vyhne se varování o pomíchaném obsahu s HTTPS', 'Download favicons' => 'Stahovat favicony', 'general' => 'základní', 'An error occurred during the last check. Refresh the feed manually and check the %sconsole%s for errors afterwards!' => 'Nastala chyba při poslední kontrole. Obnovte zdroj ručně a poté zkontrolujte %skonzoli%s na chyby!', 'Refresh interval in minutes for unread counter' => 'Obnovovací interval v minutách pro počítadlo nepřečtených', 'Nothing to show. Enable the debug mode to see log messages.' => 'Není co ukázat. Povolte ladící režim pro zobrazení záznamů.', 'Enable debug mode' => 'Povolit ladící režim', 'Original link marks article as read' => 'Původní odkaz označí článek za přečtený', 'Cloak the image referrer' => 'Zamaskovat původce obrázků', 'This subscription already exists.' => 'Tento odběr již existuje.', 'Connection timeout.' => 'Vypršel časový limit spojení.', 'Error occured.' => 'Nastala chyba.', 'Feed is malformed.' => 'Odběr má špatný formát.', 'Invalid SSL certificate.' => 'Neplatný SSL certifikát.', 'Maximum number of HTTP redirections exceeded.' => 'Maximální počet HTTP přesměrování překročen.', 'The content size exceeds to maximum allowed size.' => 'Velikost obsahu překročila maximální povolenou velikost.', 'Unable to detect the feed format.' => 'Nelze detekovat formát odběru.', 'add a new group' => 'přidat novou skupinu', 'Groups' => 'Skupiny', 'Back to the group' => 'Zpět do skupiny', 'view' => 'zobrazit', 'Item title links to' => 'Titulek článku odkazuje na', 'Original' => 'Originál', 'Last login:' => 'Poslední přihlášení:', 'Search' => 'Hledat', 'There are no results for your search' => 'Žádné výsledky vašeho hledání', );
mkresin/miniflux
locales/cs_CZ/translations.php
PHP
agpl-3.0
14,023
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2015 Zurmo Inc. * * Zurmo 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 with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2015. All rights reserved". ********************************************************************************/ class ApprovalProcessForMixedModelsSearchListView extends SecuredListView { public static function getDefaultMetadata() { $metadata = array( 'global' => array( 'panels' => array( array( 'rows' => array( array('cells' => array( array( 'elements' => array( array('attributeName' => 'name', 'type' => 'Text', 'isLink' => true), ), ), ) ), array('cells' => array( array( 'elements' => array( array('attributeName' => 'opportunity', 'type' => 'Opportunity', 'isLink' => true), ), ), ) ), array('cells' => array( array( 'elements' => array( array('attributeName' => 'assignedto', 'type' => 'User', 'isLink' => true ), ), ), ) ), array('cells' => array( array( 'elements' => array( array('attributeName' => 'comments', 'type' => 'TextArea'), ), ), ) ), ), ), ), ), ); return $metadata; } public static function getDesignerRulesType() { return 'ForMixedModelsSearchListView'; } } ?>
Ramkavanan/SHCRM
app/protected/modules/approvalProcess/views/ApprovalProcessForMixedModelsSearchListView.php
PHP
agpl-3.0
4,693
<?php /* Smarty version 2.6.11, created on 2014-09-27 03:20:43 compiled from include/EditView/header.tpl */ ?> <?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins(array('plugins' => array(array('function', 'sugar_button', 'include/EditView/header.tpl', 81, false),array('function', 'sugar_action_menu', 'include/EditView/header.tpl', 91, false),)), $this); ?> {* /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program 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 with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ *} <script> {literal} $(document).ready(function(){ $("ul.clickMenu").each(function(index, node){ $(node).sugarActionMenu(); }); }); {/literal} </script> <div class="clear"></div> <form action="index.php" method="POST" name="{$form_name}" id="{$form_id}" {$enctype}> <table width="100%" cellpadding="0" cellspacing="0" border="0" class="dcQuickEdit"> <tr> <td class="buttons"> <input type="hidden" name="module" value="{$module}"> {if isset($smarty.request.isDuplicate) && $smarty.request.isDuplicate eq "true"} <input type="hidden" name="record" value=""> <input type="hidden" name="duplicateSave" value="true"> <input type="hidden" name="duplicateId" value="{$fields.id.value}"> {else} <input type="hidden" name="record" value="{$fields.id.value}"> {/if} <input type="hidden" name="isDuplicate" value="false"> <input type="hidden" name="action"> <input type="hidden" name="return_module" value="{$smarty.request.return_module}"> <input type="hidden" name="return_action" value="{$smarty.request.return_action}"> <input type="hidden" name="return_id" value="{$smarty.request.return_id}"> <input type="hidden" name="module_tab"> <input type="hidden" name="contact_role"> {if (!empty($smarty.request.return_module) || !empty($smarty.request.relate_to)) && !(isset($smarty.request.isDuplicate) && $smarty.request.isDuplicate eq "true")} <input type="hidden" name="relate_to" value="{if $smarty.request.return_relationship}{$smarty.request.return_relationship}{elseif $smarty.request.relate_to && empty($smarty.request.from_dcmenu)}{$smarty.request.relate_to}{elseif empty($isDCForm) && empty($smarty.request.from_dcmenu)}{$smarty.request.return_module}{/if}"> <input type="hidden" name="relate_id" value="{$smarty.request.return_id}"> {/if} <input type="hidden" name="offset" value="{$offset}"> {assign var='place' value="_HEADER"} <!-- to be used for id for buttons with custom code in def files--> <?php if (isset ( $this->_tpl_vars['form']['hidden'] )): $_from = $this->_tpl_vars['form']['hidden']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)): foreach ($_from as $this->_tpl_vars['field']): echo $this->_tpl_vars['field']; ?> <?php endforeach; endif; unset($_from); endif; if (empty ( $this->_tpl_vars['form']['button_location'] ) || $this->_tpl_vars['form']['button_location'] == 'top'): if (! empty ( $this->_tpl_vars['form'] ) && ! empty ( $this->_tpl_vars['form']['buttons'] )): ?> <?php $_from = $this->_tpl_vars['form']['buttons']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)): foreach ($_from as $this->_tpl_vars['val'] => $this->_tpl_vars['button']): ?> <?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => ($this->_tpl_vars['button']),'form_id' => ($this->_tpl_vars['form_id']),'view' => ($this->_tpl_vars['view']),'appendTo' => 'header_buttons','location' => 'HEADER'), $this);?> <?php endforeach; endif; unset($_from); else: echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'SAVE','view' => ($this->_tpl_vars['view']),'form_id' => ($this->_tpl_vars['form_id']),'location' => 'HEADER','appendTo' => 'header_buttons'), $this);?> <?php echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'CANCEL','view' => ($this->_tpl_vars['view']),'form_id' => ($this->_tpl_vars['form_id']),'location' => 'HEADER','appendTo' => 'header_buttons'), $this);?> <?php endif; if (empty ( $this->_tpl_vars['form']['hideAudit'] ) || ! $this->_tpl_vars['form']['hideAudit']): echo smarty_function_sugar_button(array('module' => ($this->_tpl_vars['module']),'id' => 'Audit','view' => ($this->_tpl_vars['view']),'form_id' => ($this->_tpl_vars['form_id']),'appendTo' => 'header_buttons'), $this);?> <?php endif; endif; echo smarty_function_sugar_action_menu(array('buttons' => $this->_tpl_vars['header_buttons'],'class' => 'fancymenu','flat' => true), $this);?> </td> <td align='right'><?php echo $this->_tpl_vars['ADMIN_EDIT']; ?> <?php if ($this->_tpl_vars['panelCount'] == 0): ?> <?php if ($this->_tpl_vars['SHOW_VCR_CONTROL']): ?> {$PAGINATION} <?php endif; endif; ?> </td> </tr> </table>
alishahpakneeds/akbarsugarcrm
cache/smarty/templates_c/%%95^955^955CF478%%header.tpl.php
PHP
agpl-3.0
6,701
<?php /** * HTTP Raw Header Field Validator Class | Validation\HTTP\Headers\Raw.php * * @author Bruno Augusto * * @copyright Copyright (c) 2017 Next Studios * @license http://www.gnu.org/licenses/agpl-3.0.txt GNU Affero General Public License 3.0 */ namespace Next\Validation\HTTP\Headers; use Next\Components\Object; # Object Class /** * The Raw Header Validator checks if input string if valid to be used as * unfiltered — thus "raw" — Header Field * * Because they must be manually — and carefully — set, the only concerns * we take care of is for the value not to be NULL, otherwise this would * result in an empty string when being used and for the string to not * have a colon (:) which is what usually separates a Header Field name * from its value * * If a Raw Header must be sent with a Name, then it's not Raw, it's Generic ;) * * @package Next\Validation * * @uses Next\Components\Object * Next\Validation\HTTP\Headers\Header */ class Raw extends Object implements Header { /** * Parameter Options Definition * * @var array $parameters */ protected $parameters = [ 'value' => [ 'required' => TRUE ] ]; /** * Validates Generic Header Field * * @return boolean * TRUE if valid and FALSE otherwise */ public function validate() : bool { return ( $this -> options -> value !== NULL && strpos( $this -> options -> value, ':' ) === FALSE ); } }
nextframework/next
Validation/HTTP/Headers/Raw.php
PHP
agpl-3.0
1,530
<?php /* Smarty version 2.6.11, created on 2014-11-06 21:16:36 compiled from cache/modules/Leads/SearchFormHeader.tpl */ ?> <?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins(array('plugins' => array(array('function', 'sugar_getjspath', 'cache/modules/Leads/SearchFormHeader.tpl', 4, false),)), $this); ?> <div class="clear"></div> <div class='listViewBody'> <script type="text/javascript" src="<?php echo smarty_function_sugar_getjspath(array('file' => 'include/javascript/popup_parent_helper.js'), $this);?> "></script> <?php echo $this->_tpl_vars['TABS']; ?> <?php echo ' <script> function submitOnEnter(e) { var characterCode = (e && e.which) ? e.which : event.keyCode; if (characterCode == 13) { document.getElementById(\'search_form\').submit(); return false; } else { return true; } } </script> '; ?> <form name='search_form' id='search_form' class='search_form' method='post' action='index.php?module=<?php echo $this->_tpl_vars['module']; ?> &action=<?php echo $this->_tpl_vars['action']; ?> ' onkeydown='submitOnEnter(event);'> <input type='hidden' name='searchFormTab' value='<?php echo $this->_tpl_vars['displayView']; ?> '/> <input type='hidden' name='module' value='<?php echo $this->_tpl_vars['module']; ?> '/> <input type='hidden' name='action' value='<?php echo $this->_tpl_vars['action']; ?> '/> <input type='hidden' name='query' value='true'/> <?php $_from = $this->_tpl_vars['TAB_ARRAY']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }$this->_foreach['tabIteration'] = array('total' => count($_from), 'iteration' => 0); if ($this->_foreach['tabIteration']['total'] > 0): foreach ($_from as $this->_tpl_vars['tabkey'] => $this->_tpl_vars['tabData']): $this->_foreach['tabIteration']['iteration']++; ?> <div id='<?php echo $this->_tpl_vars['module']; echo $this->_tpl_vars['tabData']['name']; ?> _searchSearchForm' style='<?php echo $this->_tpl_vars['tabData']['displayDiv']; ?> ' class="edit view search <?php echo $this->_tpl_vars['tabData']['name']; ?> "><?php if ($this->_tpl_vars['tabData']['displayDiv']): else: echo $this->_tpl_vars['return_txt']; endif; ?></div> <?php endforeach; endif; unset($_from); ?> <div id='<?php echo $this->_tpl_vars['module']; ?> saved_viewsSearchForm' style='display: none;'><?php echo $this->_tpl_vars['saved_views_txt']; ?> </div>
SoftNext/secondp
cache/smarty/templates_c/%%E2^E2E^E2EE98C0%%SearchFormHeader.tpl.php
PHP
agpl-3.0
2,421
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // Copyright (c) 2015 Alexander Nimmervoll // // 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/>. using System; using System.Windows; using System.Diagnostics; using System.Windows.Navigation; using CalDavSynchronizer.Ui.Options.ViewModels; namespace CalDavSynchronizer.Ui.Options.Views { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class OXInfoDialog : Window { public OXInfoDialog() { InitializeComponent(); DataContextChanged += OptionsWindow_DataContextChanged; } private void OptionsWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var viewModel = e.NewValue as OXInfoDialogViewModel; if (viewModel != null) { viewModel.CloseRequested += ViewModel_CloseRequested; } } private void ViewModel_CloseRequested(object sender, CloseEventArgs e) { DialogResult = e.IsAcceptedByUser; } } }
aluxnimm/outlookcaldavsynchronizer
CalDavSynchronizer/Ui/Options/Views/OXInfoDialog.xaml.cs
C#
agpl-3.0
1,818
/** * */ /** * @author sergio * */ package bluecrystal.domain.helper;
bluecrystalsign/signer-source
bluecrystal.deps.domain/src/main/java/bluecrystal/domain/helper/package-info.java
Java
agpl-3.0
82
require 'feed-normalizer' require 'open-uri' class FeedPost < ActiveRecord::Base extend PreferencesHelper class << self def update_posts posts = find(:all, :select => "feedid") post_ids = posts.map {|p| p.feedid} begin feed = FeedNormalizer::FeedNormalizer.parse open(global_prefs.blog_feed_url) feed_ids = feed.entries.map {|e| e.id} new_ids = feed_ids - post_ids feed.entries.each do |entry| if new_ids.include? entry.id post = FeedPost.new() post.feedid = entry.id post.title = entry.title post.urls = entry.urls post.categories = entry.categories post.content = entry.content post.authors = entry.authors post.date_published = entry.date_published #post.last_updated = entry.last_updated post.save end end new_ids.length rescue nil end end end end
austintimeexchange/oscurrency
app/models/feed_post.rb
Ruby
agpl-3.0
998
package jcog.pri.bag; import jcog.Util; import jcog.data.list.FasterList; import jcog.pri.*; import jcog.pri.bag.impl.ArrayBag; import jcog.pri.bag.impl.HijackBag; import jcog.pri.bag.impl.PriReferenceArrayBag; import jcog.pri.bag.impl.hijack.DefaultHijackBag; import jcog.random.XoRoShiRo128PlusRandom; import jcog.signal.Tensor; import jcog.signal.tensor.ArrayTensor; import org.apache.commons.math3.random.EmpiricalDistribution; import org.apache.commons.math3.stat.Frequency; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.eclipse.collections.api.block.function.primitive.FloatToFloatFunction; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.stream.Collectors; import static jcog.Texts.n4; import static jcog.pri.bag.ArrayBagTest.assertSorted; import static org.junit.jupiter.api.Assertions.*; /** * @author me */ class BagTest { public static void testBasicInsertionRemoval(Bag<String, PriReference<String>> c) { assertEquals(1, c.capacity()); if (!(c instanceof DefaultHijackBag)) { assertEquals(0, c.size()); assertTrue(c.isEmpty()); } PLink x0 = new PLink("x", 2 * ScalarValue.EPSILON); PriReference added = c.put(x0); assertSame(added, x0); c.commit(); assertEquals(1, c.size()); assertEquals(0, c.priMin(), ScalarValue.EPSILON * 2); PriReference<String> x = c.get("x"); assertNotNull(x); assertSame(x, x0); assertTrue(Util.equals(Prioritized.Zero.priElseNeg1(), x.priElseNeg1(), 0.01f)); } public static Random rng() { return new XoRoShiRo128PlusRandom(1); } public static void printDist(@NotNull EmpiricalDistribution f) { System.out.println(f.getSampleStats().toString().replace("\n", " ")); f.getBinStats().forEach( s -> { /*if (s.getN() > 0)*/ System.out.println( n4(s.getMin()) + ".." + n4(s.getMax()) + ":\t" + s.getN()); } ); } private static Tensor samplingPriDist(@NotNull Bag<PLink<String>, PLink<String>> b, int batches, int batchSize, int bins) { assert(bins > 1); Set<String> hit = new TreeSet(); Frequency hits = new Frequency(); ArrayTensor f = new ArrayTensor(bins); assertFalse(b.isEmpty()); Random rng = new XoRoShiRo128PlusRandom(1); float min = b.priMin(), max = b.priMax(), range = max-min; for (int i = 0; i < batches; i++) { b.sample(rng, batchSize, x -> { f.data[Util.bin(b.pri(x), bins)]++; String s = x.get(); hits.addValue(s); hit.add(s); }); } int total = batches * batchSize; assertEquals(total, Util.sum(f.data), 0.001f); if (hits.getUniqueCount() != b.size()) { System.out.println(hits.getUniqueCount() + " != " + b.size()); Set<String> items = b.stream().map(NLink::get).collect(Collectors.toSet()); items.removeAll(hit); System.out.println("not hit: " + items); System.out.println(hits); fail("all elements must have been sampled at least once"); } return f.scaled(1f / total); } public static void testRemoveByKey(Bag<String, PriReference<String>> a) { a.put(new PLink("x", 0.1f)); a.commit(); assertEquals(1, a.size()); a.remove("x"); a.commit(); assertEquals(0, a.size()); assertTrue(a.isEmpty()); if (a instanceof ArrayBag) { assertTrue(((PriReferenceArrayBag) a).listCopy().isEmpty()); //assertTrue(((PLinkArrayBag) a).keySet().isEmpty()); } } static void testBagSamplingDistributionLinear(Bag<PLink<String>, PLink<String>> bag, float batchSizeProp) { fillLinear(bag, bag.capacity()); testBagSamplingDistribution(bag, batchSizeProp); } static void testBagSamplingDistributionSquashed(Bag<PLink<String>, PLink<String>> bag, float batchSizeProp) { fill(bag, bag.capacity(), (x)-> (x/2f) + 0.5f); testBagSamplingDistribution(bag, batchSizeProp); } static void testBagSamplingDistributionCurved(Bag<PLink<String>, PLink<String>> bag, float batchSizeProp) { fill(bag, bag.capacity(), (x)-> 1-(1-x)*(1-x)); testBagSamplingDistribution(bag, batchSizeProp); } static void testBagSamplingDistributionRandom(ArrayBag<PLink<String>, PLink<String>> bag, float batchSizeProp) { fillRandom(bag); testBagSamplingDistribution(bag, batchSizeProp); } static void testBagSamplingDistribution(Bag<PLink<String>, PLink<String>> bag, float batchSizeProp) { int cap = bag.capacity(); int batchSize = (int)Math.ceil(batchSizeProp * cap); int batches = cap * 1000 / batchSize; if (bag.size() < 3) return; //histogram tests wont apply int bins = Math.min(8, Math.max(3, cap/2)); Tensor f1 = samplingPriDist(bag, batches, batchSize, bins); String h = "cap=" + cap + " total=" + (batches * batchSize); // System.out.println(h + ":\n\t" + f1.tsv2()); // System.out.println(); float[] ff = f1.snapshot(); float orderThresh = 0.1f; int n = ff.length; if (ff[n-1] == 0) n--; //skip last empty histogram cell HACK if (ff[n-1] == 0) n--; //skip last empty histogram cell HACK for (int j = 0; j < n; j++) { // assertTrue(ff[j] > 0); //no zero bins for (int i = j+1; i < n; i++) { float diff = ff[j] - ff[i]; boolean unordered = diff > orderThresh; if (unordered) { fail("sampling distribution not ordered. contents=" + bag); } } } final float MIN_RATIO = 1.5f; for (int lows : n > 4 ? new int[] { 0, 1} : new int[] { 0 } ) { for (int highs : n > 4 ? new int[] { n -1, n -2} : new int[] { n -1 } ) { if (lows!=highs) { float maxMinRatio = ff[highs] / ff[lows]; assertTrue( maxMinRatio > MIN_RATIO, maxMinRatio + " ratio between max and min" ); } } } } private float maxMinRatio(@NotNull EmpiricalDistribution d) { List<SummaryStatistics> bins = d.getBinStats(); return ((float) bins.get(bins.size() - 1).getN() / (bins.get(0).getN())); } public static void testPutMinMaxAndUniqueness(Bag<Integer, PriReference<Integer>> a) { float pri = 0.5f; int n = a.capacity() * 16; for (int i = 0; i < n; i++) { a.put(new PLink((i), pri)); } a.commit(null); assertEquals(a.capacity(), a.size()); if (a instanceof ArrayBag) assertSorted((ArrayBag)a); List<Integer> keys = new FasterList(a.capacity()); a.forEachKey(keys::add); assertEquals(a.size(), keys.size()); assertEquals(new HashSet(keys).size(), keys.size()); assertEquals(pri, a.priMin(), 0.01f); assertEquals(a.priMin(), a.priMax(), 0.08f); if (a instanceof ArrayBag) assertTrue(((HijackBag)a).density() > 0.75f); } public static void populate(Bag<String, PriReference<String>> b, Random rng, int count, int dimensionality, float minPri, float maxPri, float qua) { populate(b, rng, count, dimensionality, minPri, maxPri, qua, qua); } private static void populate(Bag<String, PriReference<String>> a, Random rng, int count, int dimensionality, float minPri, float maxPri, float minQua, float maxQua) { float dPri = maxPri - minPri; for (int i = 0; i < count; i++) { a.put(new PLink( "x" + rng.nextInt(dimensionality), rng.nextFloat() * dPri + minPri) ); } a.commit(null); if (a instanceof ArrayBag) assertSorted((ArrayBag)a); } /** * fill it exactly to capacity */ public static void fillLinear(Bag<PLink<String>, PLink<String>> bag, int c) { fill(bag, c, (x)->x); assertEquals(1f / (c+1), bag.priMin(), 0.03f); assertEquals(1 - 1f/(c+1), bag.priMax(), 0.03f); } public static void fill(Bag<PLink<String>, PLink<String>> bag, int c, FloatToFloatFunction priCurve) { assertTrue(bag.isEmpty()); for (int i = c-1; i >= 0; i--) { float x = (i + 1) / (c+1f); //center of index PLink inserted = bag.put(new PLink(i + "x", priCurve.valueOf(x))); assert(inserted!=null); } bag.commit(null); assertEquals(c, bag.size()); if (bag instanceof ArrayBag) assertSorted((ArrayBag)bag); } private static void fillRandom(ArrayBag<PLink<String>, PLink<String>> bag) { assertTrue(bag.isEmpty()); int c = bag.capacity(); Random rng = new XoRoShiRo128PlusRandom(1); for (int i = c-1; i >= 0; i--) { PLink inserted = bag.put(new PLink(i + "x", rng.nextFloat())); assertTrue(inserted!=null); assertSorted(bag); } bag.commit(null); assertEquals(c, bag.size()); assertSorted(bag); } }
automenta/narchy
util/src/test/java/jcog/pri/bag/BagTest.java
Java
agpl-3.0
10,149
import { Component } from '@angular/core'; import { AuthService } from './login/auth.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; mostrarMenu: boolean = false; constructor(private authService: AuthService){ } ngOnInit(){ this.authService.mostrarProdutoEmmiter.subscribe( mostrar => this.mostrarMenu = mostrar ); } }
ricardoroberto/TesteGrpLTM
FrontEnd/Estoque.Front/src/app/app.component.ts
TypeScript
agpl-3.0
470
#include "variableswidget.h" #include "ui_variableswidget.h" #include "desktoputils.h" #include "variablespage/variablestablemodel.h" #include <QModelIndexList> #include <boost/foreach.hpp> #include <algorithm> #include <QDebug> VariablesWidget::VariablesWidget(QWidget *parent) : QWidget(parent), ui(new Ui::VariablesWidget) { ui->setupUi(this); _dataSet = NULL; _currentColumn = NULL; _levelsTableModel = new LevelsTableModel(this); ui->labelsView->setModel(_levelsTableModel); ui->columnheader->setText(""); (ui->labelsView->verticalHeader())->hide(); setToolTip("Double-click on a label to change it"); connect(ui->moveUpButton, SIGNAL(clicked()), this, SLOT(moveUpClicked())); connect(ui->moveDownButton, SIGNAL(clicked()), this, SLOT(moveDownClicked())); connect(ui->reverseButton, SIGNAL(clicked()), this, SLOT(reverseClicked())); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(close())); connect(_levelsTableModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(labelDataChanged(QModelIndex, QModelIndex))); } VariablesWidget::~VariablesWidget() { delete ui; } void VariablesWidget::setDataSet(DataSet *dataSet) { _dataSet = dataSet; _levelsTableModel->refresh(); } void VariablesWidget::clearDataSet() { _dataSet = NULL; _currentColumn = NULL; } void VariablesWidget::moveUpClicked() { QModelIndexList selection = ui->labelsView->selectionModel()->selectedIndexes(); if (selection.length() == 0) return; qSort(selection.begin(), selection.end(), qLess<QModelIndex>()); if (selection.at(0).row() == 0) return; _levelsTableModel->moveUp(selection); // Reset Selection ui->labelsView->clearSelection(); ui->labelsView->setSelectionMode(QAbstractItemView::MultiSelection); BOOST_FOREACH (QModelIndex &index, selection) { if (index.column() == 0) { ui->labelsView->selectRow(index.row() - 1); } } //ui->labelsView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->labelsView->setSelectionMode(QAbstractItemView::ExtendedSelection); if (_currentColumn != NULL) emit(columnChanged(toQStr(_currentColumn->name()))); } void VariablesWidget::moveDownClicked() { QModelIndexList selection = ui->labelsView->selectionModel()->selectedIndexes(); if (selection.length() == 0) return; qSort(selection.begin(), selection.end(), qGreater<QModelIndex>()); QModelIndex dummy = QModelIndex(); if (selection.at(0).row() >= (_levelsTableModel->rowCount(dummy) - 1)) return; _levelsTableModel->moveDown(selection); // Reset Selection ui->labelsView->clearSelection(); ui->labelsView->setSelectionMode(QAbstractItemView::MultiSelection); BOOST_FOREACH (QModelIndex &index, selection) { if (index.column() == 0) { ui->labelsView->selectRow(index.row() + 1); } } //ui->labelsView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->labelsView->setSelectionMode(QAbstractItemView::ExtendedSelection); if (_currentColumn != NULL) emit(columnChanged(toQStr(_currentColumn->name()))); } void VariablesWidget::reverseClicked() { _levelsTableModel->reverse(); ui->labelsView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->labelsView->setSelectionMode(QAbstractItemView::ExtendedSelection); if (_currentColumn != NULL) emit(columnChanged(toQStr(_currentColumn->name()))); } void VariablesWidget::setCurrentColumn(int columnnumber) { _currentColumn = &_dataSet->columns().at(columnnumber); QString columnheader(_currentColumn->name().c_str()); _levelsTableModel->setColumn(_currentColumn); ui->columnheader->setText("<b>" + columnheader + "</b>"); } void VariablesWidget::labelDataChanged(QModelIndex m1, QModelIndex m2) { if (_currentColumn != NULL) emit(columnChanged(toQStr(_currentColumn->name()))); emit(resetTableView()); }
aknight1-uva/jasp-desktop
JASP-Desktop/variableswidget.cpp
C++
agpl-3.0
3,776
""" Views related to course groups functionality. """ from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.http import require_POST from django.contrib.auth.models import User from django.core.paginator import Paginator, EmptyPage from django.core.urlresolvers import reverse from django.http import Http404, HttpResponseBadRequest from django.views.decorators.http import require_http_methods from util.json_request import expect_json, JsonResponse from django.db import transaction from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext import logging import re from opaque_keys.edx.keys import CourseKey from opaque_keys.edx.locations import SlashSeparatedCourseKey from courseware.courses import get_course_with_access from edxmako.shortcuts import render_to_response from . import cohorts from lms.djangoapps.django_comment_client.utils import get_discussion_category_map, get_discussion_categories_ids from lms.djangoapps.django_comment_client.constants import TYPE_ENTRY from .models import CourseUserGroup, CourseUserGroupPartitionGroup, CohortMembership log = logging.getLogger(__name__) def json_http_response(data): """ Return an HttpResponse with the data json-serialized and the right content type header. """ return JsonResponse(data) def split_by_comma_and_whitespace(cstr): """ Split a string both by commas and whitespace. Returns a list. """ return re.split(r'[\s,]+', cstr) def link_cohort_to_partition_group(cohort, partition_id, group_id): """ Create cohort to partition_id/group_id link. """ CourseUserGroupPartitionGroup( course_user_group=cohort, partition_id=partition_id, group_id=group_id, ).save() def unlink_cohort_partition_group(cohort): """ Remove any existing cohort to partition_id/group_id link. """ CourseUserGroupPartitionGroup.objects.filter(course_user_group=cohort).delete() # pylint: disable=invalid-name def _get_course_cohort_settings_representation(course, course_cohort_settings): """ Returns a JSON representation of a course cohort settings. """ cohorted_course_wide_discussions, cohorted_inline_discussions = get_cohorted_discussions( course, course_cohort_settings ) return { 'id': course_cohort_settings.id, 'is_cohorted': course_cohort_settings.is_cohorted, 'cohorted_inline_discussions': cohorted_inline_discussions, 'cohorted_course_wide_discussions': cohorted_course_wide_discussions, 'always_cohort_inline_discussions': course_cohort_settings.always_cohort_inline_discussions, } def _get_cohort_representation(cohort, course): """ Returns a JSON representation of a cohort. """ group_id, partition_id = cohorts.get_group_info_for_cohort(cohort) assignment_type = cohorts.get_assignment_type(cohort) return { 'name': cohort.name, 'id': cohort.id, 'user_count': cohort.users.filter(courseenrollment__course_id=course.location.course_key, courseenrollment__is_active=1).count(), 'assignment_type': assignment_type, 'user_partition_id': partition_id, 'group_id': group_id, } def get_cohorted_discussions(course, course_settings): """ Returns the course-wide and inline cohorted discussion ids separately. """ cohorted_course_wide_discussions = [] cohorted_inline_discussions = [] course_wide_discussions = [topic['id'] for __, topic in course.discussion_topics.items()] all_discussions = get_discussion_categories_ids(course, None, include_all=True) for cohorted_discussion_id in course_settings.cohorted_discussions: if cohorted_discussion_id in course_wide_discussions: cohorted_course_wide_discussions.append(cohorted_discussion_id) elif cohorted_discussion_id in all_discussions: cohorted_inline_discussions.append(cohorted_discussion_id) return cohorted_course_wide_discussions, cohorted_inline_discussions @require_http_methods(("GET", "PATCH")) @ensure_csrf_cookie @expect_json @login_required def course_cohort_settings_handler(request, course_key_string): """ The restful handler for cohort setting requests. Requires JSON. This will raise 404 if user is not staff. GET Returns the JSON representation of cohort settings for the course. PATCH Updates the cohort settings for the course. Returns the JSON representation of updated settings. """ course_key = CourseKey.from_string(course_key_string) course = get_course_with_access(request.user, 'staff', course_key) cohort_settings = cohorts.get_course_cohort_settings(course_key) if request.method == 'PATCH': cohorted_course_wide_discussions, cohorted_inline_discussions = get_cohorted_discussions( course, cohort_settings ) settings_to_change = {} if 'is_cohorted' in request.json: settings_to_change['is_cohorted'] = request.json.get('is_cohorted') if 'cohorted_course_wide_discussions' in request.json or 'cohorted_inline_discussions' in request.json: cohorted_course_wide_discussions = request.json.get( 'cohorted_course_wide_discussions', cohorted_course_wide_discussions ) cohorted_inline_discussions = request.json.get( 'cohorted_inline_discussions', cohorted_inline_discussions ) settings_to_change['cohorted_discussions'] = cohorted_course_wide_discussions + cohorted_inline_discussions if 'always_cohort_inline_discussions' in request.json: settings_to_change['always_cohort_inline_discussions'] = request.json.get( 'always_cohort_inline_discussions' ) if not settings_to_change: return JsonResponse({"error": unicode("Bad Request")}, 400) try: cohort_settings = cohorts.set_course_cohort_settings( course_key, **settings_to_change ) except ValueError as err: # Note: error message not translated because it is not exposed to the user (UI prevents this state). return JsonResponse({"error": unicode(err)}, 400) return JsonResponse(_get_course_cohort_settings_representation(course, cohort_settings)) @require_http_methods(("GET", "PUT", "POST", "PATCH")) @ensure_csrf_cookie @expect_json @login_required def cohort_handler(request, course_key_string, cohort_id=None): """ The restful handler for cohort requests. Requires JSON. GET If a cohort ID is specified, returns a JSON representation of the cohort (name, id, user_count, assignment_type, user_partition_id, group_id). If no cohort ID is specified, returns the JSON representation of all cohorts. This is returned as a dict with the list of cohort information stored under the key `cohorts`. PUT or POST or PATCH If a cohort ID is specified, updates the cohort with the specified ID. Currently the only properties that can be updated are `name`, `user_partition_id` and `group_id`. Returns the JSON representation of the updated cohort. If no cohort ID is specified, creates a new cohort and returns the JSON representation of the updated cohort. """ course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string) course = get_course_with_access(request.user, 'staff', course_key) if request.method == 'GET': if not cohort_id: all_cohorts = [ _get_cohort_representation(c, course) for c in cohorts.get_course_cohorts(course) ] return JsonResponse({'cohorts': all_cohorts}) else: cohort = cohorts.get_cohort_by_id(course_key, cohort_id) return JsonResponse(_get_cohort_representation(cohort, course)) else: name = request.json.get('name') assignment_type = request.json.get('assignment_type') if not name: # Note: error message not translated because it is not exposed to the user (UI prevents this state). return JsonResponse({"error": "Cohort name must be specified."}, 400) if not assignment_type: # Note: error message not translated because it is not exposed to the user (UI prevents this state). return JsonResponse({"error": "Assignment type must be specified."}, 400) # If cohort_id is specified, update the existing cohort. Otherwise, create a new cohort. if cohort_id: cohort = cohorts.get_cohort_by_id(course_key, cohort_id) if name != cohort.name: if cohorts.is_cohort_exists(course_key, name): err_msg = ugettext("A cohort with the same name already exists.") return JsonResponse({"error": unicode(err_msg)}, 400) cohort.name = name cohort.save() try: cohorts.set_assignment_type(cohort, assignment_type) except ValueError as err: return JsonResponse({"error": unicode(err)}, 400) else: try: cohort = cohorts.add_cohort(course_key, name, assignment_type) except ValueError as err: return JsonResponse({"error": unicode(err)}, 400) group_id = request.json.get('group_id') if group_id is not None: user_partition_id = request.json.get('user_partition_id') if user_partition_id is None: # Note: error message not translated because it is not exposed to the user (UI prevents this state). return JsonResponse( {"error": "If group_id is specified, user_partition_id must also be specified."}, 400 ) existing_group_id, existing_partition_id = cohorts.get_group_info_for_cohort(cohort) if group_id != existing_group_id or user_partition_id != existing_partition_id: unlink_cohort_partition_group(cohort) link_cohort_to_partition_group(cohort, user_partition_id, group_id) else: # If group_id was specified as None, unlink the cohort if it previously was associated with a group. existing_group_id, _ = cohorts.get_group_info_for_cohort(cohort) if existing_group_id is not None: unlink_cohort_partition_group(cohort) return JsonResponse(_get_cohort_representation(cohort, course)) @ensure_csrf_cookie def users_in_cohort(request, course_key_string, cohort_id): """ Return users in the cohort. Show up to 100 per page, and page using the 'page' GET attribute in the call. Format: Returns: Json dump of dictionary in the following format: {'success': True, 'page': page, 'num_pages': paginator.num_pages, 'users': [{'username': ..., 'email': ..., 'name': ...}] } """ # this is a string when we get it here course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string) get_course_with_access(request.user, 'staff', course_key) # this will error if called with a non-int cohort_id. That's ok--it # shouldn't happen for valid clients. cohort = cohorts.get_cohort_by_id(course_key, int(cohort_id)) paginator = Paginator(cohort.users.all(), 100) try: page = int(request.GET.get('page')) except (TypeError, ValueError): # These strings aren't user-facing so don't translate them return HttpResponseBadRequest('Requested page must be numeric') else: if page < 0: return HttpResponseBadRequest('Requested page must be greater than zero') try: users = paginator.page(page) except EmptyPage: users = [] # When page > number of pages, return a blank page user_info = [{'username': u.username, 'email': u.email, 'name': '{0} {1}'.format(u.first_name, u.last_name)} for u in users] return json_http_response({'success': True, 'page': page, 'num_pages': paginator.num_pages, 'users': user_info}) @transaction.non_atomic_requests @ensure_csrf_cookie @require_POST def add_users_to_cohort(request, course_key_string, cohort_id): """ Return json dict of: {'success': True, 'added': [{'username': ..., 'name': ..., 'email': ...}, ...], 'changed': [{'username': ..., 'name': ..., 'email': ..., 'previous_cohort': ...}, ...], 'present': [str1, str2, ...], # already there 'unknown': [str1, str2, ...]} Raises Http404 if the cohort cannot be found for the given course. """ # this is a string when we get it here course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string) get_course_with_access(request.user, 'staff', course_key) try: cohort = cohorts.get_cohort_by_id(course_key, cohort_id) except CourseUserGroup.DoesNotExist: raise Http404("Cohort (ID {cohort_id}) not found for {course_key_string}".format( cohort_id=cohort_id, course_key_string=course_key_string )) users = request.POST.get('users', '') added = [] changed = [] present = [] unknown = [] for username_or_email in split_by_comma_and_whitespace(users): if not username_or_email: continue try: (user, previous_cohort) = cohorts.add_user_to_cohort(cohort, username_or_email) info = { 'username': user.username, 'email': user.email, } if previous_cohort: info['previous_cohort'] = previous_cohort changed.append(info) else: added.append(info) except ValueError: present.append(username_or_email) except User.DoesNotExist: unknown.append(username_or_email) return json_http_response({'success': True, 'added': added, 'changed': changed, 'present': present, 'unknown': unknown}) @ensure_csrf_cookie @require_POST def remove_user_from_cohort(request, course_key_string, cohort_id): """ Expects 'username': username in POST data. Return json dict of: {'success': True} or {'success': False, 'msg': error_msg} """ # this is a string when we get it here course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string) get_course_with_access(request.user, 'staff', course_key) username = request.POST.get('username') if username is None: return json_http_response({'success': False, 'msg': 'No username specified'}) try: user = User.objects.get(username=username) except User.DoesNotExist: log.debug('no user') return json_http_response({'success': False, 'msg': "No user '{0}'".format(username)}) try: membership = CohortMembership.objects.get(user=user, course_id=course_key) membership.delete() except CohortMembership.DoesNotExist: pass return json_http_response({'success': True}) def debug_cohort_mgmt(request, course_key_string): """ Debugging view for dev. """ # this is a string when we get it here course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string) # add staff check to make sure it's safe if it's accidentally deployed. get_course_with_access(request.user, 'staff', course_key) context = {'cohorts_url': reverse( 'cohorts', kwargs={'course_key': course_key.to_deprecated_string()} )} return render_to_response('/course_groups/debug.html', context) @expect_json @login_required def cohort_discussion_topics(request, course_key_string): """ The handler for cohort discussion categories requests. This will raise 404 if user is not staff. Returns the JSON representation of discussion topics w.r.t categories for the course. Example: >>> example = { >>> "course_wide_discussions": { >>> "entries": { >>> "General": { >>> "sort_key": "General", >>> "is_cohorted": True, >>> "id": "i4x-edx-eiorguegnru-course-foobarbaz" >>> } >>> } >>> "children": ["General", "entry"] >>> }, >>> "inline_discussions" : { >>> "subcategories": { >>> "Getting Started": { >>> "subcategories": {}, >>> "children": [ >>> ["Working with Videos", "entry"], >>> ["Videos on edX", "entry"] >>> ], >>> "entries": { >>> "Working with Videos": { >>> "sort_key": None, >>> "is_cohorted": False, >>> "id": "d9f970a42067413cbb633f81cfb12604" >>> }, >>> "Videos on edX": { >>> "sort_key": None, >>> "is_cohorted": False, >>> "id": "98d8feb5971041a085512ae22b398613" >>> } >>> } >>> }, >>> "children": ["Getting Started", "subcategory"] >>> }, >>> } >>> } """ course_key = CourseKey.from_string(course_key_string) course = get_course_with_access(request.user, 'staff', course_key) discussion_topics = {} discussion_category_map = get_discussion_category_map( course, request.user, cohorted_if_in_list=True, exclude_unstarted=False ) # We extract the data for the course wide discussions from the category map. course_wide_entries = discussion_category_map.pop('entries') course_wide_children = [] inline_children = [] for name, c_type in discussion_category_map['children']: if name in course_wide_entries and c_type == TYPE_ENTRY: course_wide_children.append([name, c_type]) else: inline_children.append([name, c_type]) discussion_topics['course_wide_discussions'] = { 'entries': course_wide_entries, 'children': course_wide_children } discussion_category_map['children'] = inline_children discussion_topics['inline_discussions'] = discussion_category_map return JsonResponse(discussion_topics)
romain-li/edx-platform
openedx/core/djangoapps/course_groups/views.py
Python
agpl-3.0
19,604
/* * GCWBaseContainerComponent.cpp * * Created on: Jan 24, 2013 * Author: root */ #include "GCWBaseContainerComponent.h" #include "templates/params/creature/CreatureFlag.h" bool GCWBaseContainerComponent::checkContainerPermission(SceneObject* sceneObject, CreatureObject* creature, uint16 permission) const { ManagedReference<BuildingObject*> building = cast<BuildingObject*>(sceneObject); if (building == NULL) return false; return checkContainerPermission(building, creature, permission, false); } bool GCWBaseContainerComponent::checkContainerPermission(BuildingObject* building, CreatureObject* creature, uint16 permission, bool sendMessage) const { if (permission == ContainerPermissions::WALKIN) { if (building == NULL) { return false; } if (creature->isPlayerCreature() && creature->getPlayerObject()->hasGodMode()) return true; if (building->getPvpStatusBitmask() & CreatureFlag::OVERT) { return checkPVPPermission( building, creature, permission, sendMessage); } else { return checkPVEPermission(building, creature, permission, sendMessage); } } return StructureContainerComponent::checkContainerPermission(building, creature, permission); } bool GCWBaseContainerComponent::checkPVPPermission(BuildingObject* building, CreatureObject* creature, uint16 permission, bool sendMessage) const { PlayerObject* player = creature->getPlayerObject(); if (player == NULL) { return false; } if (creature->getFaction() == 0) { if (sendMessage) creature->sendSystemMessage("@faction/faction_hq/faction_hq_response:youre_neutral_excluded"); // This is a restricted access military structure, and you haven't aligned yourself with the military. You are not cleared to enter. return false; } if (player->getFactionStatus() != FactionStatus::OVERT) { if (sendMessage) creature->sendSystemMessage("@faction/faction_hq/faction_hq_response:youre_covert_excluded"); // You must be a member of the Special Forces to enter this structure. return false; } if (creature->getFaction() == building->getFaction()) { return true; } DataObjectComponentReference* data = building->getDataObjectComponent(); DestructibleBuildingDataComponent* baseData = NULL; if (data != NULL) { baseData = cast<DestructibleBuildingDataComponent*>(data->get()); } if (baseData == NULL) return false; if (!baseData->hasDefense()) { return true; } else { if (sendMessage) creature->sendSystemMessage("@faction_perk:destroy_turrets"); // You cannot enter this HQ until all Turrets have been destroyed. return false; } } bool GCWBaseContainerComponent::checkPVEPermission(BuildingObject* building, CreatureObject* creature, uint16 permission, bool sendMessage) const { PlayerObject* player = creature->getPlayerObject(); if (player == NULL) { return false; } if (creature->getFaction() == 0) { if (sendMessage) creature->sendSystemMessage("@faction/faction_hq/faction_hq_response:youre_neutral_excluded"); // This is a restricted access military structure, and you haven't aligned yourself with the military. You are not cleared to enter. return false; } if ((player->getFactionStatus() != FactionStatus::COVERT && player->getFactionStatus() != FactionStatus::OVERT)) { if (sendMessage) creature->sendSystemMessage("You must be at least a combatant to enter"); return false; } if (creature->getFaction() == building->getFaction()) { return true; } DataObjectComponentReference* data = building->getDataObjectComponent(); DestructibleBuildingDataComponent* baseData = NULL; if (data != NULL) { baseData = cast<DestructibleBuildingDataComponent*>(data->get()); } if (baseData != NULL) { if (!baseData->hasDefense()) { return true; } else { if (sendMessage) creature->sendSystemMessage("@faction_perk:destroy_turrets"); // You cannot enter this HQ until all Turrets have been destroyed. return false; } } else { if (creature->getFaction() != building->getFaction()) { return false; } } return true; }
Tatwi/legend-of-hondo
MMOCoreORB/src/server/zone/objects/building/components/GCWBaseContainerComponent.cpp
C++
agpl-3.0
4,046
# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano 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. # # TriSano 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 TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. When(/^I navigate to the new morbidity event page and start a simple event$/) do @browser.open "/trisano/cmrs/new" add_demographic_info(@browser, { :last_name => get_unique_name }) @browser.type('morbidity_event_first_reported_PH_date', Date.today) end When(/^I navigate to the new assessment event page and start a simple event$/) do @browser.open "/trisano/aes/new" add_demographic_info(@browser, { :last_name => get_unique_name }) @browser.type('assessment_event_first_reported_PH_date', Date.today) end When /^I go to the new CMR page$/ do @browser.open "/trisano/cmrs/new" @browser.wait_for_page_to_load end When(/^I navigate to the morbidity event edit page$/) do @browser.click "link=EVENTS" @browser.wait_for_page_to_load $load_time @browser.click "link=Edit" @browser.wait_for_page_to_load $load_time end When(/^I navigate to the assessment event edit page$/) do @browser.click "link=EVENTS" @browser.wait_for_page_to_load $load_time @browser.click "link=Edit" @browser.wait_for_page_to_load $load_time end When(/^I am on the assessment event edit page$/) do @browser.open "/trisano/aes/#{(@event).id}/edit" @browser.wait_for_page_to_load end When(/^I am on the morbidity event edit page$/) do @browser.open "/trisano/cmrs/#{(@event).id}/edit" @browser.wait_for_page_to_load end When(/^I am on the morbidity event show page$/) do @browser.open "/trisano/cmrs/#{(@event).id}" @browser.wait_for_page_to_load end # Consider refactoring the name of this one -- it really isn't # navigating, it's more like a "when I am on" -- doesn't 'I am on' # imply a verification that you are already there? When(/^I navigate to the morbidity event show page$/) do @browser.open "/trisano/cmrs/#{(@event).id}" @browser.wait_for_page_to_load end When(/^I navigate to the assessment event show page$/) do @browser.open "/trisano/aes/#{(@event).id}" @browser.wait_for_page_to_load end When /^I am on the events index page$/ do @browser.open "/trisano/events" @browser.wait_for_page_to_load end When(/^I am on the contact event edit page$/) do @browser.open "/trisano/contact_events/#{@contact_event.id}/edit" @browser.wait_for_page_to_load end When /^I navigate to the contact event edit page$/ do When "I am on the contact event edit page" end When /^I navigate to the encounter event edit page$/ do @browser.open "/trisano/encounter_events/#{(@encounter_event).id}/edit" @browser.wait_for_page_to_load end When /^I am on the encounter event edit page$/ do When "I navigate to the encounter event edit page" end When /^I navigate to the contact named "(.+)"$/ do |last_name| @contact_event = ContactEvent.first(:include => { :interested_party => { :person_entity => :person } }, :conditions => ['people.last_name = ?', last_name]) @browser.open "/trisano/contact_events/#{@contact_event.id}/edit" @browser.wait_for_page_to_load end When /^I select "([^\"]*)" from the sibling navigator$/ do |option_text| @browser.select "css=.events_nav", option_text @browser.wait_for_page_to_load end When /^I select "([^\"]*)" from the sibling navigator and Save$/ do |option_text| @browser.select "css=.events_nav", option_text @browser.wait_for_element_present "//button/span[contains(text(), 'Save')]" @browser.click "//button/span[contains(text(), 'Save')]" @browser.wait_for_page_to_load end When /^I select "([^\"]*)" from the sibling navigator and leave without saving$/ do |option_text| @browser.select "css=.events_nav", option_text @browser.wait_for_element_present "//button/span[contains(text(), 'Leave')]" @browser.click "//button/span[contains(text(), 'Leave')]" @browser.wait_for_page_to_load end When /^I select "([^\"]*)" from the sibling navigator but cancel the dialog$/ do |option_text| @browser.select "css=.events_nav", option_text @browser.wait_for_element_present "//a/span[contains(text(), 'close')]" @browser.click "//a/span[contains(text(), 'close')]" end Then /^I should be on the contact named "([^\"]*)"$/ do |last_name| @contact_event = ContactEvent.first(:include => { :interested_party => { :person_entity => :person } }, :conditions => ['people.last_name = ?', last_name]) @browser.get_location.should =~ /trisano\/contact_events\/#{@contact_event.id}\/edit/ end When /^I enter "([^\"]*)" as the contact\'s first name$/ do |text| @browser.type("css=#contact_event_interested_party_attributes_person_entity_attributes_person_attributes_first_name", text) end Then /^no value should be selected in the sibling navigator$/ do script = "selenium.browserbot.getCurrentWindow().$j('.events_nav').val();" @browser.get_eval(script).should == "" end When(/^I am on the place event edit page$/) do @browser.open "/trisano/place_events/#{(@place_event).id}/edit" @browser.wait_for_page_to_load end When /^I save and continue$/ do @browser.click("//*[@id='save_and_continue_btn']") @browser.wait_for_page_to_load end When /^I save and exit$/ do @browser.click("//*[@id='save_and_exit_btn']") @browser.wait_for_page_to_load end Then /^events list should show (\d+) events$/ do |expected_count| @browser.get_xpath_count("//div[@class='patientname']").should == expected_count end Given /^a clean events table$/ do Address.destroy_all ParticipationsRiskFactor.destroy_all Participation.destroy_all Task.destroy_all Event.destroy_all end After('@clean_events') do Address.all.each(&:delete) ParticipationsRiskFactor.destroy_all Participation.destroy_all Task.destroy_all Event.all.each(&:delete) end When /^I scroll down a bit$/ do script = "selenium.browserbot.getCurrentWindow().$j(window).scrollTop(300);" @browser.get_eval(script).should == "[object Window]" # Just making sure the script ran end Then /^I should have been scrolled back to the top of the page$/ do script = "selenium.browserbot.getCurrentWindow().$j(window).scrollTop();" @browser.get_eval(script).should == "0" end Then /^I should have a note that says "([^\"]*)"$/ do |text| @browser.get_xpath_count("//div[@id='existing-notes']//p[contains(text(), '#{text}')]").to_i.should >= 1 end When /^I enter a valid first reported to public health date$/ do @browser.type('morbidity_event_first_reported_PH_date', Date.today) end When /^I enter basic CMR data$/ do @browser.type 'morbidity_event_interested_party_attributes_person_entity_attributes_person_attributes_last_name', 'Smoker' When %{I enter a valid first reported to public health date} end
csinitiative/trisano
webapp/features/enhanced_step_definitions/event_steps.rb
Ruby
agpl-3.0
7,381
/* */ /* * Copyright (C) 2015-present ScyllaDB * * Modified by ScyllaDB */ /* * SPDX-License-Identifier: (AGPL-3.0-or-later and Apache-2.0) */ #pragma once #include <iostream> namespace db { enum class read_repair_decision { NONE, GLOBAL, DC_LOCAL }; inline std::ostream& operator<<(std::ostream& out, db::read_repair_decision d) { switch (d) { case db::read_repair_decision::NONE: out << "NONE"; break; case db::read_repair_decision::GLOBAL: out << "GLOBAL"; break; case db::read_repair_decision::DC_LOCAL: out << "DC_LOCAL"; break; default: out << "ERR"; break; } return out; } }
scylladb/scylla
db/read_repair_decision.hh
C++
agpl-3.0
632
/* Copyright (C) 2007-2017 Patrick G. Durand * * 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. * * You may obtain a copy of the License at * * https://www.gnu.org/licenses/agpl-3.0.txt * * 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. */ package bzh.plealog.dbmirror.lucenedico.go; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import bzh.plealog.dbmirror.indexer.ParserMonitor; import bzh.plealog.dbmirror.lucenedico.DicoParsable; import bzh.plealog.dbmirror.lucenedico.DicoParserException; import bzh.plealog.dbmirror.lucenedico.DicoStorageSystem; import bzh.plealog.dbmirror.lucenedico.DicoUtils; import bzh.plealog.dbmirror.util.Utils; import bzh.plealog.dbmirror.util.conf.DBMSAbstractConfig; /** * Class which parses obo file and create, for each of terms a GeneOntologyTerm * containing the name, the GO id, the ontology and the parents of the term. * * @author Patrick G. Durand * */ public class GeneOntologyOBONodeParser implements DicoParsable { // terms of the obo file private HashMap<String, GeneOntologyTerm> _nodes = new HashMap<String, GeneOntologyTerm>(); private ParserMonitor _pMonitor; private boolean _verbose = true; private int _entries; private static final Log LOGGER = LogFactory .getLog(DBMSAbstractConfig.KDMS_ROOTLOG_CATEGORY + ".GeneOntologyOBONodeParser"); private static final String ROOT_GO = "GO:0003673"; private static final String ROOT_NAME = "Gene_Ontology"; private static final String BIO_PRO_GO = "GO:0008150"; private static final String BIO_PRO_ONT = "biological_process"; private static final String MOL_FUNC_GO = "GO:0003674"; private static final String MOL_FUNC_ONT = "molecular_function"; private static final String CELL_COMP_GO = "GO:0005575"; private static final String CELL_COMP_ONT = "cellular_component"; private static final String OBSO_BIOPRO_GO = "obsolete_Bp"; private static final String OBSO_BIOPRO_NAME = "obsolete_biological_process"; private static final String OBSO_MOLFUNC_GO = "obsolete_Mf"; private static final String OBSO_MOLFUNC_NAME = "obsolete_molecular_function"; private static final String OBSO_CELLCOMP_GO = "obsolete_Cc"; private static final String OBSO_CELLCOMP_NAME = "obsolete_cellular_component"; private static final String TERM = "[Term]"; private static final String ID = "id:"; private static final String NAME = "name:"; private static final String IS_OBSOLETE = "is_obsolete:"; private static final String NAMESPACE = "namespace:"; private static final String IS_A = "is_a:"; private static final String RELATIONSHIP = "relationship:"; private static final String PART_OF = "part_of"; private static final String REGULATES = "regulates"; private static final String POSITIVELY_REGULATES = "positively_regulates"; private static final String NEGATIVELY_REGULATES = "negatively_regulates"; private static final String TYPE_DEF = "[Typedef]"; private static final String ALT_ID = "alt_id"; private static final int IS_A_LENGTH = IS_A .length(); private static final int PART_OF_LENGTH = PART_OF .length(); private static final int REGULATES_LENGTH = REGULATES .length(); private static final int POSITIVELY_REGULATES_LENGTH = POSITIVELY_REGULATES .length(); private static final int NEGATIVELY_REGULATES_LENGTH = NEGATIVELY_REGULATES .length(); private static final int RELATIONSHIP_LENGTH = RELATIONSHIP .length(); public GeneOntologyOBONodeParser() { _nodes = new HashMap<String, GeneOntologyTerm>(); _verbose = false; _entries = 0; } /** * Implementation of DicoParsable interface. */ public void setParserMonitor(ParserMonitor pm) { _pMonitor = pm; } /** * Initialize the root of the gene Ontology graph. [R O O T] / | \ bio_pro * mol_func cell_comp | | | obso_bp obso_mf obso_cc */ private void initStructure() { GeneOntologyTerm root = new GeneOntologyTerm(ROOT_GO, ROOT_NAME, null); _nodes.put(ROOT_GO, root); GeneOntologyTerm bio_p = new GeneOntologyTerm(BIO_PRO_GO, BIO_PRO_ONT, BIO_PRO_ONT); bio_p.add_parent(root, GeneOntologyTermRelationship.TYPE_EDGE.K); _nodes.put(BIO_PRO_GO, bio_p); GeneOntologyTerm mol_fun = new GeneOntologyTerm(MOL_FUNC_GO, MOL_FUNC_ONT, MOL_FUNC_ONT); mol_fun.add_parent(root, GeneOntologyTermRelationship.TYPE_EDGE.K); _nodes.put(MOL_FUNC_GO, mol_fun); GeneOntologyTerm cell_comp = new GeneOntologyTerm(CELL_COMP_GO, CELL_COMP_ONT, CELL_COMP_ONT); cell_comp.add_parent(root, GeneOntologyTermRelationship.TYPE_EDGE.K); _nodes.put(CELL_COMP_GO, cell_comp); GeneOntologyTerm o_bp = new GeneOntologyTerm(OBSO_BIOPRO_GO, OBSO_BIOPRO_NAME, BIO_PRO_ONT); o_bp.add_parent(bio_p, GeneOntologyTermRelationship.TYPE_EDGE.K); _nodes.put(OBSO_BIOPRO_GO, o_bp); GeneOntologyTerm o_mf = new GeneOntologyTerm(OBSO_MOLFUNC_GO, OBSO_MOLFUNC_NAME, MOL_FUNC_ONT); o_mf.add_parent(mol_fun, GeneOntologyTermRelationship.TYPE_EDGE.K); _nodes.put(OBSO_MOLFUNC_GO, o_mf); GeneOntologyTerm o_cc = new GeneOntologyTerm(OBSO_CELLCOMP_GO, OBSO_CELLCOMP_NAME, CELL_COMP_ONT); o_cc.add_parent(cell_comp, GeneOntologyTermRelationship.TYPE_EDGE.K); _nodes.put(OBSO_CELLCOMP_GO, o_cc); _entries = 6; } /** * Create and inquire the differents fields of the GeneOntologyTerm created * from parsed term. * * @param file * the file ro process * @param goIdTerm * GO id of the term obtained by the "id" field * @param nameAndOntology * of the term obtained by the "name" field * @param id_parent * fathers of the term obtained by the "is_a/part_of/regulate" field * @param edge * type of the link between a term's parent and the term. depends on * "is_a/part_of/regulate" field * @param alternative_id * alternative GO id of the term obtained by the "alt_id" field * @param curPos * current position in the file (butes) */ private void handleData(String file, String goIdTerm, String nameAndOntology, ArrayList<String> id_parent, ArrayList<GeneOntologyTermRelationship.TYPE_EDGE> edge, ArrayList<String> alternative_id, long curPos) { GeneOntologyTerm son; GeneOntologyTerm father; // Ignore the root to avoid bugs if (goIdTerm != null && !goIdTerm.equals(ROOT_GO) && nameAndOntology != null) { if (!_nodes.containsKey(goIdTerm)) { son = new GeneOntologyTerm(goIdTerm, nameAndOntology); _nodes.put(goIdTerm, son); } else if (_nodes.get(goIdTerm).get_node_name() == null) { son = _nodes.get(goIdTerm); son.set_node_ontology(nameAndOntology); son.set_node_name(nameAndOntology); son.set_node_nameAndOntology(nameAndOntology); } else { son = _nodes.get(goIdTerm); } if (_pMonitor != null) { _pMonitor.seqFound(goIdTerm, nameAndOntology, file, curPos, curPos, false); } // For each father of the term scanned for (int i = 0; i < id_parent.size(); i++) { if (!_nodes.containsKey(id_parent.get(i))) { father = new GeneOntologyTerm(id_parent.get(i)); son.add_parent(father, edge.get(i)); _nodes.put(father.get_node_id(), father); } else { father = _nodes.get(id_parent.get(i)); // add the father to the fatherlist of the current term and add the // current term as son in the sonlist of the father term son.add_parent(father, edge.get(i)); } } if (!alternative_id.isEmpty()) { for (String alt_id : alternative_id) { _nodes.put(alt_id, son); } } if (_verbose && (_entries % 5000) == 0) { System.out.println("Nb term parsed: " + _entries); } } } public static String prepareTerm(String name, String ontology) { StringBuffer buf = new StringBuffer(); buf.delete(0, buf.length()); buf.append(DicoUtils.GO_NAME_KEY); buf.append(name); buf.append("|"); buf.append(DicoUtils.GO_ONTO_KEY); if (ontology != null) buf.append(ontology); else buf.append("unknown"); return buf.toString(); } /** * Parse the obo file */ public void parse(String file, DicoStorageSystem ss) throws DicoParserException { BufferedReader reader = null; String line; String go_iD = null; String go_name = null; String type = null; String termPrepared; String alt_id_term; String ontology = null; ArrayList<String> go_parent = new ArrayList<String>(); ArrayList<GeneOntologyTermRelationship.TYPE_EDGE> typeEdge = new ArrayList<GeneOntologyTermRelationship.TYPE_EDGE>(); ArrayList<String> alt_id = new ArrayList<String>(); int endOfLineSize, termCounter = 0; long curPos = 0; boolean stop = false; try { _entries = 0; initStructure(); endOfLineSize = Utils.getLineTerminatorSize(file); reader = new BufferedReader(new InputStreamReader(new FileInputStream( file), "UTF-8")); if (_pMonitor != null) { _pMonitor.startProcessingFile(file, new File(file).length()); } while ((line = reader.readLine()) != null && !stop) { if (line.startsWith(TERM)) { termCounter++; termPrepared = prepareTerm(go_name, ontology); handleData(file, go_iD, termPrepared, go_parent, typeEdge, alt_id, curPos); go_iD = ontology = go_name = type = null; go_parent.clear(); typeEdge.clear(); alt_id.clear(); } else if (line.startsWith(ID)) { go_iD = line.substring(3).trim(); } else if (line.startsWith(NAME)) { go_name = line.substring(5).trim(); } else if (line.startsWith(NAMESPACE)) { ontology = line.substring(10).trim(); } else if (line.startsWith(IS_OBSOLETE)) { typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.O); if (ontology.equals(BIO_PRO_ONT)) { go_parent.add(OBSO_BIOPRO_GO); } else if (ontology.equals(MOL_FUNC_ONT)) { go_parent.add(OBSO_MOLFUNC_GO); } else if (ontology.equals(CELL_COMP_GO)) { go_parent.add(OBSO_CELLCOMP_GO); } } else if (line.startsWith(IS_A)) { typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.I); type = line.substring(IS_A_LENGTH + 1).trim().split("!")[0].trim(); go_parent.add(type); } else if (line.startsWith(RELATIONSHIP)) { type = line.substring(RELATIONSHIP_LENGTH + 1).trim().split("!")[0] .trim(); if (type.startsWith(PART_OF)) { typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.P); go_parent.add(type.substring(PART_OF_LENGTH + 1)); } else if (type.startsWith(REGULATES)) { typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.R); go_parent.add(type.substring(REGULATES_LENGTH + 1)); } else if (type.startsWith(POSITIVELY_REGULATES)) { typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.U); go_parent.add(type.substring(POSITIVELY_REGULATES_LENGTH + 1)); } else if (type.startsWith(NEGATIVELY_REGULATES)) { typeEdge.add(GeneOntologyTermRelationship.TYPE_EDGE.N); go_parent.add(type.substring(NEGATIVELY_REGULATES_LENGTH + 1)); } } else if (line.startsWith(TYPE_DEF)) { stop = true; } else if (line.startsWith(ALT_ID)) { alt_id_term = line.substring(7).trim(); alt_id.add(alt_id_term); } curPos += (long) (line.length() + endOfLineSize); } // handle last term termPrepared = prepareTerm(go_name, ontology); handleData(file, go_iD, termPrepared, go_parent, typeEdge, alt_id, curPos); // add Term in a Lucene index indexingSequences(ss); } catch (Exception e) { String msg = "Error while parsing GeneOntology entry no. " + (termCounter + 1); LOGGER.warn(msg + ": " + e); throw new DicoParserException(msg + ": " + e.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } if (_pMonitor != null) { _pMonitor.stopProcessingFile(file, _entries); } } if (_entries == 0) throw new DicoParserException("Data file does not contain any terms."); } public HashMap<String, GeneOntologyTerm> get_nodes() { return _nodes; } /** * For each term found, we add it in a Lucene index * * @param ss * link to index */ private void indexingSequences(DicoStorageSystem ss) { GeneOntologyTerm term; Object[] keys = _nodes.keySet().toArray(); int size; size = keys.length; _entries += size; for (int i = 0; i < size; i++) { term = _nodes.get(keys[i]); if (ss != null) { ss.addBinaryEntry((String) keys[i], term); } } } /** * Implementation of DicoParsable interface. */ public void setVerbose(boolean verbose) { _verbose = verbose; } public int getTerms() { return _entries; } }
pgdurand/BeeDeeM
src/bzh/plealog/dbmirror/lucenedico/go/GeneOntologyOBONodeParser.java
Java
agpl-3.0
15,713
#coding:utf-8 from openerp.osv import osv,fields class rainsoft_stock_return(osv.Model): _inherit='stock.return.picking' _defaults={ 'invoice_state': '2binvoiced', }
kevin8909/xjerp
openerp/addons/Rainsoft_Xiangjie/rainsoft_stock_return.py
Python
agpl-3.0
185
<?php /* * Copyright 2007-2015 Abstrium <contact (at) pydio.com> * This file is part of Pydio. * * Pydio 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. * * Pydio 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 Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <https://pydio.com>. */ namespace Pydio\OCS; use GuzzleHttp\Client; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Pydio\Cache\Core\CacheStreamLayer; use Pydio\Core\Exception\PydioException; use Pydio\Core\Model\Context; use Pydio\Core\Model\ContextInterface; use Pydio\Core\Services\ConfService; use Pydio\Core\Utils\Vars\InputFilter; use Pydio\Log\Core\Logger; use Pydio\OCS\Client\OCSClient; use Pydio\OCS\Model\SQLStore; use Zend\Diactoros\Response\JsonResponse; defined('AJXP_EXEC') or die('Access not allowed'); /** * Class ActionsController * @package Pydio\OCS */ class ActionsController { private $configs; /** * ActionsController constructor. * @param $configs */ public function __construct($configs){ $this->configs = $configs; } /** * @param ServerRequestInterface $request * @param ResponseInterface $response * @return null * @throws PydioException * @throws \Exception */ public function switchAction(ServerRequestInterface &$request, ResponseInterface &$response) { /** @var ContextInterface $ctx */ $ctx = $request->getAttribute("ctx"); $action = $request->getAttribute("action"); $httpVars = $request->getParsedBody(); switch($action){ case "user_list_authorized_users": if(isSet($httpVars['trusted_server_id'])){ $this->forwardUsersListToRemote($request, $response); } break; case "accept_invitation": $remoteShareId = InputFilter::sanitize($httpVars["remote_share_id"], InputFilter::SANITIZE_ALPHANUM); $store = new SQLStore(); $remoteShare = $store->remoteShareById($remoteShareId); if($remoteShare === null){ throw new PydioException("Cannot find remote share with ID ".$remoteShareId); } $client = new OCSClient(); $client->acceptInvitation($remoteShare); $remoteShare->setStatus(OCS_INVITATION_STATUS_ACCEPTED); $store->storeRemoteShare($remoteShare); $urlBase = $ctx->getUrlBase(); CacheStreamLayer::clearDirCache($urlBase); CacheStreamLayer::clearStatCache($urlBase . "/" . $remoteShare->getDocumentName()); $remoteCtx = new Context($remoteShare->getUser(), "ocs_remote_share_" . $remoteShare->getId()); CacheStreamLayer::clearStatCache($remoteCtx->getUrlBase()); break; case "reject_invitation": $remoteShareId = InputFilter::sanitize($httpVars["remote_share_id"], InputFilter::SANITIZE_ALPHANUM); $store = new SQLStore(); $remoteShare = $store->remoteShareById($remoteShareId); if($remoteShare === null){ throw new PydioException("Cannot find remote share with ID ".$remoteShareId); } $client = new OCSClient(); try { $client->declineInvitation($remoteShare); } catch (\Exception $e) { // If the reject fails, we still want the share to be removed from the db Logger::error(__CLASS__,"Exception",$e->getMessage()); } $store->deleteRemoteShare($remoteShare); ConfService::getInstance()->invalidateLoadedRepositories(); $urlBase = $ctx->getUrlBase(); CacheStreamLayer::clearDirCache($urlBase); CacheStreamLayer::clearStatCache($urlBase . "/" . $remoteShare->getDocumentName()); $remoteCtx = new Context($remoteShare->getUser(), "ocs_remote_share_" . $remoteShare->getId()); CacheStreamLayer::clearStatCache($remoteCtx->getUrlBase()); break; default: break; } return null; } /** * @param ServerRequestInterface $request * @param ResponseInterface $responseInterface * @throws PydioException */ protected function forwardUsersListToRemote(ServerRequestInterface &$request, ResponseInterface &$responseInterface){ $httpVars = $request->getParsedBody(); $searchQuery = InputFilter::sanitize($httpVars['value'], InputFilter::SANITIZE_HTML_STRICT); $trustedServerId = InputFilter::sanitize($httpVars['trusted_server_id'], InputFilter::SANITIZE_ALPHANUM); if(!isSet($this->configs["TRUSTED_SERVERS"]) || !isSet($this->configs["TRUSTED_SERVERS"][$trustedServerId])){ throw new PydioException("Cannot find trusted server with id " . $trustedServerId); } $serverData = $this->configs["TRUSTED_SERVERS"][$trustedServerId]; $url = $serverData['url'] . '/api/pydio/user_list_authorized_users/' . $searchQuery; $params = [ 'format' => 'json', 'users_only' => 'true', 'existing_only' => 'true', 'exclude_current' => 'false' ]; $client = new Client(); $postResponse = $client->post($url, [ 'headers' => [ 'Authorization' => 'Basic ' . base64_encode($serverData['user'] . ':' . $serverData['pass']) ], 'body' => $params ]); $body = $postResponse->getBody()->getContents(); $jsonContent = json_decode($body); foreach($jsonContent as $userEntry){ $userEntry->trusted_server_id = $trustedServerId; $userEntry->trusted_server_label = $serverData['label']; } $httpVars['processed'] = true; $request = $request->withParsedBody($httpVars); $responseInterface = new JsonResponse($jsonContent); } }
ChuckDaniels87/pydio-core
core/src/plugins/core.ocs/src/ActionsController.php
PHP
agpl-3.0
6,752
/* This file is part of ContentManager. ContentManager 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. ContentManager 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 ContentManager. If not, see <http://www.gnu.org/licenses/>. */ var messageHandler = { displayInfoMessage : function (message) { var messageJson = {messageClass : "alert-info", message : message} $("#app-message").html(Mustache.render($('#message-template').html() ,messageJson)); setTimeout(function(){ $("#app-message").html(''); },1500) }, displayLoadMessage : function (message) { var messageJson = {message : message} $("#app-message").html(Mustache.render($('#message-template').html() ,messageJson)); }, displayErrorMessage : function (message) { var messageJson = {messageClass : "alert-danger", message : message} $("#app-message").html(Mustache.render($('#message-template').html() ,messageJson)); setTimeout(function(){ $("#app-message").html(''); },3000) }, resetMessage : function(){ $("#app-message").html(Mustache.render($('#message-template').html() ,{})); }, showJiveErrorMessage : function(message){ osapi.jive.core.container.sendNotification( {'message':message, 'severity' : 'error'} ); }, getCurrentMessage : function(){ return $("#app-message").text() }, displayTagErrorMessage : function (message) { var messageJson = {messageClass : "alert-danger", message : message} $("#tag-message").html(Mustache.render($('#message-template').html() ,messageJson)); setTimeout(function(){ $("#tag-message").html(''); },1500) }, displayCategoryErrorMessage : function(message){ var messageJson = {messageClass : "alert-danger", message : message} $("#category-message").html(Mustache.render($('#message-template').html() ,messageJson)); setTimeout(function(){ $("#category-message").html(''); },1500) } }
siddharthadeshpande89/jive-content-manager
apps/content_manager/public/javascripts/helpers/messageViewHandler.js
JavaScript
agpl-3.0
2,511
var origShow = jQuery.fn.show, origHide = jQuery.fn.hide; jQuery.fn.show = function() { $(this).removeClass("hidden"); return origShow.apply(this, arguments); }; jQuery.fn.hide = function() { $(this).addClass("hidden"); return origHide.apply(this, arguments); }; $.ajaxSetup({ cache: false }); function onBlur() { document.body.className = 'blurred'; } function onFocus() { document.body.className = 'focused'; } function getNotification(type) { sendRequest({type: type}, "notifications", "get", function(res) { $("#notification-dropdown").html(function() { var str = ""; if (type !== "messages") { if (res.result !== null && typeof res.result !== "undefined" && res.result.length > 0) { for (x in res.result) str += tmpl("notification-" + type, res.result[x]); } else str = tmpl("notification-empty", {}); return str; } else if (type === "messages") { if (res.conversations !== null && typeof res.conversations !== "undefined" && res.conversations.length > 0) { $.getJSON(siteurl + "style/" + design + "/img/emoticons/emoticons.json", function(data) { smileys = new Array(); for (x in data) smileys[data[x]] = '<img src="' + siteurl + 'style/' + design + '/img/emoticons/' + data[x] + '.png" class="message-smiley" data-key="' + data[x] + '">'; for (con in res.conversations) { var c = res.conversations[con], i = 0, image = null; if (c.users !== null && typeof c.users === "string") { us = c.users.split(","), userstring = ""; for (user in us) { if (i === 2) { userstring += ", +" + (us.length - 2); break; } var tmp = us[user].split("|"); userstring += ", " + tmp[0]; i++; } userstring = userstring.substr(2); } else if (c.users !== null & typeof c.users === "object") { // there is only one user userstring = c.users.name; image = c.users.pimg; } else userstring = "None"; c.message = c.message.substr(0, 35); for (x in smileys) c.message = replaceAll('[:' + x + ':]', smileys[x], c.message); str += tmpl("notification-messages", {name: userstring, message: c.message, conversation: c.conversation, sendername: c.sendername, time: c.time, image: checkImage(image, "users", "cr_")}); } $("#notification-dropdown").html(str); return; }); } else return tmpl("notification-empty", {}); } }).removeClass("notification-messages notification-friends notification-general").addClass("notification-" + type).show(); }); } function sendRequest(requestData, module, action, callback) { if (typeof requestData !== "undefined") { return $.ajax({ url: convertUrl({module: module, action: action}), dataType: "json", data: requestData, type: 'POST', success: function(data) { if (typeof data.session !== "undefined" && data.session === 0) { alert("Your session is timed out! Please login again!"); location.href = convertUrl({module: "start"}); } else if (data.status == false) { if (typeof data.msg == "undefined") data.msg = "Error"; bootbox.alert(data.msg); } else if (typeof callback == 'function') { callback(data); refreshTime(); } } }); } return null; } function convertUrl(data) { if (modrewrite) { var str = siteurl + data.module; if (typeof data.action !== "undefined" && data.action !== null) str += "/" + data.action; if (typeof data.x !== "undefined" && data.x !== null) str += "/" + data.x; if (typeof data.y !== "undefined" && data.y !== null) str += "/" + data.y; return str; } else { var str = siteurl + "index.php?m=" + data.module; if (typeof data.action !== "undefined" && data.x !== null) str += "&action=" + data.action; if (typeof data.x !== "undefined" && data.x !== null) str += "&x=" + data.y; if (typeof data.y !== "undefined" && data.x !== null) str += "&y=" + data.y; return str; } } function checkImage(filename, type, prefix) { prefix = (typeof prefix === "undefined") ? "" : prefix; if (filename === null || typeof filename === "undefined" || filename.length === 0) return siteurl + 'style/' + design + '/img/placeholders/noimg-' + type + '.png'; return prefix + filename; } function getErrorMessage(tplname) { return tmpl(tplname, {}); } function like(ref_name, ref_id, callback) { sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "like", callback); } function dislike(ref_name, ref_id, callback) { sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "dislike", callback); } function unlike(ref_name, ref_id, callback) { sendRequest({"ref_name": ref_name, "ref_id": ref_id}, "likes", "unlike", callback); } function comment(ref_name, ref_id, content, callback) { sendRequest({"ref_name": ref_name, "ref_id": ref_id, "content": content}, "comments", "add", callback); } function deleteComment(comment_id) { bootbox.confirm("Are You sure you want to delete this comment?", function(r) { if (r) { sendRequest({"comment_id": comment_id}, "comments", "remove", function() { $("#comment-" + comment_id).remove(); }); } }); } function getLikes(refname, refid, dislike, title) { sendRequest({"ref_name": refname, "ref_id": refid, "dislike": dislike}, "likes", "get", function(res) { if (typeof res.likes !== "undefined" && res.likes.length > 0) { bootbox.dialog({ message: function() { var msg = ""; for (x in res.likes) msg += tmpl("like-list", res.likes[x]); return '<div class="likesmodalbox">' + msg + '</div>'; }, title: title, buttons: { main: { label: "Ok", className: "btn-primary" } }, className: "likelistmodal" }); } }); } function refreshTime() { $(".timestring").each(function() { var el = $(this); el.replaceWith(function() { return convertDate(el.data("source")); }); }); $(".tooltip").remove(); $(".tooltip-trigger").tooltip({ container: 'body' }); } function convertDate(timestring) { if (typeof timestring == "undefined" || timestring === "" || timestring === null) return "NaN"; var now = new Date(); var then = new Date(timestring.replace(/-/g, '/')); var r = ""; then.setMinutes(then.getMinutes() + now.getTimezoneOffset() * (-1)); var since = Math.round((now.getTime() - then.getTime()) / 1000); var chunks = [ [22896000, 'year'], [2592000, 'month'], [604800, 'week'], [86400, 'day'], [3600, 'hour'], [60, 'minute'] ]; if (since < 60) r = "just now"; else { var count; for (i = 0, j = chunks.length; i < j; i++) { seconds = chunks[i][0]; name = chunks[i][1]; count = Math.floor(since / seconds); if (count !== 0) break; } r = ((count === 1) ? '1 ' + name : count + " " + name + "s") + " ago"; } return '<span class="tooltip-trigger timestring" data-source="' + timestring + '" data-title="' + then.toLocaleString() + '">' + r + '</span>'; } function escapeRegExp(string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } function replaceAll(find, replace, str) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } $(document).ready(function() { if (/*@cc_on!@*/false) { // check for Internet Explorer document.onfocusin = onFocus; document.onfocusout = onBlur; } else { window.onfocus = onFocus; window.onblur = onBlur; } $(".sidebar").css("minHeight", window.innerHeight - 101); $('input.filefakeinput').change(function() { $($(this).data("rel")).val($(this).val()); }); $('.dropdown-menu').on('click', function(e) { if ($(this).hasClass('dropdown-checkbox-menu')) { e.stopPropagation(); } }); $('.btn[data-loading-text]').click(function() { $(this).button('loading'); }); $("a[href=\"#\"],a[href=\"\"]").click(function(e) { e.preventDefault(); }); $("#mobile-slide-nav > .mobile-menu").html($(".main-menu > .nav").html()); $(document).on("click", "#menu-trigger", function() { if (login) { if ($("body").hasClass("menu-active")) $("body").removeClass("menu-active"); else $("body").addClass("menu-active"); } else location.href = convertUrl({module: "start"}); }).on("mouseenter", ".notification-general-item:not(.read)", function() { var el = $(this); sendRequest({id: el.data("id")}, "notifications", "markRead", function() { el.addClass("read"); el.find(".label-new").fadeOut("slow"); }); }); if (login) { //Load unread messages badge sendRequest({type: "messages"}, "notifications", "get", function(res) { if (typeof res.conversations !== "undefined" && res.conversations.length > 0) { $(".main-menu-item-messages > a > .badge").html(res.conversations.length); $(".notification-link-messages").addClass("active"); } else $(".notification-link-messages").removeClass("active"); }); sendRequest({type: "friends"}, "notifications", "get", function(res) { if (typeof res.result !== "undefined" && res.result !== null && res.result.length > 0) { $(".main-menu-item-friends > a > .badge").html(res.result.length); $(".notification-link-friends").addClass("active"); } else $(".notification-link-friends").removeClass("active"); }); sendRequest({type: "general"}, "notifications", "get", function(res) { if (res.new > 0) $(".notification-link-general").addClass("active"); else $(".notification-link-general").removeClass("active"); }); } $(document).on("click", "a.close", function(e) { e.stopPropagation(); }); $(document).on("submit", "form.ajaxform", function(e) { e.preventDefault(); var form = $(this); form.find("input[type='submit'],button[type='submit']").button('loading'); if (form.prop("ajaxform-send") === true) return; if (form.attr("enctype") === "multipart/form-data") { var name = "ajaxformframe" + Math.random(); var frame = $("<iframe/>", {"name": name, class: "hidden"}).appendTo(form); form.attr("target", name).prop("ajaxform-send", true).submit(); frame.on("load", function() { form.find("input[type='submit'],button[type='submit']").button('reset'); if (form.find(".ajaxform-callback").length > 0) { console.log(frame.contents().find('body').html()); var callback = window[form.find(".ajaxform-callback").val()]; if (typeof callback === "function") callback(jQuery.parseJSON(frame.contents().find('body').html())); } }); } else { $.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serialize(), dataType: "json" }).done(function(data) { form.find("input[type='submit'],button[type='submit']").button('reset'); if (form.find(".ajaxform-callback").length > 0) { var callback = window[form.find(".ajaxform-callback").val()]; if (data.status === false) { bootbox.alert(data.msg); } else if (typeof callback === "function") callback(data); } }); } }).on("click", function(e) { if ($(e.target).attr("id") !== "notification-dropdown" && $("#notification-dropdown").length > 0) $("#notification-dropdown").hide(); }); $("#infoModal").on('show.bs.modal', function(e) { $("#infoModal").find(".modal-title").html($(e.relatedTarget).data("title")); if (typeof $(e.relatedTarget).data("href") !== "undefined") $("#infoModal").find(".modal-body").html('<iframe src="' + $(e.relatedTarget).data("href") + '" style="border:0;width:100%"></iframe>').css("padding", 10); }); $("*[data-moveto]").each(function() { $(this).appendTo($(this).data("moveto")).removeAttr("data-moveto"); }); });
kolplex/cunity
style/CunityRefreshed/javascript/cunity-core.js
JavaScript
agpl-3.0
14,280
# encoding: utf-8 require './test/test_helper' describe ArtistasController do let(:artista) { create(:artista) } describe 'anónimamente' do it 'accede al index' do get :index must_respond_with :success assigns(:artistas).wont_be_nil end it 'muestra un artista' do get :show, id: artista must_respond_with :success end it 'no accede a edit' do get :edit, id: artista must_redirect_to :root end it 'no actualiza' do put :update, id: artista, artista: attributes_for(:artista) must_redirect_to :root end it 'no destruye' do delete :destroy, id: artista must_redirect_to :root end end describe 'logueado' do before { loguearse } describe 'con permisos' do it 'accede a edit' do autorizar { get :edit, id: artista } must_respond_with :success end it 'actualiza' do autorizar { put :update, id: artista, artista: { nombre: 'Juan Salvo' } } must_redirect_to assigns(:artista) artista.reload.nombre.must_equal 'Juan Salvo' end it 'destruye' do artista.must_be :persisted? lambda do autorizar { delete :destroy, id: artista } end.must_change 'Artista.count', -1 must_redirect_to artistas_path end end end end
mauriciopasquier/bibliotecadeleter
test/controllers/artistas_controller_test.rb
Ruby
agpl-3.0
1,366
/* Code for Life Copyright (C) 2015, Ocado Innovation Limited 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/>. ADDITIONAL TERMS – Section 7 GNU General Public Licence This licence does not grant any right, title or interest in any “Ocado” logos, trade names or the trademark “Ocado” or any other trademarks or domain names owned by Ocado Innovation Limited or the Ocado group of companies or any other distinctive brand features of “Ocado” as may be secured from time to time. You must not distribute any modification of this program using the trademark “Ocado” or claim any affiliation or association with Ocado or its employees. You are not authorised to use the name Ocado (or any of its trade names) or the names of any author or contributor in advertising or for publicity purposes pertaining to the distribution of this program, without the prior written authorisation of Ocado. Any propagation, distribution or conveyance of this program must include this copyright notice and these terms. You must not misrepresent the origins of this program; modified versions of the program must be marked as such and not identified as the original program. */ 'use strict'; var ocargo = ocargo || {}; var Blockly = Blockly || {}; function initCustomBlocks() { initCustomBlocksDescription(); initCustomBlocksPython(); } function initCustomBlocksDescription() { Blockly.Blocks['start'] = { // Beginning block - identifies the start of the program init: function() { ocargo.blocklyControl.numStartBlocks++; this.setColour(50); this.appendDummyInput() .appendField('Start') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + CHARACTER_EN_FACE_URL, ocargo.BlocklyControl.BLOCK_CHARACTER_HEIGHT, ocargo.BlocklyControl.BLOCK_CHARACTER_WIDTH)); this.setNextStatement(true, 'Action'); this.setTooltip('The beginning of the program'); this.setDeletable(false); } }; /*****************/ /* Action Blocks */ /*****************/ Blockly.Blocks['move_forwards'] = { // Block for moving forward init: function() { this.setColour(160); this.appendDummyInput() .appendField('move forwards') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/forward.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Move the van forwards'); } }; Blockly.Blocks['turn_left'] = { // Block for turning left init: function() { this.setColour(160); this.appendDummyInput() .appendField('turn left') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 38, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/left.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Turn the van left'); } }; Blockly.Blocks['turn_right'] = { // Block for turning right init: function() { this.setColour(160); this.appendDummyInput() .appendField('turn right') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 29, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/right.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Turn the van right'); } }; Blockly.Blocks['turn_around'] = { // Block for turning around init: function() { this.setColour(160); this.appendDummyInput() .appendField('turn around') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 12, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/turn_around.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Turn the van around'); } }; Blockly.Blocks['wait'] = { // Block for not moving the van for a time init: function() { this.setColour(160); this.appendDummyInput() .appendField('wait') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 60, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/wait.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Keep the van stationary'); } }; Blockly.Blocks['deliver'] = { // Block for delivering (only on levels with multiple destinations) init: function() { this.setColour(160); this.appendDummyInput() .appendField('deliver') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 43, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'actions/deliver.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Deliver the goods from the van'); } }; Blockly.Blocks['puff_up'] = { // Block for puffing up the van init: function() { this.setColour(330); this.appendDummyInput() .appendField('puff up') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 43, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'EventAction'); this.setNextStatement(false); this.setTooltip('Puff up the van to scare away the cows'); } }; Blockly.Blocks['sound_horn'] = { // Block for puffing up the van init: function() { this.setColour(330); this.appendDummyInput() .appendField('sound horn') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 43, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.IMAGE_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); this.setPreviousStatement(true, 'EventAction'); this.setNextStatement(false); this.setTooltip('Sound the horn to scare away the cows'); } }; /*****************/ /* Conditions */ /*****************/ Blockly.Blocks['road_exists'] = { init: function() { var BOOLEANS = [['road exists forward', 'FORWARD'], ['road exists left', 'LEFT'], ['road exists right', 'RIGHT']]; this.setColour(210); this.setOutput(true, 'Boolean'); this.appendDummyInput() .appendField(new Blockly.FieldDropdown(BOOLEANS), 'CHOICE') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); } }; Blockly.Blocks['traffic_light'] = { init: function() { var BOOLEANS = [['traffic light red', ocargo.TrafficLight.RED], ['traffic light green', ocargo.TrafficLight.GREEN]]; this.setColour(210); this.setOutput(true, 'Boolean'); this.appendDummyInput() .appendField(new Blockly.FieldDropdown(BOOLEANS), 'CHOICE') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); } }; Blockly.Blocks['dead_end'] = { init: function() { this.setColour(210); this.setOutput(true, 'Boolean'); this.appendDummyInput() .appendField('is dead end') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); } }; Blockly.Blocks['at_destination'] = { init: function() { this.setColour(210); this.setOutput(true, 'Boolean'); this.appendDummyInput() .appendField('at destination') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); } }; /****************/ /* Procedures */ /****************/ Blockly.Blocks['call_proc'] = { // Block for calling a defined procedure init: function() { var name = ''; this.setColour(260); this.appendDummyInput() .appendField('Call') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', 7, ocargo.BlocklyControl.BLOCK_HEIGHT)) .appendField(new Blockly.FieldTextInput(name),'NAME'); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Call'); } }; Blockly.Blocks['declare_proc'] = { // Block for declaring a procedure init: function() { var name = ''; this.setColour(260); this.appendDummyInput() .appendField('Define') .appendField(new Blockly.FieldTextInput(name),'NAME'); this.appendStatementInput('DO') .setCheck('Action') .appendField('Do'); this.setTooltip('Declares the procedure'); this.statementConnection_ = null; } }; /****************/ /* Events */ /****************/ Blockly.Blocks['declare_event'] = { // Block for declaring an event handler init: function() { this.setColour(260); var dropdown = new Blockly.FieldDropdown([['white', ocargo.Cow.WHITE], ['brown', ocargo.Cow.BROWN]], function(option) { var imageUrl = ocargo.Drawing.imageDir + ocargo.Drawing.cowUrl(option); this.sourceBlock_.getField('IMAGE').setValue(imageUrl); }); this.appendDummyInput('Event') .appendField('On ') .appendField(dropdown, 'TYPE') .appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + ocargo.Drawing.whiteCowUrl, ocargo.BlocklyControl.COW_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT), 'IMAGE'); this.getField('IMAGE').EDITABLE = true; //saves the image path as well in the XML this.appendStatementInput('DO') .setCheck('EventAction') .appendField('Do'); this.setTooltip('Declares the event handler'); this.statementConnection_ = null; }, }; /*******************/ /* Control Flows */ /*******************/ Blockly.Blocks['controls_repeat_while'] = { // Block for repeat while init: function() { this.setColour(120); this.appendValueInput("condition") .setCheck("Boolean") .appendField("repeat while"); this.appendStatementInput("body") .setCheck("Action") .appendField("do"); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('While a value is true, do some statements'); } }; Blockly.Blocks['controls_repeat_until'] = { // Block for repeat until init: function() { this.setColour(120); this.appendValueInput("condition") .setCheck("Boolean") .appendField("repeat until"); this.appendStatementInput("body") .setCheck("Action") .appendField("do"); this.setPreviousStatement(true, 'Action'); this.setNextStatement(true, 'Action'); this.setTooltip('Until a value is true, do some statements'); } }; // Set text colour to red var textBlock = Blockly.Blocks['text']; var originalTextInit = textBlock.init; textBlock.init = function() { originalTextInit.call(this); this.setColour(260); }; //Customise controls_repeat block to not allow more than a sensible number of repetitions var controlsRepeatBlock = Blockly.Blocks['controls_repeat']; var originalInit = controlsRepeatBlock.init; controlsRepeatBlock.init = function () { originalInit.call(this); this.setPreviousStatement(!0, 'Action'); this.setNextStatement(!0, 'Action'); this.inputList[1].setCheck('Action'); //Disallow event action blocks to be in body var input = this.inputList[0]; var field = input.fieldRow[1]; field.changeHandler_ = function(text) { var n = Blockly.FieldTextInput.numberValidator(text); if (n) { n = String(Math.min(Math.max(0, Math.floor(n)), 20)); } return n; }; }; // Make 'not' taller var notBlock = Blockly.Blocks['logic_negate']; var originalNotInit = notBlock.init; notBlock.init = function () { originalNotInit.call(this); this.inputList[0].appendField(new Blockly.FieldImage(ocargo.Drawing.imageDir + 'empty.svg', ocargo.BlocklyControl.EXTRA_BLOCK_WIDTH, ocargo.BlocklyControl.BLOCK_HEIGHT)); }; } function initCustomBlocksPython() { Blockly.Python['start'] = function(block) { return ''; }; Blockly.Python['move_forwards'] = function(block) { return 'v.move_forwards()\n'; }; Blockly.Python['turn_left'] = function(block) { return 'v.turn_left()\n'; }; Blockly.Python['turn_right'] = function(block) { return 'v.turn_right()\n'; }; Blockly.Python['turn_around'] = function(block) { return 'v.turn_around()\n'; }; Blockly.Python['wait'] = function(block) { return 'v.wait()\n'; }; Blockly.Python['deliver'] = function(block) { return 'v.deliver()\n'; }; Blockly.Python['road_exists'] = function(block) { if(block.inputList[0].fieldRow[1].value_ === 'FORWARD'){ var python = "v.is_road('FORWARD')"; }else if(block.inputList[0].fieldRow[1].value_ === 'LEFT'){ var python = "v.is_road('LEFT')"; }else{ var python = "v.is_road('RIGHT')"; } return [python, Blockly.Python.ORDER_NONE]; // TODO: figure out what this ordering relates to }; Blockly.Python['traffic_light'] = function(block) { var python; if(block.inputList[0].fieldRow[1].value_ === ocargo.TrafficLight.RED){ python = "v.at_traffic_light('RED')"; }else{ python = "v.at_traffic_light('GREEN')"; } return [python, Blockly.Python.ORDER_NONE]; //TODO: figure out what this ordering relates to }; Blockly.Python['dead_end'] = function(block) { return ['v.at_dead_end()', Blockly.Python.ORDER_NONE]; // TODO: figure out what this ordering relates to }; Blockly.Python['cow_crossing'] = function(block) { return ['v.cow_crossing()', Blockly.Python.ORDER_NONE]; // TODO: figure out what this ordering relates to }; Blockly.Python['at_destination'] = function(block) { return ['v.at_destination()', Blockly.Python.ORDER_NONE]; // TODO: figure out what this ordering relates to; }; Blockly.Python['call_proc'] = function(block) { return block.inputList[0].fieldRow[2].text_ + '()\n'; }; Blockly.Python['declare_proc'] = function(block) { var branch = Blockly.Python.statementToCode(block, 'DO'); return 'def ' + block.inputList[0].fieldRow[1].text_ + '():\n' + branch; // TODO: get code out of sub-blocks (there's a Blockly function for it) }; Blockly.Python['declare_event'] = function(block) { // TODO support events in python throw 'events not supported in python'; }; Blockly.Python['controls_repeat_while'] = function(block) { var condition = Blockly.Python.valueToCode(block, 'condition', Blockly.Python.ORDER_ATOMIC); var subBlock = Blockly.Python.statementToCode(block, 'body'); var code = 'while ' + condition + ':\n' + subBlock; return code; }; Blockly.Python['controls_repeat_until'] = function(block) { var condition = Blockly.Python.valueToCode(block, 'condition', Blockly.Python.ORDER_ATOMIC); var subBlock = Blockly.Python.statementToCode(block, 'body'); var code = 'while not ' + condition + ':\n' + subBlock; return code; }; }
mikebryant/rapid-router
game/static/game/js/blocklyCustomBlocks.js
JavaScript
agpl-3.0
20,655
<?php /** * Copyright 2015-2018 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/>. */ return [ 'not_negative' => ':attribute não pode ser negativo.', 'required' => ':attribute é necessário.', 'too_long' => ':attribute limite máximo excedido - só pode ser até :limit caracteres.', 'wrong_confirmation' => 'A confirmação não corresponde.', 'beatmap_discussion_post' => [ 'discussion_locked' => 'A discussão está bloqueada.', 'first_post' => 'Não é possível eliminar uma publicação de começo.', ], 'beatmapset_discussion' => [ 'beatmap_missing' => 'A marca de tempo está especificada mas o beatmap está em falta.', 'beatmapset_no_hype' => "O beatmap não pode ser hypeado.", 'hype_requires_null_beatmap' => 'O hype tem que ser feito na secção Geral (todas as dificuldades).', 'invalid_beatmap_id' => 'Dificuldade especificada inválida.', 'invalid_beatmapset_id' => 'Beatmap especificado inválido.', 'locked' => 'A discussão está bloqueada.', 'hype' => [ 'guest' => 'Tens que estar com a sessão iniciada para hypear.', 'hyped' => 'Já hypeaste este beatmap.', 'limit_exceeded' => 'Usaste todo o teu hype.', 'not_hypeable' => 'Este beatmap não pode ser hypeado', 'owner' => 'Nada de hypear o teu próprio beatmap.', ], 'timestamp' => [ 'exceeds_beatmapset_length' => 'A marca de tempo especificada ultrapassa a duração do beatmap.', 'negative' => "A marca de tempo não pode ser negativa.", ], ], 'forum' => [ 'feature_vote' => [ 'not_feature_topic' => 'Só se pode votar numa característica solicitada.', 'not_enough_feature_votes' => 'Votos insuficientes.', ], 'poll_vote' => [ 'invalid' => 'Opção especificada inválida.', ], 'post' => [ 'beatmapset_post_no_delete' => 'Não é permitido eliminar a publicação dos metadados do beatmap.', 'beatmapset_post_no_edit' => 'Não é permitido editar a publicação dos metadados do beatmap.', ], 'topic_poll' => [ 'duplicate_options' => 'Uma opção duplicada não é permitida.', 'invalid_max_options' => 'As opções por cada utilizador não podem exceder o número de opções disponíveis.', 'minimum_one_selection' => 'Um mínimo de uma opção é necessária por utilizador.', 'minimum_two_options' => 'São necessárias pelo menos duas opções.', 'too_many_options' => 'Número máximo de opções permitidas excedido.', ], 'topic_vote' => [ 'required' => 'Selecciona uma opção quando estiveres a votar.', 'too_many' => 'Foram seleccionadas opções a mais do que as permitidas.', ], ], 'user' => [ 'contains_username' => 'A palavra-passe não pode conter o nome de utilizador.', 'email_already_used' => 'Endereço de email já usado.', 'invalid_country' => 'País inexistente na base de dados.', 'invalid_discord' => 'Nome de utilizador do Discord inválido.', 'invalid_email' => "Não parece que seja um endereço de email válido.", 'too_short' => 'A nova palavra-passe é demasiado curta.', 'unknown_duplicate' => 'Nome de utilizador e endereço de e-mail já usados.', 'username_available_in' => 'Este nome de utilizador irá estar disponível para uso em :duration.', 'username_available_soon' => 'Este nome de utilizador irá estar disponível para uso em qualquer momento!', 'username_invalid_characters' => 'O nome de utilizador solicitado contém caracteres inválidos.', 'username_in_use' => 'Este nome de utilizador já está a ser usado!', 'username_no_space_userscore_mix' => 'Por favor usa sublinhados ou espaços, não ambos!', 'username_no_spaces' => "O nome de utilizador não pode começar ou acabar com espaços!", 'username_not_allowed' => 'Esta escolha para nome de utilizador não é permitida.', 'username_too_short' => 'O nome de utilizador solicitado é demasiado curto.', 'username_too_long' => 'O nome de utilizador solicitado é demasiado longo.', 'weak' => 'Palavra-passe colocada na lista-negra.', 'wrong_current_password' => 'A palavra-passe actual está incorrecta.', 'wrong_email_confirmation' => 'A confirmação do email não corresponde.', 'wrong_password_confirmation' => 'A confirmação da palavra-passe não corresponde.', 'too_long' => 'Comprimento máximo excedido - só pode ser até :limit caracteres.', 'change_username' => [ 'supporter_required' => [ '_' => 'Tu tens de ter :link para mudar o teu nome!', 'link_text' => 'ajudaste o osu!', ], 'username_is_same' => 'Este já é o teu nome de utilizador, tontinho!', ], ], ];
kj415j45/osu-web
resources/lang/pt/model_validation.php
PHP
agpl-3.0
5,767
package org.rakam.report; import com.facebook.presto.sql.tree.*; import org.rakam.util.ValidationUtil; import java.util.Optional; import java.util.function.Function; import static com.facebook.presto.sql.tree.LogicalBinaryExpression.Type.AND; import static com.facebook.presto.sql.tree.LogicalBinaryExpression.Type.OR; public class PreComputedTableSubQueryVisitor extends AstVisitor<String, Boolean> { private final Function<String, Optional<String>> columnNameMapper; public PreComputedTableSubQueryVisitor(Function<String, Optional<String>> columnNameMapper) { this.columnNameMapper = columnNameMapper; } @Override protected String visitLogicalBinaryExpression(LogicalBinaryExpression node, Boolean negate) { LogicalBinaryExpression.Type type = node.getType(); if (type == AND) { // TODO find a better way // Optimization for the case when one hand or binary expression is IS NOT NULL predicate if (node.getRight() instanceof IsNotNullPredicate && !(node.getLeft() instanceof IsNotNullPredicate) || node.getLeft() instanceof IsNotNullPredicate && !(node.getRight() instanceof IsNotNullPredicate)) { Expression isNotNull = node.getRight() instanceof IsNotNullPredicate ? node.getRight() : node.getLeft(); Expression setExpression = isNotNull == node.getRight() ? node.getLeft() : node.getRight(); String excludeQuery = process(new IsNullPredicate(((IsNotNullPredicate) isNotNull).getValue()), negate); return "SELECT l.date, l.dimension, l._user_set FROM (" + process(setExpression, negate) + ") l LEFT JOIN (" + excludeQuery + ") r ON (r.date = l.date AND l.dimension = r.dimension) WHERE r.date IS NULL"; } String right = process(node.getRight(), negate); String left = process(node.getLeft(), negate); // TODO: use INTERSECT when it's implemented in Presto. return "SELECT l.date, l.dimension, l._user_set FROM (" + left + ") l JOIN (" + right + ") r ON (r.date = l.date)"; } else if (type == OR) { return "SELECT date, dimension, _user_set FROM (" + process(node.getLeft(), negate) + " UNION ALL " + process(node.getRight(), negate) + ")"; } else { throw new IllegalStateException(); } } @Override protected String visitNotExpression(NotExpression node, Boolean negate) { return process(node.getValue(), !negate); } @Override protected String visitComparisonExpression(ComparisonExpression node, Boolean negate) { String left = process(node.getLeft(), negate); String right = process(node.getRight(), negate); String predicate = node.getType().getValue() + " " + right; if (negate) { predicate = String.format("not(%s)", predicate); } return "SELECT date, dimension, _user_set FROM " + left + " WHERE dimension " + predicate; } @Override protected String visitLongLiteral(LongLiteral node, Boolean negate) { return Long.toString(node.getValue()); } @Override protected String visitLikePredicate(LikePredicate node, Boolean negate) { return "SELECT date, dimension, _user_set FROM " + process(node.getValue(), negate) + " WHERE dimension LIKE " + process(node.getPattern(), negate); } @Override protected String visitIsNotNullPredicate(IsNotNullPredicate node, Boolean negate) { if (negate) { return visitIsNullPredicate(new IsNullPredicate(node.getValue()), !negate); } String column = process(node.getValue(), negate); return "SELECT date, dimension, _user_set FROM " + column + " WHERE dimension is not null"; } @Override protected String visitIsNullPredicate(IsNullPredicate node, Boolean negate) { if (negate) { return visitIsNullPredicate(new IsNullPredicate(node.getValue()), !negate); } return "SELECT date, dimension, _user_set FROM " + process(node.getValue(), negate) + " WHERE dimension is null"; } @Override protected String visitInPredicate(InPredicate node, Boolean negate) { String predicate = "IN " + process(node.getValue(), null) + " " + process(node, negate) + " ) "; if (negate) { predicate = String.format("NOT ", predicate); } return "SELECT date, dimension, _user_set FROM " + process(node.getValue(), negate) + " WHERE dimension " + predicate; } @Override protected String visitBetweenPredicate(BetweenPredicate node, Boolean negate) { String predicate = "BETWEEN " + process(node.getMin(), null) + " " + process(node, negate) + " ) "; if (negate) { predicate = String.format("not(%s)", predicate); } return "SELECT date, dimension, _user_set FROM " + process(node.getValue(), negate) + " WHERE dimension " + predicate; } @Override protected String visitDoubleLiteral(DoubleLiteral node, Boolean negate) { return Double.toString(node.getValue()); } @Override protected String visitGenericLiteral(GenericLiteral node, Boolean negate) { return node.getType() + " '" + node.getValue() + "'"; } @Override protected String visitTimeLiteral(TimeLiteral node, Boolean negate) { return "TIME '" + node.getValue() + "'"; } @Override protected String visitTimestampLiteral(TimestampLiteral node, Boolean negate) { return "TIMESTAMP '" + node.getValue() + "'"; } @Override protected String visitNullLiteral(NullLiteral node, Boolean negate) { return "null"; } @Override protected String visitIntervalLiteral(IntervalLiteral node, Boolean negate) { String sign = (node.getSign() == IntervalLiteral.Sign.NEGATIVE) ? "- " : ""; StringBuilder builder = new StringBuilder() .append("INTERVAL ") .append(sign) .append(" '").append(node.getValue()).append("' ") .append(node.getStartField()); if (node.getEndField().isPresent()) { builder.append(" TO ").append(node.getEndField().get()); } return builder.toString(); } @Override protected String visitBooleanLiteral(BooleanLiteral node, Boolean negate) { return String.valueOf(node.getValue()); } @Override protected String visitStringLiteral(StringLiteral node, Boolean negate) { return "'" + node.getValue().replace("'", "''") + "'"; } @Override protected String visitIdentifier(Identifier node, Boolean context) { String tableColumn = ValidationUtil .checkTableColumn(node.getValue(), "reference in filter", '"'); Optional<String> preComputedTable = columnNameMapper.apply(tableColumn); if (preComputedTable.isPresent()) { return preComputedTable.get(); } throw new UnsupportedOperationException(); } @Override protected String visitNode(Node node, Boolean negate) { throw new UnsupportedOperationException(); } }
buremba/rakam
rakam-spi/src/main/java/org/rakam/report/PreComputedTableSubQueryVisitor.java
Java
agpl-3.0
7,236
# -*- 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 logging from copy import copy from eve.utils import config, ParsedRequest from superdesk.utc import utcnow from superdesk.services import BaseService from superdesk.publish.formatters.ninjs_formatter import NINJSFormatter from superdesk import get_resource_service from superdesk.metadata.item import ITEM_TYPE, CONTENT_TYPE logger = logging.getLogger('superdesk') class PublishService(BaseService): """A service for publishing to the content api. Serves mainly as a proxy to the data layer. """ formatter = NINJSFormatter() subscriber = {'config': {}} def publish(self, item, subscribers=[]): """Publish an item to content api. This must be enabled via ``PUBLISH_TO_CONTENT_API`` setting. :param item: item to publish """ if not self._filter_item(item): doc = self.formatter._transform_to_ninjs(item, self.subscriber) now = utcnow() doc.setdefault('firstcreated', now) doc.setdefault('versioncreated', now) doc.setdefault(config.VERSION, item.get(config.VERSION, 1)) doc['subscribers'] = [str(sub['_id']) for sub in subscribers] if 'evolvedfrom' in doc: parent_item = self.find_one(req=None, _id=doc['evolvedfrom']) if parent_item: doc['ancestors'] = copy(parent_item.get('ancestors', [])) doc['ancestors'].append(doc['evolvedfrom']) doc['bookmarks'] = parent_item.get('bookmarks', []) else: logger.warning("Failed to find evolvedfrom item '{}' for '{}'".format( doc['evolvedfrom'], doc['guid']) ) self._assign_associations(item, doc) logger.info('publishing %s to %s' % (doc['guid'], subscribers)) _id = self._create_doc(doc) if 'evolvedfrom' in doc and parent_item: self.system_update(parent_item['_id'], {'nextversion': _id}, parent_item) return _id else: return None def create(self, docs, **kwargs): ids = [] for doc in docs: ids.append(self._create_doc(doc, **kwargs)) return ids def _create_doc(self, doc, **kwargs): """Create a new item or update existing.""" item = copy(doc) item.setdefault('_id', item.get('guid')) _id = item[config.ID_FIELD] = item.pop('guid') # merging the existing and new subscribers original = self.find_one(req=None, _id=_id) if original: item['subscribers'] = list(set(original.get('subscribers', [])) | set(item.get('subscribers', []))) self._process_associations(item, original) self._create_version_doc(item) if original: self.update(_id, item, original) return _id else: return super().create([item], **kwargs)[0] def _create_version_doc(self, item): """ Store the item in the item version collection :param item: :return: """ version_item = copy(item) version_item['_id_document'] = version_item.pop('_id') get_resource_service('items_versions').create([version_item]) # if the update is a cancel we need to cancel all versions if item.get('pubstatus', '') == 'canceled': self._cancel_versions(item.get('_id')) def _cancel_versions(self, doc_id): """ Given an id of a document set the pubstatus to canceled for all versions :param doc_id: :return: """ query = {'_id_document': doc_id} update = {'pubstatus': 'canceled'} for item in get_resource_service('items_versions').get_from_mongo(req=None, lookup=query): if item.get('pubstatus') != 'canceled': get_resource_service('items_versions').update(item['_id'], update, item) def _filter_item(self, item): """ Filter the item out if it matches any API Block filter conditions :param item: :return: True of the item is blocked, False if it is OK to publish it on the API. """ # Get the API blocking Filters req = ParsedRequest() filter_conditions = list(get_resource_service('content_filters').get(req=req, lookup={'api_block': True})) # No API blocking filters if not filter_conditions: return False filter_service = get_resource_service('content_filters') for fc in filter_conditions: if filter_service.does_match(fc, item): logger.info('API Filter block {} matched for item {}.'.format(fc, item.get(config.ID_FIELD))) return True return False def _assign_associations(self, item, doc): """Assign Associations to published item :param dict item: item being published :param dit doc: ninjs documents """ if item[ITEM_TYPE] != CONTENT_TYPE.TEXT: return for assoc, assoc_item in (item.get('associations') or {}).items(): if not assoc_item: continue doc.get('associations', {}).get(assoc)['subscribers'] = list(map(str, assoc_item.get('subscribers') or [])) def _process_associations(self, updates, original): """Update associations using existing published item and ensure that associated item subscribers are equal or subset of the parent subscribers. :param updates: :param original: :return: """ if updates[ITEM_TYPE] != CONTENT_TYPE.TEXT: return subscribers = updates.get('subscribers') or [] for assoc, update_assoc in (updates.get('associations') or {}).items(): if not update_assoc: continue if original: original_assoc = (original.get('associations') or {}).get(assoc) if original_assoc and original_assoc.get(config.ID_FIELD) == update_assoc.get(config.ID_FIELD): update_assoc['subscribers'] = list(set(original_assoc.get('subscribers') or []) | set(update_assoc.get('subscribers') or [])) update_assoc['subscribers'] = list(set(update_assoc['subscribers']) & set(subscribers))
marwoodandrew/superdesk-core
content_api/publish/service.py
Python
agpl-3.0
6,723
package android.support.design.widget; import android.content.Context; import android.content.res.TypedArray; import android.support.design.c; final class by { private static final int[] a = new int[]{c.colorPrimary}; static void a(Context context) { int i = 0; TypedArray obtainStyledAttributes = context.obtainStyledAttributes(a); if (!obtainStyledAttributes.hasValue(0)) { i = 1; } if (obtainStyledAttributes != null) { obtainStyledAttributes.recycle(); } if (i != 0) { throw new IllegalArgumentException("You need to use a Theme.AppCompat theme (or descendant) with the design library."); } } }
WenbinHou/PKUAutoGateway.Android
Reference/IPGWAndroid/android/support/design/widget/by.java
Java
agpl-3.0
714
<?php class Search { public static function matchTerm($term, $text) { $reg = "/[ ]+/"; $text = self::normalize($text); $term = self::normalize($term); $words_text = preg_split($reg, $text); $words_term = preg_split($reg, $term); $text_final = ""; foreach($words_term as $key_term => $word_term) { $matcher = "/".self::normalize($word_term)."/i"; $find = false; foreach($words_text as $key_text => $word_text) { if(preg_match($matcher, $word_text)) { $find = true; unset($words_text[$key_text]); break; } unset($words_text[$key_text]); } if(!$find) { return false; } } return $find; } public static function matchTermLight($term, $text) { $reg = "/[ ]+/"; $text = self::normalize($text); $term = self::normalize($term); $words_text = preg_split($reg, $text); $words_term = preg_split($reg, $term); $text_final = ""; foreach($words_term as $key_term => $word_term) { $find = false; foreach($words_text as $key_text => $word_text) { if($word_term == $word_text) { $find = true; unset($words_text[$key_text]); break; } unset($words_text[$key_text]); } if(!$find) { return false; } } return $find; } public static function normalize($text) { return KeyInflector::unaccent($text); } public static function getWords($value) { $words = array(); $expressions = preg_split('/([,; \|()])/', $value); $words_mandatories = array("ac"); foreach($expressions as $exp) { if(preg_match('/[\wû]{3,}/', $exp) || in_array(strtolower($exp), $words_mandatories)) { $words[] = strtolower($exp); } } return $words; } }
24eme/vinsdeloire
project/plugins/acVinLibPlugin/lib/util/Search.class.php
PHP
agpl-3.0
1,975
/** * Copyright (C) 2016 Jorge Campos Serrano. * * This program 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 * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ Template.notificationsWidget.helpers({ notifications: function() { return Notifications.find({userId: Meteor.userId(), read: false}, {limit: 4}); }, notificationCount: function(){ return Notifications.find({userId: Meteor.userId(), read: false}).count(); } });
jcamposs/coderoom
client/templates/notifications/notifications_widget.js
JavaScript
agpl-3.0
1,772
<?php /*** COPYRIGHT NOTICE ********************************************************* * * Copyright 2009-2016 ProjeQtOr - Pascal BERNARD - support@projeqtor.org * Contributors : - * * This file is part of ProjeQtOr. * * ProjeQtOr 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. * * ProjeQtOr 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 * ProjeQtOr. If not, see <http://www.gnu.org/licenses/>. * * You can get complete code of ProjeQtOr, other resource, help and information * about contributors at http://www.projeqtor.org * *** DO NOT REMOVE THIS NOTICE ************************************************/ /** ============================================================================ * Contact */ require_once('_securityCheck.php'); class Contact extends ContactMain { /** ========================================================================== * Constructor * @param $id the id of the object in the database (null if not stored yet) * @return void */ function __construct($id = NULL, $withoutDependentObjects=false) { parent::__construct($id,$withoutDependentObjects); } /** ========================================================================== * Destructor * @return void */ function __destruct() { parent::__destruct(); } } ?>
papjul/projeqtor
model/Contact.php
PHP
agpl-3.0
1,800
############################################################################## # # ______ Releasing children from poverty _ # / ____/___ ____ ___ ____ ____ ___________(_)___ ____ # / / / __ \/ __ `__ \/ __ \/ __ `/ ___/ ___/ / __ \/ __ \ # / /___/ /_/ / / / / / / /_/ / /_/ (__ |__ ) / /_/ / / / / # \____/\____/_/ /_/ /_/ .___/\__,_/____/____/_/\____/_/ /_/ # /_/ # in Jesus' name # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # @author: Nicolas Badoux <n.badoux@hotmail.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/>. # ############################################################################## # pylint: disable=C8101 { "name": "Survey Phone", "summary": "Make the filling of survey by internal users easier.", "version": "12.0.1.0.0", "category": "Other", "sequence": 150, "author": "Compassion CH", "license": "AGPL-3", "website": "http://www.compassion.ch", "depends": [ "survey", # oca_addons/survey "base_phone", # oca_addons/connector-telephony "survey", "partner_contact_birthdate", # oca_addons/partner_contact "advanced_translation", ], "data": [ "views/survey_user_input_view.xml", "views/survey_phone.xml", "report/survey_report.xml", ], "demo": [], "installable": True, "auto_install": False, }
CompassionCH/compassion-modules
survey_phone/__manifest__.py
Python
agpl-3.0
2,093
// // Copyright (C) 2013-2016 University of Amsterdam // // 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/>. // #include "tablemodelvariableslevels.h" #include <QMimeData> #include <QDebug> #include "options/optionstring.h" #include "options/optionlist.h" #include "options/optionvariables.h" #include "column.h" using namespace std; TableModelVariablesLevels::TableModelVariablesLevels(QWidget *parent) : TableModel(parent) { _boundTo = NULL; _source = NULL; _variableTypesSuggested = 0; _variableTypesAllowed = 0xff; _nominalTextIcon = QIcon(":/icons/variable-nominal-text.svg"); _nominalIcon = QIcon(":/icons/variable-nominal.svg"); _ordinalIcon = QIcon(":/icons/variable-ordinal.svg"); _scaleIcon = QIcon(":/icons/variable-scale.svg"); _limitToOneLevel = false; } void TableModelVariablesLevels::bindTo(Option *option) { if (_source == NULL) { qDebug() << "source not set!"; return; } _boundTo = dynamic_cast<OptionsTable *>(option); _levels = _boundTo->value(); Terms alreadyAssigned; foreach (Options *level, _levels) { OptionVariables *levelVariablesOption = static_cast<OptionVariables*>(level->get("variables")); Terms variablesInLevel = levelVariablesOption->variables(); alreadyAssigned.add(variablesInLevel); } if (alreadyAssigned.size() > 0) _source->notifyAlreadyAssigned(alreadyAssigned); refresh(); } void TableModelVariablesLevels::mimeDataMoved(const QModelIndexList &indexes) { bool levelRemoved = false; Terms toRemove; foreach (const QModelIndex &index, indexes) toRemove.add(_rows.at(index.row()).title()); for (int i = _levels.size() - 1; i >= 0; i--) { Options *levelOptions = _levels.at(i); OptionVariables *variablesOption = dynamic_cast<OptionVariables *>(levelOptions->get("variables")); Terms variables = variablesOption->variables(); variables.remove(toRemove); if (variables.size() == 0) { Options *options = _levels.at(i); _levels.erase(find(_levels.begin(), _levels.end(), options)); delete options; levelRemoved = true; } else { variablesOption->setValue(variables.asVector()); } } if (levelRemoved) { OptionString *nameOption = static_cast<OptionString *>(_boundTo->rowTemplate()->get("name")); QString nameTemplate = tq(nameOption->value()); for (uint i = 0; i < _levels.size(); i++) { nameOption = static_cast<OptionString *>(_levels.at(i)->get("name")); nameOption->setValue(fq(nameTemplate.arg(i + 1))); } } _boundTo->setValue(_levels); refresh(); } void TableModelVariablesLevels::setVariableTypesSuggested(int variableTypesSuggested) { _variableTypesSuggested = variableTypesSuggested; } int TableModelVariablesLevels::variableTypesSuggested() const { return _variableTypesSuggested; } void TableModelVariablesLevels::setVariableTypesAllowed(int variableTypesAllowed) { _variableTypesAllowed = variableTypesAllowed; } int TableModelVariablesLevels::variableTypesAllowed() const { return _variableTypesAllowed; } void TableModelVariablesLevels::setLimitToOneLevel(bool limitToOne) { _limitToOneLevel = limitToOne; } bool TableModelVariablesLevels::isSuggested(const Term &term) const { QVariant v = requestInfo(term, VariableInfo::VariableType); int variableType = v.toInt(); return variableType & _variableTypesSuggested; } bool TableModelVariablesLevels::isAllowed(const Term &term) const { QVariant v = requestInfo(term, VariableInfo::VariableType); int variableType = v.toInt(); return variableType == 0 || variableType & _variableTypesAllowed; } int TableModelVariablesLevels::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); if (_boundTo == NULL) return 0; return _rows.length(); } int TableModelVariablesLevels::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); if (_boundTo == NULL) return 0; return 1; } QVariant TableModelVariablesLevels::data(const QModelIndex &index, int role) const { if (_boundTo == NULL) return QVariant(); Row row = _rows.at(index.row()); if (role == Qt::DisplayRole || role == Qt::EditRole) { if ( ! row.isOption()) { return row.title(); } else { OptionList *list = row.option(); QString selected = tq(list->value()); if (role == Qt::DisplayRole) return selected; QStringList items = tql(list->options()); QList<QVariant> value; value.append(selected); value.append(items); return value; } } else if (role == Qt::DecorationRole) { if (row.isHeading() == false && row.isOption() == false) { int variableType = requestInfo(row.title(), VariableInfo::VariableType).toInt(); switch (variableType) { case Column::ColumnTypeNominalText: return QVariant(_nominalTextIcon); case Column::ColumnTypeNominal: return QVariant(_nominalIcon); case Column::ColumnTypeOrdinal: return QVariant(_ordinalIcon); case Column::ColumnTypeScale: return QVariant(_scaleIcon); default: return QVariant(); } } } else if (role == Qt::ForegroundRole) { if (_limitToOneLevel == false && index.row() == _rows.length() - 1) return QBrush(QColor(0xAA, 0xAA, 0xAA)); } else if (role == Qt::TextAlignmentRole) { if (row.isHeading()) return Qt::AlignCenter; else if (row.isOption()) return Qt::AlignTop; } else if (role == Qt::SizeHintRole) { if (row.isHeading()) return QSize(-1, 24); } return QVariant(); } Qt::ItemFlags TableModelVariablesLevels::flags(const QModelIndex &index) const { Qt::ItemFlags flags = Qt::ItemIsEnabled; if (index.isValid() == false) { flags |= Qt::ItemIsDropEnabled; } else { Row row = _rows.at(index.row()); if (row.isOption()) flags |= Qt::ItemIsEditable; else if (row.isHeading() == false) flags |= Qt::ItemIsSelectable | Qt::ItemIsDragEnabled; } return flags; } bool TableModelVariablesLevels::setData(const QModelIndex &index, const QVariant &value, int role) { if (role != Qt::DisplayRole && role != Qt::EditRole) return false; if (_boundTo == NULL) return false; OptionList *list = _rows.at(index.row()).option(); QString qsValue = value.toString(); QByteArray bytes = qsValue.toUtf8(); list->setValue(string(bytes.constData(), bytes.length())); _boundTo->setValue(_levels); emit dataChanged(index, index); return true; } Qt::DropActions TableModelVariablesLevels::supportedDropActions() const { return Qt::MoveAction; } Qt::DropActions TableModelVariablesLevels::supportedDragActions() const { return Qt::MoveAction; } QStringList TableModelVariablesLevels::mimeTypes() const { QStringList m; m << "application/vnd.list.variable"; return m; } QMimeData *TableModelVariablesLevels::mimeData(const QModelIndexList &indexes) const { QMimeData *mimeData = new QMimeData(); QByteArray encodedData; QDataStream dataStream(&encodedData, QIODevice::WriteOnly); dataStream << indexes.length(); for (int i = 0; i < indexes.length(); i++) { Row row = _rows.at(indexes.at(i).row()); dataStream << QStringList(row.title()); } mimeData->setData("application/vnd.list.variable", encodedData); return mimeData; } bool TableModelVariablesLevels::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { if (action == Qt::IgnoreAction) return true; if ( ! canDropMimeData(data, action, row, column, parent)) return false; if (mimeTypes().contains("application/vnd.list.variable")) { QByteArray encodedData = data->data("application/vnd.list.variable"); Terms variables; variables.set(encodedData); if (variables.size() == 0) return false; if (parent.isValid() == false) { if (row == -1) // dropped at end row = _rows.length(); else if (row == 0) // dropped at beginning row = 1; size_t level = 0; int positionInLevel = 0; for (int i = 1; i < row; i++) { if (_rows[i].isHeading()) { level++; positionInLevel = 0; } else if (_rows[i].isOption() == false) { positionInLevel++; } } if (level == _levels.size()) { // create new level Options *options = dynamic_cast<Options*>(_boundTo->rowTemplate()->clone()); OptionString *nameOption = dynamic_cast<OptionString *>(options->get("name")); string levelName = fq(tq(nameOption->value()).arg(level + 1)); nameOption->setValue(levelName); _levels.push_back(options); } Options *levelDroppedOn = _levels.at(level); OptionVariables *variablesOption = dynamic_cast<OptionVariables*>(levelDroppedOn->get("variables")); Terms currentVariables = variablesOption->variables(); foreach (const Term &variable, variables) { if (currentVariables.contains(variable)) // prevent dropping to own level (because it introduces complications) return false; currentVariables.insert(positionInLevel, variable); positionInLevel++; } variablesOption->setValue(currentVariables.asVector()); // remove the variables which were just dropped, from the other levels // (to handle the case that a variable is dragged and dropped from another level) bool levelRemoved = false; vector<Options*>::iterator itr = _levels.begin(); while (itr != _levels.end()) { Options *level = *itr; if (level == levelDroppedOn) { itr++; continue; } OptionVariables *variablesOption = dynamic_cast<OptionVariables*>(level->get("variables")); Terms currentVariables = variablesOption->variables(); currentVariables.remove(variables); if (currentVariables.size() == 0) { delete variablesOption; itr = _levels.erase(itr); levelRemoved = true; } else { variablesOption->setValue(currentVariables.asVector()); itr++; } } if (levelRemoved) { // update the level names OptionString *nameOption = static_cast<OptionString *>(_boundTo->rowTemplate()->get("name")); QString nameTemplate = tq(nameOption->value()); for (uint i = 0; i < _levels.size(); i++) { nameOption = static_cast<OptionString *>(_levels.at(i)->get("name")); nameOption->setValue(fq(nameTemplate.arg(i + 1))); } } _boundTo->setValue(_levels); refresh(); return true; } } return false; } bool TableModelVariablesLevels::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const { Q_UNUSED(action); Q_UNUSED(row); Q_UNUSED(column); Q_UNUSED(parent); if (data->hasFormat("application/vnd.list.variable")) { QByteArray encodedData = data->data("application/vnd.list.variable"); Terms variables; variables.set(encodedData); foreach (const Term &variable, variables) { if ( ! isAllowed(variable)) return false; } return true; } else { return false; } return false; } void TableModelVariablesLevels::setSource(TableModelVariablesAvailable *source) { _source = source; setInfoProvider(source); } void TableModelVariablesLevels::refresh() { _rows.clear(); if (_boundTo == NULL) return; beginResetModel(); uint i; for (i = 0; i < _levels.size(); i++) { Options *level = _levels.at(i); OptionVariables *variablesOption = dynamic_cast<OptionVariables *>(level->get("variables")); OptionString *nameOption = dynamic_cast<OptionString *>(level->get("name")); vector<string> variables = variablesOption->variables(); _rows.append(Row(tq(nameOption->value()), true)); for (uint j = 2; j < level->size(); j++) { OptionList *list = dynamic_cast<OptionList *>(level->get(j)); _rows.append(Row(list)); } foreach (const string &variable, variables) _rows.append(Row(tq(variable))); } if (_limitToOneLevel == false) { OptionString *nameTemplate = static_cast<OptionString *>(_boundTo->rowTemplate()->get("name")); QString name = tq(nameTemplate->value()).arg(i + 1); _rows.append(Row(name, true)); } endResetModel(); }
raviselker/jasp-desktop
JASP-Desktop/widgets/tablemodelvariableslevels.cpp
C++
agpl-3.0
12,498
class ChangeBoardCompositionResolution < ResolutionWrapper attr_accessor :max_user_directors, :max_employee_directors, :max_supporter_directors, :max_producer_directors, :max_consumer_directors def after_initialize [ :max_user_directors, :max_employee_directors, :max_supporter_directors, :max_producer_directors, :max_consumer_directors ].each do |clause_name| send("#{clause_name}=", organisation.constitution.send(clause_name)) unless send(clause_name) end end def attributes_for_resolutions result = [] [:user, :employee, :supporter, :producer, :consumer].each do |member_type| method = "max_#{member_type}_directors" if organisation.send(method) != send(method).to_i result.push({ :relation => :change_integer_resolutions, :name => method, :value => send(method).to_i, :title => "Allow a maximum of #{send(method)} #{member_type.to_s.titlecase} Members on the Board" }) end end result end end
oneclickorgs/one-click-orgs
app/models/change_board_composition_resolution.rb
Ruby
agpl-3.0
1,028
# frozen_string_literal: true module Decidim # This holds the decidim-surveys version. module Surveys def self.version "0.22.0" end end end
codegram/decidim
decidim-surveys/lib/decidim/surveys/version.rb
Ruby
agpl-3.0
161
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.fluxtion.runtime.plugin.executor; import com.fluxtion.runtime.event.Event; import com.fluxtion.runtime.lifecycle.EventHandler; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * * @author Greg Higgins (greg.higgins@V12technology.com) */ public class SingleThreadedAsyncEventHandler implements AsyncEventHandler { private final EventHandler handler; public SingleThreadedAsyncEventHandler(EventHandler handler) { this.handler = handler; } @Override public Future submitTask(SepCallable task) { return new Future() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return true; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public Object get() throws InterruptedException, ExecutionException { try { return task.call(handler); } catch (Exception ex) { throw new RuntimeException(ex); } } @Override public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return get(); } }; } @Override public void onEvent(Event e) { handler.onEvent(e); } @Override public EventHandler delegate() { return handler; } }
v12technology/fluxtion-utils
runtime-plugins/src/main/java/com/fluxtion/runtime/plugin/executor/SingleThreadedAsyncEventHandler.java
Java
agpl-3.0
1,904
/** * This file is part of RLO-Plan. * * Copyright 2009, 2010 Tillmann Karras, Josua Grawitter * * RLO-Plan 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. * * RLO-Plan 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 RLO-Plan. If not, see <http://www.gnu.org/licenses/>. */ var column_titles = ['Uhrzeit', 'Klasse', 'Fach', 'Dauer', 'Vertretung', 'Änderung', 'Alter Raum', 'Neuer Raum']; var column_names = ['time', 'course', 'subject', 'duration', 'sub', 'change', 'oldroom', 'newroom']; var column_widths = ['40px', '40px', '45px', '25px', '150px', '245px', '40px', '40px']; var column_maxLengths = [ 5, 5, 6, 3, 30, 40, 5, 5]; var day_names = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag']; var relative_day_names = ['heute', 'morgen', 'übermorgen']; // array index corresponds to distance from today function modify_entry(button) { hide_buttons(button); show_buttons(button.nextSibling.nextSibling); var row = button.parentNode.parentNode; for (var i = 0; i < row.childNodes.length - 1; i++) { var cell = row.childNodes[i]; make_textbox(cell, i); make_backup(cell, cell.lastChild.value); } } function remove_row(row) { if (row.parentNode.childNodes.length == 2) { var teacher = row.parentNode.parentNode; var day = teacher.parentNode; if (day.childNodes.length == 4) { remove(day); } else { remove(teacher); } } else { remove(row); } } function delete_entry(button) { hide_buttons(button.previousSibling); var row = button.parentNode.parentNode; var msg = 'action=delete&id=' + row.id.substr(5); // remove 'entry' from 'entry123' var status = newStatus('Wird gelöscht...', row.lastChild); send_msg(msg, function(xhr) { if (xhr.status == 200) { remove_row(row); } else { show_buttons(button.previousSibling); remove_status(status, xhr); } }); } function save_entry(button) { var row = button.parentNode.parentNode; var teacher = row.parentNode.parentNode; var day = teacher.parentNode; var date = parse_date(day.firstChild.textContent); if (date === null) { alert('Bitte berichtigen Sie erst das Datum.'); return; } date = format_date_server(date); var msg = '&date=' + date + '&teacher=' + teacher.firstChild.textContent; var contentHasChanged = false; for (var i = 0; i < row.childNodes.length - 1; i++) { var cell = row.childNodes[i]; var new_value = cell.firstChild.value; if (i == 0) { new_value = parse_time(new_value); if (new_value === null) { alert('Die Uhrzeit ist fehlerhaft.'); return; } hide_buttons(button); } if (new_value != cell.lastChild.textContent) { cell.textContent = new_value; msg += '&' + column_names[i] + '=' + new_value; contentHasChanged = true; } else { cell.textContent = cell.lastChild.textContent; } } if (contentHasChanged) { msg = 'action=update&id=' + row.id.substr(5) + msg; var status = newStatus('Wird gespeichert...', row.lastChild); send_msg(msg, function(xhr) { show_buttons(button.previousSibling.previousSibling); if (xhr.status != 200) { button.previousSibling.previousSibling.click(); } remove_status(status, xhr); }); } else { show_buttons(button.previousSibling.previousSibling); } } function save_new_entry(button) { var row = button.parentNode.parentNode; var teacher = row.parentNode.parentNode; var day = teacher.parentNode; var date = parse_date(day.firstChild.textContent); if (date === null) { alert('Bitte berichtigen Sie erst das Datum.'); return; } date = format_date_server(date); var msg = '&date=' + date + '&teacher=' + teacher.firstChild.textContent; for (var i = 0; i < row.childNodes.length - 1; i++) { var cell = row.childNodes[i]; var new_value = cell.firstChild.value; if (i == 0) { new_value = parse_time(new_value); if (new_value === null) { alert('Die Uhrzeit ist fehlerhaft.'); return; } hide_buttons(button); } cell.textContent = new_value; msg += '&' + column_names[i] + '=' + cell.textContent; } msg = 'action=add' + msg; var status = newStatus('Wird hinzugefügt...', row.lastChild); send_msg(msg, function(xhr) { remove_status(status, xhr); if (xhr.status == 200) { row.id = 'entry' + xhr.responseText; } else { row.lastChild.firstChild.onclick(); } // TODO: is this ok here? show_buttons(button.previousSibling.previousSibling); button.onclick = function() { save_entry(button); } button.nextSibling.innerHTML = 'Abbrechen'; button.nextSibling.onclick = function() { cancel_editing(button.nextSibling); } }); } function delete_new_entry(button) { remove_row(button.parentNode.parentNode); } function add_new_entry(button) { var row = newElement('tr'); // data cells: for (var i = 0; i < column_widths.length; i++) { var cell = newCell(''); make_textbox(cell, i); row.appendChild(cell); } // button cell: var button_cell = newElement('td'); var mod_button = newButton('Bearbeiten', modify_entry); mod_button.style.display = 'none'; button_cell.appendChild(mod_button); var del_button = newButton('Löschen', delete_entry); del_button.style.display = 'none'; button_cell.appendChild(del_button); var save_button = newButton('Speichern', save_new_entry); button_cell.appendChild(save_button); var cancel_button = newButton('Löschen', delete_new_entry); button_cell.appendChild(cancel_button); row.appendChild(button_cell); button.previousSibling.appendChild(row); row.firstChild.firstChild.focus(); } function add_teacher(button) { var day = button.parentNode; var teacher = newTeacher('Neuer Lehrer', []); day.insertBefore(teacher, day.lastChild); teacher.childNodes[1].value = ''; teacher.firstChild.onclick(); } function parse_time(time) { var matches = time.match(/^(\d\d?).(\d\d?)$/); if (matches !== null) { for (var i = 1; i <= 2; i++) { if (matches[i].length == 1) { matches[i] = '0' + matches[i]; } } return matches[1] + ':' + matches[2]; } return null; } function parse_date(date) { var matches = date.match(/(\d\d?).(\d\d?).((\d\d)?\d\d)$/); if (matches !== null) { var year = matches[3]; if (year.length == 2) { year = '20' + year; } return new Date(year, matches[2] - 1, matches[1], 0, 0, 0, 0); } var lower_date = date.toLowerCase(); for (var i = 0; i < relative_day_names.length; i++) { if (lower_date == relative_day_names[i]) { var result = new Date(); result.setDate(result.getDate() + i); return result; } } if (date.length <= 10) { // length of 'Donnerstag' for (var i = 0; i < day_names.length; i++) { if (lower_date == day_names[i].substr(0, lower_date.length).toLowerCase()) { var result = new Date(); var today = result.getDay(); if (i < today) { i += 7; } result.setDate(result.getDate() + i - today); return result; } } } return null; } // DayOfWeek, DD.MM.YYYY function format_date_client(d) { var day = d.getDate() + ''; if (day.length == 1) { day = '0' + day; } var month = (d.getMonth() + 1) + ''; if (month.length == 1) { month = '0' + month; } return day_names[d.getDay()] + ', ' + day + '.' + month + '.' + d.getFullYear(); } // YYYY-MM-DD function format_date_server(d) { return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate(); } function get_default_date() { var d = new Date(); var last_day = document.getElementById('ovp').lastChild.previousSibling; if (last_day) { var last_date = parse_date(last_day.firstChild.textContent); if (last_date && last_date.getDate() >= d.getDate()) { d = last_date; d.setDate(d.getDate() + 1); } } if (d.getDay() == 0) { // skip Sunday d.setDate(d.getDate() + 1); } else if (d.getDay() == 6) { // skip Saturday d.setDate(d.getDate() + 2); } return format_date_client(d); } function add_day(button) { var ovp = button.parentNode; var date = get_default_date(); var day = newDay(date, []); ovp.insertBefore(day, ovp.lastChild); day.firstChild.onclick(); } // 'id' is from the database function newEntry(id, cols) { var row = newElement('tr'); row.id = 'entry' + id; // data cells: for (i in cols) { row.appendChild(newCell(cols[i])); } // button cell: var button_cell = newElement('td'); var mod_button = newButton('Bearbeiten', modify_entry); button_cell.appendChild(mod_button); var del_button = newButton('Löschen', delete_entry); button_cell.appendChild(del_button); var save_button = newButton('Speichern', save_entry); save_button.style.display = 'none'; button_cell.appendChild(save_button); var cancel_button = newButton('Abbrechen', cancel_editing); cancel_button.style.display = 'none'; button_cell.appendChild(cancel_button); row.appendChild(button_cell); return row; } function save_teacher(teacher) { // subfunction needed since otherwise "status" would reference one variable only function update_entry(msg, parent) { var status = newStatus('Wird aktualisiert...', parent); send_msg(msg, function(xhr) { remove_status(status, xhr); }); } var date = parse_date(teacher.parentNode.firstChild.textContent); if (date === null) { alert('Bitte berichtigen Sie erst das Datum.'); return; } date = format_date_server(date); var rows = teacher.childNodes[2].childNodes; for (var i = 1; i < rows.length; i++) { var row = rows[i]; if (row.id) { var cells = row.childNodes; var msg = 'action=update&id=' + row.id.substr(5) + '&date=' + date + '&teacher=' + teacher.firstChild.textContent; for (var j = 0; j < cells.length - 1; j++) { msg += '&' + column_names[j] + '=' + cells[j].textContent; } update_entry(msg, row.lastChild); } } } function newTeacher(name, entries) { var teacher = newElement('section'); var header = newElement('h3'); header.style.display = 'table'; header.innerHTML = name; header.onclick = function() { header.style.display = 'none'; var textbox = header.nextSibling; textbox.style.display = 'block'; textbox.focus(); textbox.select(); } teacher.appendChild(header); var textbox = newElement('input'); textbox.type = 'text'; textbox.style.display = 'none'; textbox.value = name; textbox['last_key'] = 0; textbox.onkeydown = function(e) { var key; if (window.event) { key = event.keyCode; } else if (e) { key = e.which; } if (key == 9 && textbox['last_key'] == 0) { textbox['create_entry_on_first_blur'] = true; } textbox['last_key'] = key - 9; return true; } textbox.onkeyup = function() { textbox['last_key'] = 0; } textbox.onblur = function() { textbox.style.display = 'none'; var header = textbox.previousSibling; var table = textbox.nextSibling; if (textbox.value != header.textContent && textbox.value != '') { header.textContent = textbox.value; if (table.childNodes.length > 1) { save_teacher(textbox.parentNode); } } if (table.childNodes.length == 1 && textbox['create_entry_on_first_blur']) { textbox.parentNode.lastChild.onclick(); } header.style.display = 'table'; } teacher.appendChild(textbox); var table = newElement('table'); table.setAttribute('class', 'ovp_table'); var header_row = newElement('tr'); for (var i = 0; i < column_titles.length; i++) { header_row.appendChild(newCell(column_titles[i])); } header_row.appendChild(newCell('Aktion')); table.appendChild(header_row); for (i in entries) { table.appendChild(entries[i]); } teacher.appendChild(table); var entry_button = newButton('+ Eintrag', add_new_entry); teacher.appendChild(entry_button); return teacher; } function newDay(title, teachers) { var day = newElement('section'); var header = newElement('h2'); header.style.display = 'table'; header.innerHTML = title; header.onclick = function() { header.style.display = 'none'; var textbox = header.nextSibling; textbox.style.display = 'block'; textbox.focus(); textbox.select(); } day.appendChild(header); var textbox = newElement('input'); textbox.type = 'text'; textbox.style.display = 'none'; textbox.value = title; textbox['last_key'] = 0; textbox.onkeydown = function(e) { var key; if (window.event) { key = event.keyCode; } else if (e) { key = e.which; } if (key == 9 && textbox['last_key'] == 0) { textbox['create_teacher_on_first_blur'] = true; } textbox['last_key'] = key - 9; return true; } textbox.onkeyup = function() { textbox['last_key'] = 0; } textbox.onblur = function() { var header = textbox.previousSibling; if (textbox.value != '') { var new_date = parse_date(textbox.value); if (new_date) { var new_header = format_date_client(new_date); if (header.textContent != new_header) { header.textContent = new_header; var teachers = textbox.parentNode.getElementsByTagName('section'); for (var i = 0; i < teachers.length; i++) { save_teacher(teachers[i]); } } } else { header.innerHTML = '<span class="ovp_error">' + textbox.value + '</span>'; } } textbox.style.display = 'none'; header.style.display = 'table'; if (textbox.parentNode.childNodes.length == 3 && textbox['create_teacher_on_first_blur']) { textbox.parentNode.lastChild.onclick(); } } day.appendChild(textbox); for (i in teachers) { day.appendChild(teachers[i]); } day.appendChild(newButton('+ Lehrer', add_teacher)); return day; } function insert_days(days) { var ovp = document.getElementById('ovp'); for (i in days) { ovp.insertBefore(days[i], ovp.lastChild); } } function init_entry() { document.getElementById('ovp').appendChild(newButton('+ Tag', add_day)); fill_in_data(); } document.addEventListener("DOMContentLoaded", init_entry, false);
gwater/rlo-plan
entry.js
JavaScript
agpl-3.0
16,345
/////////////////////////////////////////////////////////////////////////////// //Copyright (C) 2014 Joliciel Informatique // //This file is part of Talismane. // //Talismane 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. // //Talismane 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 Talismane. If not, see <http://www.gnu.org/licenses/>. ////////////////////////////////////////////////////////////////////////////// package com.joliciel.talismane.machineLearning.features; /** * Mimics an in-then-else structure - if condition is true return thenFeature result, else return elseFeature result. * @author Assaf Urieli * */ public class IfThenElseGenericFeature<T,Y> extends AbstractCachableFeature<T,Y> { private BooleanFeature<T> condition; private Feature<T,Y> thenFeature; private Feature<T,Y> elseFeature; public IfThenElseGenericFeature(BooleanFeature<T> condition, Feature<T,Y> thenFeature, Feature<T,Y> elseFeature) { super(); this.condition = condition; this.thenFeature = thenFeature; this.elseFeature = elseFeature; this.setName("IfThenElse(" + condition.getName() + "," + thenFeature.getName() + "," + elseFeature.getName() + ")"); } @Override protected FeatureResult<Y> checkInternal(T context, RuntimeEnvironment env) { FeatureResult<Y> featureResult = null; FeatureResult<Boolean> conditionResult = condition.check(context, env); if (conditionResult!=null) { boolean conditionOutcome = conditionResult.getOutcome(); if (conditionOutcome) { FeatureResult<Y> thenFeatureResult = thenFeature.check(context, env); if (thenFeatureResult!=null) { Y result = thenFeatureResult.getOutcome(); featureResult = this.generateResult(result); } } else { FeatureResult<Y> elseFeatureResult = elseFeature.check(context, env); if (elseFeatureResult!=null) { Y result = elseFeatureResult.getOutcome(); featureResult = this.generateResult(result); } } } return featureResult; } public BooleanFeature<T> getCondition() { return condition; } public Feature<T,Y> getThenFeature() { return thenFeature; } public Feature<T,Y> getElseFeature() { return elseFeature; } public void setCondition(BooleanFeature<T> condition) { this.condition = condition; } public void setThenFeature(Feature<T,Y> thenFeature) { this.thenFeature = thenFeature; } public void setElseFeature(Feature<T,Y> elseFeature) { this.elseFeature = elseFeature; } @SuppressWarnings("rawtypes") @Override public Class<? extends Feature> getFeatureType() { return thenFeature.getFeatureType(); } }
safety-data/talismane
talismane_machine_learning/src/main/java/com/joliciel/talismane/machineLearning/features/IfThenElseGenericFeature.java
Java
agpl-3.0
3,068
class SDGManagement::CardsController < SDGManagement::BaseController include Admin::Widget::CardsActions helper_method :index_path load_and_authorize_resource :phase, class: "SDG::Phase", id_param: "sdg_phase_id" load_and_authorize_resource :card, through: :phase, class: "Widget::Card" private def index_path sdg_management_homepage_path end end
consul/consul
app/controllers/sdg_management/cards_controller.rb
Ruby
agpl-3.0
374
<!-- Piwik --> <script type="text/javascript"> var _paq = _paq || []; _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//arrakiz.org/analytics/"; _paq.push(['setTrackerUrl', u+'piwik.php']); _paq.push(['setSiteId', 1]); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); </script> <noscript><p><img src="//arrakiz.org/analytics/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript> <!-- End Piwik Code -->
Scindix/ArrakizPHP
tracking.php
PHP
agpl-3.0
612
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'kmol' SITENAME = 'CDW11 網頁 (虎尾科大MDE)' SITEURL = 'http://cdw11-40323200.rhcloud.com/static/' # 不要用文章所在目錄作為類別 USE_FOLDER_AS_CATEGORY = False #PATH = 'content' #OUTPUT_PATH = 'output' TIMEZONE = 'Asia/Taipei' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('pelican-bootstrap3', 'https://github.com/DandyDev/pelican-bootstrap3/'), ('pelican-plugins', 'https://github.com/getpelican/pelican-plugins'), ('Tipue search', 'https://github.com/Tipue/Tipue-Search'),) # Social widget #SOCIAL = (('You can add links in your config file', '#'),('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True # 必須絕對目錄或相對於設定檔案所在目錄 PLUGIN_PATHS = ['plugin'] PLUGINS = ['liquid_tags.notebook', 'summary', 'tipue_search', 'sitemap', 'render_math'] # for sitemap plugin SITEMAP = { 'format': 'xml', 'priorities': { 'articles': 0.5, 'indexes': 0.5, 'pages': 0.5 }, 'changefreqs': { 'articles': 'monthly', 'indexes': 'daily', 'pages': 'monthly' } } # search is for Tipue search DIRECT_TEMPLATES = (('index', 'tags', 'categories', 'authors', 'archives', 'search')) # for pelican-bootstrap3 theme settings #TAG_CLOUD_MAX_ITEMS = 50 DISPLAY_CATEGORIES_ON_SIDEBAR = True DISPLAY_RECENT_POSTS_ON_SIDEBAR = True DISPLAY_TAGS_ON_SIDEBAR = True DISPLAY_TAGS_INLINE = True TAGS_URL = "tags.html" CATEGORIES_URL = "categories.html" #SHOW_ARTICLE_AUTHOR = True #MENUITEMS = [('Home', '/'), ('Archives', '/archives.html'), ('Search', '/search.html')] # 希望將部份常用的 Javascript 最新版程式庫放到這裡, 可以透過 http://cadlab.mde.tw/post/js/ 呼叫 STATIC_PATHS = ['js']
tsrnnash/bg8-cdw11
static/pelicanconf.py
Python
agpl-3.0
2,146
import * as React from 'react'; export interface DeleteButtonProps { questionId: string, onChange(questionId: string): void } export interface NameInputProps { name: string, onChange(value: string, e: object): void } export const DeleteButton = ({ questionId, onChange }: DeleteButtonProps) => { function handleClick() { onChange(questionId) } return <button onClick={handleClick} type="button">Delete</button>; } export const NameInput = ({ name, onChange }: NameInputProps) => { function handleChange(e: object) { onChange('name', e) }; return( <label className="label" htmlFor="activity-name-input"> Name <input aria-label="activity-name-input" className="input" id="activity-name-input" onChange={handleChange} placeholder="Text input" type="text" value={name} /> </label> ); }
empirical-org/Empirical-Core
services/QuillLMS/client/app/bundles/Diagnostic/components/lessons/lessonFormComponents.tsx
TypeScript
agpl-3.0
887
import os from flask import current_app def get_absolute_file_path(relative_path: str) -> str: return os.path.join(current_app.config['UPLOAD_FOLDER'], relative_path)
SamR1/FitTrackee
fittrackee/workouts/utils_files.py
Python
agpl-3.0
174
/* * SourceCppStartedEvent.java * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * 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.views.output.sourcecpp.events; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; public class SourceCppStartedEvent extends GwtEvent<SourceCppStartedEvent.Handler> { public interface Handler extends EventHandler { void onSourceCppStarted(SourceCppStartedEvent event); } public SourceCppStartedEvent() { } @Override public Type<Handler> getAssociatedType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onSourceCppStarted(this); } public static final Type<Handler> TYPE = new Type<>(); }
JanMarvin/rstudio
src/gwt/src/org/rstudio/studio/client/workbench/views/output/sourcecpp/events/SourceCppStartedEvent.java
Java
agpl-3.0
1,265
'use strict'; define(function(require) { var Backbone = require('backbone'), routes = require('routes'), GroupModel = require('model/groups/group-model'); var GroupsList = Backbone.Collection.extend({ model: GroupModel, url: routes.absoluteUrl(routes.GROUPS_DATA), fetch: function(options){ if (this.search) { (options || (options = {})).data = { search: this.search }; } return Backbone.Collection.prototype.fetch.call(this, options); } }); return GroupsList; })
hflabs/perecoder
rcd-web/src/main/javascript/app/model/groups/groups-list.js
JavaScript
agpl-3.0
619
/** @jsx React.DOM */ 'use strict'; var Lazy = require('lazy.js'), React = require('react'), ReactIntlMixin = require('react-intl'); var EnumerationControl = React.createClass({ mixins: [ReactIntlMixin], propTypes: { default: React.PropTypes.string, error: React.PropTypes.string, label: React.PropTypes.element.isRequired, labels: React.PropTypes.object.isRequired, name: React.PropTypes.string.isRequired, onChange: React.PropTypes.func.isRequired, suggestion: React.PropTypes.string, value: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), }, handleChange(event) { this.props.onChange(event.target.value); }, render() { var firstOptionLabel = `${this.getIntlMessage('notIndicated')} (${ this.props.suggestion ? this.formatMessage(this.getIntlMessage('suggestedValue'), {value: this.props.labels[this.props.suggestion]}) : this.formatMessage(this.getIntlMessage('defaultValue'), {value: this.props.labels[this.props.default]}) })`; return ( <div> {this.props.label} <select className="form-control" id={this.props.name} onChange={this.handleChange} value={this.props.value} > <option value="">{firstOptionLabel}</option> { Lazy(this.props.labels).map((label, labelId) => <option key={labelId} value={labelId}>{label}</option> ).toArray() } </select> </div> ); }, }); module.exports = EnumerationControl;
openfisca/openfisca-web-ui
openfisca_web_ui/static/js/components/test-case/form/enumeration-control.js
JavaScript
agpl-3.0
1,605
# -*- coding: utf-8 -*- """ This is the common settings file, intended to set sane defaults. If you have a piece of configuration that's dependent on a set of feature flags being set, then create a function that returns the calculated value based on the value of FEATURES[...]. Modules that extend this one can change the feature configuration in an environment specific config file and re-calculate those values. We should make a method that calls all these config methods so that you just make one call at the end of your site-specific dev file to reset all the dependent variables (like INSTALLED_APPS) for you. Longer TODO: 1. Right now our treatment of static content in general and in particular course-specific static content is haphazard. 2. We should have a more disciplined approach to feature flagging, even if it just means that we stick them in a dict called FEATURES. 3. We need to handle configuration for multiple courses. This could be as multiple sites, but we do need a way to map their data assets. """ # We intentionally define lots of variables that aren't used, and # want to import all variables from base settings files # pylint: disable=W0401, W0611, W0614 import sys import json import lms.envs.common from lms.envs.common import ( USE_TZ, TECH_SUPPORT_EMAIL, PLATFORM_NAME, BUGS_EMAIL, DOC_STORE_CONFIG, ALL_LANGUAGES ) from path import path from lms.lib.xblock.mixin import LmsBlockMixin from cms.lib.xblock.mixin import CmsBlockMixin from xmodule.modulestore.inheritance import InheritanceMixin from xmodule.x_module import XModuleMixin, prefer_xmodules from dealer.git import git ############################ FEATURE CONFIGURATION ############################# FEATURES = { 'USE_DJANGO_PIPELINE': True, 'GITHUB_PUSH': False, 'ENABLE_DISCUSSION_SERVICE': False, 'AUTH_USE_CERTIFICATES': False, # email address for studio staff (eg to request course creation) 'STUDIO_REQUEST_EMAIL': '', 'STUDIO_NPS_SURVEY': True, # Segment.io - must explicitly turn it on for production 'SEGMENT_IO': False, # Enable URL that shows information about the status of various services 'ENABLE_SERVICE_STATUS': False, # Don't autoplay videos for course authors 'AUTOPLAY_VIDEOS': False, # If set to True, new Studio users won't be able to author courses unless # edX has explicitly added them to the course creator group. 'ENABLE_CREATOR_GROUP': False, # whether to use password policy enforcement or not 'ENFORCE_PASSWORD_POLICY': False, # If set to True, Studio won't restrict the set of advanced components # to just those pre-approved by edX 'ALLOW_ALL_ADVANCED_COMPONENTS': False, # Turn off account locking if failed login attempts exceeds a limit 'ENABLE_MAX_FAILED_LOGIN_ATTEMPTS': False, # Allow editing of short description in course settings in cms 'EDITABLE_SHORT_DESCRIPTION': True, # Hide any Personally Identifiable Information from application logs 'SQUELCH_PII_IN_LOGS': False, # Toggles embargo functionality 'EMBARGO': False, # Turn on/off Microsites feature 'USE_MICROSITES': False, } ENABLE_JASMINE = False ########### course fields ############# # COURSE_EXTEND_FIELDS = lms.envs.common.COURSE_EXTEND_FIELDS ############################# SET PATH INFORMATION ############################# PROJECT_ROOT = path(__file__).abspath().dirname().dirname() # /edx-platform/cms REPO_ROOT = PROJECT_ROOT.dirname() COMMON_ROOT = REPO_ROOT / "common" LMS_ROOT = REPO_ROOT / "lms" ENV_ROOT = REPO_ROOT.dirname() # virtualenv dir /edx-platform is in GITHUB_REPO_ROOT = ENV_ROOT / "data" sys.path.append(REPO_ROOT) sys.path.append(PROJECT_ROOT / 'djangoapps') sys.path.append(COMMON_ROOT / 'djangoapps') sys.path.append(COMMON_ROOT / 'lib') # For geolocation ip database GEOIP_PATH = REPO_ROOT / "common/static/data/geoip/GeoIP.dat" ############################# WEB CONFIGURATION ############################# # This is where we stick our compiled template files. from tempdir import mkdtemp_clean MAKO_MODULE_DIR = mkdtemp_clean('mako') MAKO_TEMPLATES = {} MAKO_TEMPLATES['main'] = [ PROJECT_ROOT / 'templates', COMMON_ROOT / 'templates', COMMON_ROOT / 'djangoapps' / 'pipeline_mako' / 'templates', COMMON_ROOT / 'djangoapps' / 'pipeline_js' / 'templates', ] for namespace, template_dirs in lms.envs.common.MAKO_TEMPLATES.iteritems(): MAKO_TEMPLATES['lms.' + namespace] = template_dirs TEMPLATE_DIRS = MAKO_TEMPLATES['main'] EDX_ROOT_URL = '' LOGIN_REDIRECT_URL = EDX_ROOT_URL + '/signin' LOGIN_URL = EDX_ROOT_URL + '/signin' TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', 'django.core.context_processors.static', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.i18n', 'django.contrib.auth.context_processors.auth', # this is required for admin 'django.core.context_processors.csrf', 'dealer.contrib.django.staff.context_processor', # access git revision 'contentstore.context_processors.doc_url', ) # use the ratelimit backend to prevent brute force attacks AUTHENTICATION_BACKENDS = ( 'ratelimitbackend.backends.RateLimitModelBackend', ) LMS_BASE = None #################### CAPA External Code Evaluation ############################# XQUEUE_INTERFACE = { 'url': 'http://localhost:8888', 'django_auth': {'username': 'local', 'password': 'local'}, 'basic_auth': None, } ################################# Middleware ################################### # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'staticfiles.finders.FileSystemFinder', 'staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'request_cache.middleware.RequestCache', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'method_override.middleware.MethodOverrideMiddleware', # Instead of AuthenticationMiddleware, we use a cache-backed version 'cache_toolbox.middleware.CacheBackedAuthenticationMiddleware', 'student.middleware.UserStandingMiddleware', 'contentserver.middleware.StaticContentServer', 'crum.CurrentRequestUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'track.middleware.TrackMiddleware', # Allows us to dark-launch particular languages 'dark_lang.middleware.DarkLangMiddleware', 'embargo.middleware.EmbargoMiddleware', # Detects user-requested locale from 'accept-language' header in http request 'django.middleware.locale.LocaleMiddleware', 'django.middleware.transaction.TransactionMiddleware', # needs to run after locale middleware (or anything that modifies the request context) 'edxmako.middleware.MakoMiddleware', # catches any uncaught RateLimitExceptions and returns a 403 instead of a 500 'ratelimitbackend.middleware.RateLimitMiddleware', # for expiring inactive sessions 'session_inactivity_timeout.middleware.SessionInactivityTimeout', # use Django built in clickjacking protection 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) # Clickjacking protection can be enabled by setting this to 'DENY' X_FRAME_OPTIONS = 'ALLOW' ############# XBlock Configuration ########## # This should be moved into an XBlock Runtime/Application object # once the responsibility of XBlock creation is moved out of modulestore - cpennington XBLOCK_MIXINS = (LmsBlockMixin, CmsBlockMixin, InheritanceMixin, XModuleMixin) # Allow any XBlock in Studio # You should also enable the ALLOW_ALL_ADVANCED_COMPONENTS feature flag, so that # xblocks can be added via advanced settings XBLOCK_SELECT_FUNCTION = prefer_xmodules ############################ SIGNAL HANDLERS ################################ # This is imported to register the exception signal handling that logs exceptions import monitoring.exceptions # noqa ############################ DJANGO_BUILTINS ################################ # Change DEBUG/TEMPLATE_DEBUG in your environment settings files, not here DEBUG = False TEMPLATE_DEBUG = False # Site info SITE_ID = 1 SITE_NAME = "0.0.0.0:8001" HTTPS = 'on' ROOT_URLCONF = 'cms.urls' IGNORABLE_404_ENDS = ('favicon.ico') # Email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.126.com' EMAIL_PORT = 25 EMAIL_USE_TLS = False EMAIL_HOST_USER = 'xiaodunxin' EMAIL_HOST_PASSWORD = '123456qr' DEFAULT_FROM_EMAIL = 'xiaodunxin@126.com' DEFAULT_FEEDBACK_EMAIL = 'xiaodunxin@126.com' SERVER_EMAIL = 'xiaodunxin@126.com' ADMINS = () MANAGERS = ADMINS # Static content STATIC_URL = '/static/' + git.revision + "/" ADMIN_MEDIA_PREFIX = '/static/admin/' STATIC_ROOT = ENV_ROOT / "staticfiles" / git.revision STATICFILES_DIRS = [ COMMON_ROOT / "static", PROJECT_ROOT / "static", LMS_ROOT / "static", # This is how you would use the textbook images locally # ("book", ENV_ROOT / "book_images"), ] # Locale/Internationalization TIME_ZONE = 'Asia/Shanghai' # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name LANGUAGE_CODE = 'zh-cn' # http://www.i18nguy.com/unicode/language-identifiers.html SITE_NAME = 'mooc.diandiyun.com:18010' LANGUAGES = lms.envs.common.LANGUAGES USE_I18N = True USE_L10N = True # Localization strings (e.g. django.po) are under this directory LOCALE_PATHS = (REPO_ROOT + '/conf/locale',) # edx-platform/conf/locale/ # Messages MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' # If this is true, random scores will be generated for the purpose of debugging the profile graphs GENERATE_PROFILE_SCORES = False ############################### Pipeline ####################################### STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' from rooted_paths import rooted_glob PIPELINE_CSS = { 'style-vendor': { 'source_filenames': [ 'css/vendor/normalize.css', 'css/vendor/font-awesome.css', 'css/vendor/html5-input-polyfills/number-polyfill.css', 'js/vendor/CodeMirror/codemirror.css', 'css/vendor/ui-lightness/jquery-ui-1.8.22.custom.css', 'css/vendor/jquery.qtip.min.css', 'js/vendor/markitup/skins/simple/style.css', 'js/vendor/markitup/sets/wiki/style.css', ], 'output_filename': 'css/cms-style-vendor.css', }, 'style-app': { 'source_filenames': [ 'sass/style-app.css', ], 'output_filename': 'css/cms-style-app.css', }, 'style-app-extend1': { 'source_filenames': [ 'sass/style-app-extend1.css', ], 'output_filename': 'css/cms-style-app-extend1.css', }, 'style-xmodule': { 'source_filenames': [ 'sass/style-xmodule.css', ], 'output_filename': 'css/cms-style-xmodule.css', }, 'style-calendar-vendor': { 'source_filenames': [ 'css/vendor/fullcalendar/fullcalendar.css', 'css/vendor/fullcalendar/fullcalendar_s.css', 'css/vendor/fullcalendar/fullcalendar.print.css', ], 'output_filename': 'css/lms-style-fullcalendar-vendor.css', } } fullcalendar_vendor_js = [ 'js/vendor/fullcalendar/moment.min.js', 'js/vendor/fullcalendar/fullcalendar.min.js', 'js/vendor/fullcalendar/jquery-ui.custom.min.js', 'js/vendor/fullcalendar/lang-all.js', ] # test_order: Determines the position of this chunk of javascript on # the jasmine test page PIPELINE_JS = { 'module-js': { 'source_filenames': ( rooted_glob(COMMON_ROOT / 'static/', 'xmodule/descriptors/js/*.js') + rooted_glob(COMMON_ROOT / 'static/', 'xmodule/modules/js/*.js') + rooted_glob(COMMON_ROOT / 'static/', 'coffee/src/discussion/*.js') ), 'output_filename': 'js/cms-modules.js', 'test_order': 1 }, 'calendar_vendor': { 'source_filenames': fullcalendar_vendor_js, 'output_filename': 'js/lms-fullcalendar_vendor.js', 'test_order': 0, }, } PIPELINE_COMPILERS = ( 'pipeline.compilers.coffee.CoffeeScriptCompiler', ) PIPELINE_CSS_COMPRESSOR = None PIPELINE_JS_COMPRESSOR = None STATICFILES_IGNORE_PATTERNS = ( "*.py", "*.pyc" # it would be nice if we could do, for example, "**/*.scss", # but these strings get passed down to the `fnmatch` module, # which doesn't support that. :( # http://docs.python.org/2/library/fnmatch.html "sass/*.scss", "sass/*/*.scss", "sass/*/*/*.scss", "sass/*/*/*/*.scss", "coffee/*.coffee", "coffee/*/*.coffee", "coffee/*/*/*.coffee", "coffee/*/*/*/*.coffee", # Symlinks used by js-test-tool "xmodule_js", "common_static", ) PIPELINE_YUI_BINARY = 'yui-compressor' ################################# CELERY ###################################### # Message configuration CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_MESSAGE_COMPRESSION = 'gzip' # Results configuration CELERY_IGNORE_RESULT = False CELERY_STORE_ERRORS_EVEN_IF_IGNORED = True # Events configuration CELERY_TRACK_STARTED = True CELERY_SEND_EVENTS = True CELERY_SEND_TASK_SENT_EVENT = True # Exchange configuration CELERY_DEFAULT_EXCHANGE = 'edx.core' CELERY_DEFAULT_EXCHANGE_TYPE = 'direct' # Queues configuration HIGH_PRIORITY_QUEUE = 'edx.core.high' DEFAULT_PRIORITY_QUEUE = 'edx.core.default' LOW_PRIORITY_QUEUE = 'edx.core.low' CELERY_QUEUE_HA_POLICY = 'all' CELERY_CREATE_MISSING_QUEUES = True CELERY_DEFAULT_QUEUE = DEFAULT_PRIORITY_QUEUE CELERY_DEFAULT_ROUTING_KEY = DEFAULT_PRIORITY_QUEUE CELERY_QUEUES = { HIGH_PRIORITY_QUEUE: {}, LOW_PRIORITY_QUEUE: {}, DEFAULT_PRIORITY_QUEUE: {} } ############################## Video ########################################## # URL to test YouTube availability YOUTUBE_TEST_URL = 'https://gdata.youtube.com/feeds/api/videos/' ############################ APPS ##################################### INSTALLED_APPS = ( # Standard apps 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'djcelery', 'south', 'method_override', # Database-backed configuration 'config_models', # Monitor the status of services 'service_status', # Testing 'django_nose', # For CMS 'contentstore', 'course_creators', 'student', # misleading name due to sharing with lms 'course_groups', # not used in cms (yet), but tests run # Tracking 'track', 'eventtracking.django', # Monitoring 'datadog', # For asset pipelining 'edxmako', 'pipeline', 'staticfiles', 'static_replace', # comment common 'django_comment_common', # for course creator table 'django.contrib.admin', # XBlocks containing migrations 'mentoring', # for managing course modes 'course_modes', # Dark-launching languages 'dark_lang', # Student identity reverification 'reverification', # User preferences 'user_api', 'django_openid_auth', 'embargo', ) ################# EDX MARKETING SITE ################################## EDXMKTG_COOKIE_NAME = 'edxloggedin' MKTG_URLS = {} MKTG_URL_LINK_MAP = { } COURSES_WITH_UNSAFE_CODE = [] ############################## EVENT TRACKING ################################# TRACK_MAX_EVENT = 10000 TRACKING_BACKENDS = { 'logger': { 'ENGINE': 'track.backends.logger.LoggerBackend', 'OPTIONS': { 'name': 'tracking' } } } #### PASSWORD POLICY SETTINGS ##### PASSWORD_MIN_LENGTH = None PASSWORD_MAX_LENGTH = None PASSWORD_COMPLEXITY = {} PASSWORD_DICTIONARY_EDIT_DISTANCE_THRESHOLD = None PASSWORD_DICTIONARY = [] # We're already logging events, and we don't want to capture user # names/passwords. Heartbeat events are likely not interesting. TRACKING_IGNORE_URL_PATTERNS = [r'^/event', r'^/login', r'^/heartbeat'] TRACKING_ENABLED = True # Current youtube api for requesting transcripts. # for example: http://video.google.com/timedtext?lang=en&v=j_jEn79vS3g. YOUTUBE_API = { 'url': "http://video.google.com/timedtext", 'params': {'lang': 'en', 'v': 'set_youtube_id_of_11_symbols_here'} } ##### ACCOUNT LOCKOUT DEFAULT PARAMETERS ##### MAX_FAILED_LOGIN_ATTEMPTS_ALLOWED = 5 MAX_FAILED_LOGIN_ATTEMPTS_LOCKOUT_PERIOD_SECS = 15 * 60 ### JSdraw (only installed in some instances) try: import edx_jsdraw except ImportError: pass else: INSTALLED_APPS += ('edx_jsdraw',) ############## SSO KEY ################ SSO_KEY = "SSOFOUNDER" ############## user auth ############## PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher', 'django.contrib.auth.hashers.CryptPasswordHasher' ) ############## SSO KEY ################ SSO_KEY = "SSOFOUNDER" ############## BUSINESS SYSTEM ################# XIAODUN_BACK_HOST = 'http://busi.xiaodun.cn/app' ############## video mettings ################## VEDIO_MEETING_DOMAIN = "http://passport.guoshi.com/mp" ############## wenjuan domain ################## WENJUAN_DOMAIN = "http://apitest.wenjuan.com:8000" ####### wenjuan secret_key ####### WENJUAN_SECKEY = "9d15a674a6e621058f1ea9171413b7c0"
XiaodunServerGroup/ddyedx
cms/envs/common.py
Python
agpl-3.0
18,114
/* * Copyright (c) 2015. Philip DeCamp * Released under the BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause */ package bits.photosort; import java.io.*; import java.nio.*; import java.nio.channels.FileChannel; import java.text.*; public class TimestampReader { public static void main(String[] args) { try{ test1(); }catch(Exception ex) { ex.printStackTrace(); } } private static void test1() throws Exception { //String path = "/Volumes/DATA2/hsp_data/forgeorge/living_pics/039.jpg"; String path = "/Users/decamp/Photos/FILE0001.JPG"; ByteBuffer buf = bufferFile(new File(path)); long timestamp = readJpegTimestampMicros(buf); System.out.println(timestamp); if(timestamp != Long.MIN_VALUE) { System.out.println(new java.util.Date(timestamp / 1000L)); } } private static ByteBuffer bufferFile(File file) throws IOException { long size = file.length(); ByteBuffer buf = ByteBuffer.allocate((int)(size & 0x7FFFFFFF)); FileChannel chan = new FileInputStream(file).getChannel(); while(buf.remaining() > 0) { int n = chan.read(buf); if(n <= 0) throw new IOException("Read operation failed."); } chan.close(); buf.flip(); return buf; } /** * * Once we have the ExifMarker data, we need to delve into the where the timestamp * should be kept. This is a fairly grueling process because we have to go three layers * deep. * * JPEG Marker * | * -- TIFF Header * | * -- IFD0 * | * -- SubIFD * | * -- MakerNote IFD * | * -- Timestamp */ public static long readJpegTimestampMicros(ByteBuffer buf) throws IOException { buf = readExifSegment(buf); if(buf == null) return Long.MIN_VALUE; buf = readTiffHeader(buf); if(buf == null) return Long.MIN_VALUE; int offset = findIfdTagOffset(buf, 0x8769); if(offset < 0) return Long.MIN_VALUE; int off2 = findIfdTagOffset(buf, 0x9003, offset); if(off2 >= 0) { if(buf.position() + off2 + 20 > buf.limit()) return -1; DateFormat format = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss"); buf.position(buf.position() + off2); byte[] bytes = new byte[20]; buf.get(bytes); String dateString = new String(bytes); try{ return format.parse(dateString).getTime() * 1000L; }catch(ParseException ex) { return Long.MIN_VALUE; } } offset = findIfdTagOffset(buf, 0x927C, offset); if(offset < 0) return Long.MIN_VALUE; offset = findIfdTagOffset(buf, 0xFDE8, offset); if(offset < 0) return Long.MIN_VALUE; if(offset + 8 > buf.remaining()) return Long.MIN_VALUE; buf.position(buf.position() + offset); int sec = buf.getInt(); int usec = buf.getInt(); return sec * 1000000L + usec; } /** * @param buf Buffer containing JPEG. * @return buffer containing EXIF segment. */ private static ByteBuffer readExifSegment(ByteBuffer buf) { buf = buf.duplicate(); //Loop through each byte in JPEG and find markers. while(buf.remaining() >= 4) { int b = (buf.get() & 0xFF); //Markers always start with 0xFF. However, they may start with multiple 0xFFs. while(b == 0xFF) { if(buf.remaining() < 3) return null; b = (buf.get() & 0xFF); //Another 0xFF means the marker is still starting. //0x00 means the previous 0xFF was not a marker. //0xD8 and 0xD9 indicate SOE and EOF (StartOfImage or EndOfImage), which are not segments. if(b == 0xFF || b == 0x00 || b == 0xD8 || b == 0xD9) continue; //After the marker (0xFF + one-byte ID), the next two bytes indicate the segment length. //The segment length includes itself (two bytes), but not the two-byte marker. int length = (buf.getShort() & 0xFFFF) - 2; //Check if we have all the data. if(length > buf.remaining()) return null; //Check if this is the exif segment. if(b == 0xE1) { buf.limit(buf.position() + length); return buf; } buf.position(buf.position() + length); } } return null; } /** * @param buf Buffer containing EXIF segment. * @return ByteBuffer containing IFD0. */ private static ByteBuffer readTiffHeader(ByteBuffer buf) { if(buf.remaining() < 6) return null; buf = buf.duplicate(); if(buf.get() == 'E' && buf.get() == 'x' && buf.get() == 'i' && buf.get() == 'f' && buf.get() == 0 && buf.get() == 0) { return buf; } return null; } /** * @param buf Buffer containing IFD0 * @return timestamp micros, or Long.MIN_VALUE if not found. */ private static long findTimestampMicros(ByteBuffer buf) { int offset = findIfdTagOffset(buf, 0x8769); if(offset < 0) return Long.MIN_VALUE; offset = findIfdTagOffset(buf, 0x927C, offset); if(offset < 0) return Long.MIN_VALUE; offset = findIfdTagOffset(buf, 0xFDE8, offset); if(offset < 0) return Long.MIN_VALUE; if(offset + 8 > buf.remaining()) return Long.MIN_VALUE; buf = buf.duplicate(); buf.position(buf.position() + offset); int sec = buf.getInt(); int usec = buf.getInt(); return sec * 1000000L + usec; } /** * @param buf Buffer containing IFD0 * @param tag Tag of entry to locate. * @return offset of entry, or -1 if not found. */ private static int findIfdTagOffset(ByteBuffer buf, int tag) { return findIfdTagOffset(buf, tag, -1); } /** * @param buf Buffer containing IFD0 * @param tag Tag of entry to locate. * @param offset Offset of index to use, or -1 if first index should be used. * @return offset to entry, or -1 if not found. */ private static int findIfdTagOffset(ByteBuffer buf, int tag, int offset) { if(buf.remaining() < 8) return -1; buf = buf.duplicate(); int start = buf.position(); int length = buf.remaining(); //2-byte indicator of byte alignment indicator. //MM means Motoral (Big-Endian). //II means Intel (Little-Endian). { byte order = buf.get(); if(order != buf.get()) return -1; if(order == (byte)0x4D) { buf.order(ByteOrder.BIG_ENDIAN); }else if(order == (byte)0x49) { buf.order(ByteOrder.LITTLE_ENDIAN); }else{ return -1; } } //2-byte constant. if((buf.getShort() & 0xFFFF) != 0x002A) return -1; //If no offset is given, use 4-byte offset to SubIFD tag. if(offset < 0) offset = buf.getInt(); //Check offset validity. if(offset < 0 || length < offset + 2) return -1; //Get number of entries. buf.position(start + offset); int entryCount = (buf.getShort() & 0xFFFF); //Check length validity. if(length < offset + 2 + 12 * entryCount) return -1; //Find the entry. for(int i = 0; i < entryCount; i++) { buf.position(start + offset + 2 + i * 12); if((buf.getShort() & 0xFFFF) == tag) { buf.position(start + offset + 2 + i * 12 + 8); return buf.getInt(); } } return -1; } }
decamp/photosort
src/main/java/bits/photosort/TimestampReader.java
Java
agpl-3.0
8,819
var searchData= [ ['unknown',['UNKNOWN',['../classtetgenmesh.xhtml#a1d02bed7b59566d57b896776d78a6b25a51233a7db87ef44baab2026b0ebdf22f',1,'tetgenmesh']]], ['unusedvertex',['UNUSEDVERTEX',['../classtetgenmesh.xhtml#ad0458f823a5eef2de89c7fae067aa2aca1d0b671fcad449d30b826305df861a52',1,'tetgenmesh']]] ];
vroland/SimpleAnalyzer
doc/html/search/enumvalues_75.js
JavaScript
agpl-3.0
306
<?php /* Smarty version 2.6.11, created on 2015-06-17 13:35:10 compiled from cache/modules/AOW_WorkFlow/CasesDetailViewpriority.tpl */ ?> <?php if (is_string ( $this->_tpl_vars['fields']['priority']['options'] )): ?> <input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['fields']['priority']['name']; ?> " value="<?php echo $this->_tpl_vars['fields']['priority']['options']; ?> "> <?php echo $this->_tpl_vars['fields']['priority']['options']; ?> <?php else: ?> <input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['fields']['priority']['name']; ?> " value="<?php echo $this->_tpl_vars['fields']['priority']['value']; ?> "> <?php echo $this->_tpl_vars['fields']['priority']['options'][$this->_tpl_vars['fields']['priority']['value']]; ?> <?php endif; ?>
caleboau2012/edusupport
test/cache/smarty/templates_c/%%19^19B^19BA849F%%CasesDetailViewpriority.tpl.php
PHP
agpl-3.0
805
package acquire import ( "archive/zip" "bytes" "compress/gzip" "fmt" "io/ioutil" "strings" ) func unpackReport(filename string, data []byte) ([]byte, error) { dataBuffer := bytes.NewBuffer(data) if strings.HasSuffix(filename, ".gz") { file, err := gzip.NewReader(dataBuffer) if err != nil { return nil, err } return ioutil.ReadAll(file) } if strings.HasSuffix(filename, ".zip") { bt, err := ioutil.ReadAll(dataBuffer) if err != nil { return nil, err } r, err := zip.NewReader(bytes.NewReader(bt), int64(len(bt))) if err != nil { return nil, err } if len(r.File) != 1 { return nil, fmt.Errorf("Not exactly one file in zip %s", filename) } f := r.File[0] if !strings.HasSuffix(f.Name, ".xml") { return nil, fmt.Errorf("Not an xml file in zip %s", filename) } file, err3 := f.Open() if err3 != nil { return nil, err3 } return ioutil.ReadAll(file) } return nil, fmt.Errorf("Unknown extension of file %s", filename) }
martinhoefling/go-dmarc-report
acquire/unpack.go
GO
agpl-3.0
983
"""TOSEC models""" from django.db import models class Category(models.Model): name = models.CharField(max_length=256) description = models.CharField(max_length=256) category = models.CharField(max_length=256) version = models.CharField(max_length=32) author = models.CharField(max_length=128) section = models.CharField(max_length=12, default='TOSEC') def __str__(self): return self.name class Meta: verbose_name_plural = 'Categories' ordering = ('name', ) class Game(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.CharField(max_length=255) def __str__(self): return self.name class Meta: ordering = ('category', 'name') class Rom(models.Model): game = models.ForeignKey(Game, related_name='roms', on_delete=models.CASCADE) name = models.CharField(max_length=255) size = models.IntegerField() crc = models.CharField(max_length=16) md5 = models.CharField(max_length=32) sha1 = models.CharField(max_length=64) def __str__(self): return self.name
lutris/website
tosec/models.py
Python
agpl-3.0
1,177
<?php /** * Routes configuration * * In this file, you set up routes to your controllers and their actions. * Routes are very important mechanism that allows you to freely connect * different URLs to chosen controllers and their actions (functions). * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @license http://www.opensource.org/licenses/mit-license.php MIT License */ use Cake\Core\Plugin; use Cake\Routing\Router; /** * The default class to use for all routes * * The following route classes are supplied with CakePHP and are appropriate * to set as the default: * * - Route * - InflectedRoute * - DashedRoute * * If no call is made to `Router::defaultRouteClass()`, the class used is * `Route` (`Cake\Routing\Route\Route`) * * Note that `Route` does not do any inflections on URLs which will result in * inconsistently cased URLs when used with `:plugin`, `:controller` and * `:action` markers. * */ Router::defaultRouteClass('DashedRoute'); Router::scope('/', function ($routes) { $routes->connect('/', ['controller' => 'Migrations', 'action' => 'index']); /** * ...and connect the rest of 'Pages' controller's URLs. */ $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']); /** * Connect catchall routes for all controllers. * * Using the argument `DashedRoute`, the `fallbacks` method is a shortcut for * `$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'DashedRoute']);` * `$routes->connect('/:controller/:action/*', [], ['routeClass' => 'DashedRoute']);` * * Any route class can be used with this method, such as: * - DashedRoute * - InflectedRoute * - Route * - Or your own route class * * You can remove these routes once you've connected the * routes you want in your application. */ $routes->fallbacks('DashedRoute'); }); /** * Load all plugin routes. See the Plugin documentation on * how to customize the loading of plugin routes. */ Plugin::routes();
Oblady/web-task-runner-for-pentaho
config/routes.php
PHP
agpl-3.0
2,500
<?php namespace wcf\data\user\online; use wcf\data\option\OptionAction; use wcf\data\session\SessionList; use wcf\data\user\group\UserGroup; use wcf\data\user\User; use wcf\system\event\EventHandler; use wcf\system\WCF; use wcf\util\StringUtil; /** * Represents a list of currently online users. * * @author Marcel Werk * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Data\User\Online * * @method UserOnline current() * @method UserOnline[] getObjects() * @method UserOnline|null search($objectID) * @property UserOnline[] $objects */ class UsersOnlineList extends SessionList { /** * @inheritDoc */ public $sqlOrderBy = 'user_table.username'; /** * users online stats * @var array */ public $stats = [ 'total' => 0, 'invisible' => 0, 'members' => 0, 'guests' => 0 ]; /** * users online markings * @var array */ public $usersOnlineMarkings = null; /** * @inheritDoc */ public function __construct() { parent::__construct(); $this->sqlSelects .= "user_avatar.*, user_option_value.*, user_group.userOnlineMarking, user_table.*"; $this->sqlConditionJoins .= " LEFT JOIN wcf".WCF_N."_user user_table ON (user_table.userID = session.userID)"; $this->sqlJoins .= " LEFT JOIN wcf".WCF_N."_user user_table ON (user_table.userID = session.userID)"; $this->sqlJoins .= " LEFT JOIN wcf".WCF_N."_user_option_value user_option_value ON (user_option_value.userID = user_table.userID)"; $this->sqlJoins .= " LEFT JOIN wcf".WCF_N."_user_avatar user_avatar ON (user_avatar.avatarID = user_table.avatarID)"; $this->sqlJoins .= " LEFT JOIN wcf".WCF_N."_user_group user_group ON (user_group.groupID = user_table.userOnlineGroupID)"; $this->getConditionBuilder()->add('session.lastActivityTime > ?', [TIME_NOW - USER_ONLINE_TIMEOUT]); } /** * @inheritDoc */ public function readObjects() { parent::readObjects(); $objects = $this->objects; $this->indexToObject = $this->objects = []; foreach ($objects as $object) { $object = new UserOnline(new User(null, null, $object)); if (!$object->userID || self::isVisible($object->userID, $object->canViewOnlineStatus)) { $this->objects[$object->sessionID] = $object; $this->indexToObject[] = $object->sessionID; } } $this->objectIDs = $this->indexToObject; $this->rewind(); } /** * Fetches users online stats. */ public function readStats() { $conditionBuilder = clone $this->getConditionBuilder(); $conditionBuilder->add('session.spiderID IS NULL'); $sql = "SELECT user_option_value.userOption".User::getUserOptionID('canViewOnlineStatus')." AS canViewOnlineStatus, session.userID FROM wcf".WCF_N."_session session LEFT JOIN wcf".WCF_N."_user_option_value user_option_value ON (user_option_value.userID = session.userID) ".$conditionBuilder; $statement = WCF::getDB()->prepareStatement($sql); $statement->execute($conditionBuilder->getParameters()); while ($row = $statement->fetchArray()) { $this->stats['total']++; if ($row['userID']) { $this->stats['members']++; if ($row['canViewOnlineStatus'] && !self::isVisible($row['userID'], $row['canViewOnlineStatus'])) { $this->stats['invisible']++; } } else { $this->stats['guests']++; } } } /** * Returns a list of the users online markings. * * @return array */ public function getUsersOnlineMarkings() { if ($this->usersOnlineMarkings === null) { $this->usersOnlineMarkings = $priorities = []; // get groups foreach (UserGroup::getGroupsByType() as $group) { if ($group->userOnlineMarking != '%s') { $priorities[] = $group->priority; $this->usersOnlineMarkings[] = str_replace('%s', StringUtil::encodeHTML(WCF::getLanguage()->get($group->groupName)), $group->userOnlineMarking); } } // sort list array_multisort($priorities, SORT_DESC, $this->usersOnlineMarkings); } return $this->usersOnlineMarkings; } /** * Checks the users online record. */ public function checkRecord() { $usersOnlineTotal = (USERS_ONLINE_RECORD_NO_GUESTS ? $this->stats['members'] : $this->stats['total']); if ($usersOnlineTotal > USERS_ONLINE_RECORD) { // save new record $optionAction = new OptionAction([], 'import', ['data' => [ 'users_online_record' => $usersOnlineTotal, 'users_online_record_time' => TIME_NOW ]]); $optionAction->executeAction(); } } /** * Checks the 'canViewOnlineStatus' setting. * * @param integer $userID * @param integer $canViewOnlineStatus * @return boolean */ public static function isVisible($userID, $canViewOnlineStatus) { if (WCF::getSession()->getPermission('admin.user.canViewInvisible') || $userID == WCF::getUser()->userID) return true; $data = ['result' => false, 'userID' => $userID, 'canViewOnlineStatus' => $canViewOnlineStatus]; switch ($canViewOnlineStatus) { case 0: // everyone $data['result'] = true; break; case 1: // registered if (WCF::getUser()->userID) $data['result'] = true; break; case 2: // following /** @noinspection PhpUndefinedMethodInspection */ if (WCF::getUserProfileHandler()->isFollower($userID)) $data['result'] = true; break; } EventHandler::getInstance()->fireAction(get_called_class(), 'isVisible', $data); return $data['result']; } }
Morik/WCF
wcfsetup/install/files/lib/data/user/online/UsersOnlineList.class.php
PHP
lgpl-2.1
5,464
package org.cytoscape.task.internal.network; import java.util.ArrayList; import java.util.Collection; import org.cytoscape.model.CyNetwork; import org.cytoscape.service.util.CyServiceRegistrar; import org.cytoscape.task.AbstractNetworkCollectionTaskFactory; import org.cytoscape.task.destroy.DestroyNetworkTaskFactory; import org.cytoscape.work.TaskFactory; import org.cytoscape.work.TaskIterator; /* * #%L * Cytoscape Core Task Impl (core-task-impl) * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2006 - 2021 The Cytoscape Consortium * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class DestroyNetworkTaskFactoryImpl extends AbstractNetworkCollectionTaskFactory implements DestroyNetworkTaskFactory, TaskFactory { private final CyServiceRegistrar serviceRegistrar; public DestroyNetworkTaskFactoryImpl(CyServiceRegistrar serviceRegistrar) { this.serviceRegistrar = serviceRegistrar; } @Override public TaskIterator createTaskIterator(Collection<CyNetwork> networks) { return new TaskIterator(new DestroyNetworkTask(networks, serviceRegistrar)); } @Override public TaskIterator createTaskIterator() { return new TaskIterator(new DestroyNetworkTask(new ArrayList<>(), serviceRegistrar)); } @Override public boolean isReady() { return true; } }
cytoscape/cytoscape-impl
core-task-impl/src/main/java/org/cytoscape/task/internal/network/DestroyNetworkTaskFactoryImpl.java
Java
lgpl-2.1
1,942
<?php /*"****************************************************************************************************** * (c) 2004-2006 by MulchProductions, www.mulchprod.de * * (c) 2007-2015 by Kajona, www.kajona.de * * Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt * *-------------------------------------------------------------------------------------------------------* * $Id$ * ********************************************************************************************************/ /** * The top-level class for models, installers and top-level files * An instance of this class is used by the admin & portal object to invoke common database based methods. * Change with care! * * @package module_system * @author sidler@mulchprod.de */ abstract class class_root { const STR_MODULE_ANNOTATION = "@module"; const STR_MODULEID_ANNOTATION = "@moduleId"; /** * Instance of class_config * * @var class_config */ protected $objConfig = null; //Object containing config-data /** * Instance of class_db * * @var class_db */ protected $objDB = null; //Object to the database /** * Instance of class_session * * @var class_session */ protected $objSession = null; //Object containing the session-management /** * Instance of class_lang * * @var class_lang */ private $objLang = null; //Object managing the langfiles /** * @var interface_sortmanager */ protected $objSortManager = null; private $strAction; //current action to perform (GET/POST) protected $arrModule = array(); //Array containing information about the current module private $arrInitRow = null; //array to be used when loading details from the database. could reduce the amount of queries if populated. //--- fields to be synchronized with the database --- /** * The records current systemid * @var string * @templateExport * * @tableColumn system.system_id */ private $strSystemid = ""; /** * The records internal parent-id * @var string * @versionable * * @tableColumn system.system_prev_id */ private $strPrevId = -1; /** * The old prev-id, used to track hierarchical changes -> requires a rebuild of the rights-table * @var string */ private $strOldPrevId = -1; /** * The records module-number * @var int * @tableColumn system.system_module_nr */ private $intModuleNr = 0; /** * The records sort-position relative to the parent record * @var int * @tableColumn system.system_sort */ private $intSort = -1; /** * The id of the user who created the record initially * @var string * @versionable * @templateExport * @templateMapper user * @tableColumn system.system_owner */ private $strOwner = ""; /** * The id of the user last who did the last changes to the current record * @var string * @tableColumn system.system_lm_user */ private $strLmUser = ""; /** * Timestamp of the last modification * ATTENTION: time() based, so 32 bit integer * @todo migrate to long-timestamp * @var int * @templateExport * @templateMapper datetime * @tableColumn system.system_lm_time */ private $intLmTime = 0; /** * The id of the user locking the current record, empty otherwise * @var string * @tableColumn system.system_lock_id */ private $strLockId = ""; /** * Time the current locking was triggered * ATTENTION: time() based, so 32 bit integer * @todo migrate to long-timestamp * @var int * @tableColumn system.system_lock_time */ private $intLockTime = 0; /** * The records status * @var int * @versionable * @tableColumn system.system_status */ private $intRecordStatus = 1; /** * The records previous status, used to trigger status changed events * @var int */ private $intOldRecordStatus = 1; /** * Indicates whether the object is deleted, or not * @var int * @versionable * @tableColumn system.system_deleted */ private $intRecordDeleted = 0; /** * Human readable comment describing the current record * @var string * @tableColumn system.system_comment */ private $strRecordComment = ""; /** * Holds the current objects' class * @var string * @tableColumn system.system_class */ private $strRecordClass = ""; /** * Long-based representation of the timestamp the record was created initially * @var int * @templateExport * @templateMapper datetime * @tableColumn system.system_create_date */ private $longCreateDate = 0; /** * The start-date of the date-table * @var class_date * @versionable * @templateExport * @templateMapper datetime * * @tableColumn system_date.system_date_start */ private $objStartDate = null; /** * The end date of the date-table * @var class_date * @versionable * @templateExport * @templateMapper datetime * * @tableColumn system_date.system_date_end */ private $objEndDate = null; /** * The special-date of the date-table * @var class_date * @versionable * @templateExport * @templateMapper datetime * * @tableColumn system_date.system_date_special */ private $objSpecialDate = null; private $bitDatesChanges = false; /** * Constructor * * @param string $strSystemid * * @return class_root */ public function __construct($strSystemid = "") { //Generating all the needed objects. For this we use our cool cool carrier-object //take care of loading just the necessary objects $objCarrier = class_carrier::getInstance(); $this->objConfig = $objCarrier->getObjConfig(); $this->objDB = $objCarrier->getObjDB(); $this->objSession = $objCarrier->getObjSession(); $this->objLang = $objCarrier->getObjLang(); $this->objSortManager = new class_common_sortmanager($this); //And keep the action $this->strAction = $this->getParam("action"); $this->strSystemid = $strSystemid; $this->setStrRecordClass(get_class($this)); //try to load the current module-name and the moduleId by reflection $objReflection = new class_reflection($this); if(!isset($this->arrModule["modul"])) { $arrAnnotationValues = $objReflection->getAnnotationValuesFromClass(self::STR_MODULE_ANNOTATION); if(count($arrAnnotationValues) > 0) { $this->setArrModuleEntry("modul", trim($arrAnnotationValues[0])); $this->setArrModuleEntry("module", trim($arrAnnotationValues[0])); } } if(!isset($this->arrModule["moduleId"])) { $arrAnnotationValues = $objReflection->getAnnotationValuesFromClass(self::STR_MODULEID_ANNOTATION); if(count($arrAnnotationValues) > 0) { $this->setArrModuleEntry("moduleId", constant(trim($arrAnnotationValues[0]))); $this->setIntModuleNr(constant(trim($arrAnnotationValues[0]))); } } if($strSystemid != "") { $this->initObject(); } } /** * Method to invoke object initialization. * In nearly all cases, this is triggered by the framework itself. * @return void */ public final function initObject() { $this->initObjectInternal(); $this->internalInit(); //if given, read versioning information if($this instanceof interface_versionable) { $objChangelog = new class_module_system_changelog(); $objChangelog->readOldValues($this); } } /** * InitObjectInternal is called during an objects instantiation. * The default implementation tries to map all database-fields to the objects fields * and sets the values automatically. * * If you have a different column-property mapping or additional * setters to call, overwrite this method. * The row loaded from the database is available by calling $this->getArrInitRow(). * @return void */ protected function initObjectInternal() { $objORM = new class_orm_objectinit($this); $objORM->initObjectFromDb(); } /** * Init the current record with the system-fields * @return void */ private final function internalInit() { if(validateSystemid($this->getSystemid())) { if(is_array($this->arrInitRow)) { $arrRow = $this->arrInitRow; } else { $strQuery = "SELECT * FROM "._dbprefix_."system LEFT JOIN "._dbprefix_."system_date ON system_id = system_date_id WHERE system_id = ? "; $arrRow = $this->objDB->getPRow($strQuery, array($this->getSystemid())); } if(count($arrRow) > 3) { //$this->setStrSystemid($arrRow["system_id"]); $this->strPrevId =$arrRow["system_prev_id"]; $this->intModuleNr = $arrRow["system_module_nr"]; $this->intSort = $arrRow["system_sort"]; $this->strOwner = $arrRow["system_owner"]; $this->strLmUser = $arrRow["system_lm_user"]; $this->intLmTime = $arrRow["system_lm_time"]; $this->strLockId = $arrRow["system_lock_id"]; $this->intLockTime = $arrRow["system_lock_time"]; $this->intRecordStatus = $arrRow["system_status"]; $this->strRecordComment = $arrRow["system_comment"]; $this->longCreateDate = $arrRow["system_create_date"]; if(isset($arrRow["system_class"])) $this->strRecordClass = $arrRow["system_class"]; if(isset($arrRow["system_deleted"])) $this->intRecordDeleted = $arrRow["system_deleted"]; $this->strOldPrevId = $this->strPrevId; $this->intOldRecordStatus = $this->intRecordStatus; if($arrRow["system_date_start"] > 0) $this->objStartDate = new class_date($arrRow["system_date_start"]); if($arrRow["system_date_end"] > 0) $this->objEndDate = new class_date($arrRow["system_date_end"]); if($arrRow["system_date_special"] > 0) $this->objSpecialDate = new class_date($arrRow["system_date_special"]); } $this->bitDatesChanges = false; } } /** * A generic approach to count the number of object currently available. * This method is only a simple approach to determine the number of instances in the * database, if you need more specific counts, overwrite this method or add your own * implementation to the derived class. * * @param string $strPrevid * * @return int */ public static function getObjectCount($strPrevid = "") { $objORM = new class_orm_objectlist(); return $objORM->getObjectCount(get_called_class(), $strPrevid); } /** * A generic approach to load a list of objects currently available. * This method is only a simple approach to determine the instances in the * database, if you need more specific loaders, overwrite this method or add your own * implementation to the derived class. * * @param string $strPrevid * @param null|int $intStart * @param null|int $intEnd * * @return self[] */ public static function getObjectList($strPrevid = "", $intStart = null, $intEnd = null) { $objORM = new class_orm_objectlist(); return $objORM->getObjectList(get_called_class(), $strPrevid, $intStart, $intEnd); } /** * Validates if the current record may be restored * @return bool */ public function isRestorable() { //validate the parent nodes' id $objParent = class_objectfactory::getInstance()->getObject($this->getStrPrevId()); return $objParent != null && $objParent->getIntRecordDeleted() == 0; } public function restoreObject() { /** @var $this class_root|interface_model */ $this->objDB->transactionBegin(); $this->intRecordDeleted = 0; $this->intSort = $this->getNextSortValue($this->getStrPrevId()); $bitReturn = $this->updateObjectToDb(); class_objectfactory::getInstance()->removeFromCache($this->getSystemid()); class_orm_rowcache::removeSingleRow($this->getSystemid()); $this->objDB->flushQueryCache(); $this->objSortManager->fixSortOnPrevIdChange($this->strPrevId, $this->strPrevId); $bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDRESTORED_LOGICALLY, array($this->getSystemid(), get_class($this), $this)); if($bitReturn) { class_logger::getInstance()->addLogRow("successfully restored record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo); $this->objDB->transactionCommit(); return true; } else { class_logger::getInstance()->addLogRow("error restoring record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo); $this->objDB->transactionRollback(); return false; } } /** * Triggers the logical delete of the current object. * This means the object itself is not deleted, but marked as deleted. Restoring the object is * possible. * * @throws class_exception * @return bool */ public function deleteObject() { if(!$this->getLockManager()->isAccessibleForCurrentUser()) return false; /** @var $this class_root|interface_model */ $this->objDB->transactionBegin(); //validate, if there are subrecords, so child nodes to be deleted $arrChilds = $this->objDB->getPArray("SELECT system_id FROM "._dbprefix_."system where system_prev_id = ?", array($this->getSystemid())); foreach($arrChilds as $arrOneChild) { if(validateSystemid($arrOneChild["system_id"])) { $objInstance = class_objectfactory::getInstance()->getObject($arrOneChild["system_id"]); if($objInstance !== null) $objInstance->deleteObject(); } } $this->intRecordDeleted = 1; $this->intSort = -1; $bitReturn = $this->updateObjectToDb(); class_objectfactory::getInstance()->removeFromCache($this->getSystemid()); class_orm_rowcache::removeSingleRow($this->getSystemid()); $this->objDB->flushQueryCache(); $this->objSortManager->fixSortOnDelete(); $bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDDELETED_LOGICALLY, array($this->getSystemid(), get_class($this))); if($bitReturn) { class_logger::getInstance()->addLogRow("successfully deleted record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo); $this->objDB->transactionCommit(); return true; } else { class_logger::getInstance()->addLogRow("error deleting record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo); $this->objDB->transactionRollback(); return false; } } /** * Deletes the object from the database. The record is removed in total, so no restoring will be possible. * * @return bool * @throws class_exception */ public function deleteObjectFromDatabase() { if(!$this->getLockManager()->isAccessibleForCurrentUser()) return false; if($this instanceof interface_versionable) { $objChanges = new class_module_system_changelog(); $objChanges->createLogEntry($this, class_module_system_changelog::$STR_ACTION_DELETE); } /** @var $this class_root|interface_model */ $this->objDB->transactionBegin(); //validate, if there are subrecords, so child nodes to be deleted $arrChilds = $this->objDB->getPArray("SELECT system_id FROM "._dbprefix_."system where system_prev_id = ?", array($this->getSystemid())); foreach($arrChilds as $arrOneChild) { if(validateSystemid($arrOneChild["system_id"])) { $objInstance = class_objectfactory::getInstance()->getObject($arrOneChild["system_id"]); if($objInstance !== null) $objInstance->deleteObjectFromDatabase(); } } $objORM = new class_orm_objectdelete($this); $bitReturn = $objORM->deleteObject(); $this->objSortManager->fixSortOnDelete(); $bitReturn = $bitReturn && $this->deleteSystemRecord($this->getSystemid()); class_objectfactory::getInstance()->removeFromCache($this->getSystemid()); class_orm_rowcache::removeSingleRow($this->getSystemid()); //try to call other modules, maybe wanting to delete anything in addition, if the current record //is going to be deleted $bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDDELETED, array($this->getSystemid(), get_class($this))); if($bitReturn) { class_logger::getInstance()->addLogRow("successfully deleted record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo); $this->objDB->transactionCommit(); $this->objDB->flushQueryCache(); return true; } else { class_logger::getInstance()->addLogRow("error deleting record ".$this->getSystemid()." / ".$this->getStrDisplayName(), class_logger::$levelInfo); $this->objDB->transactionRollback(); $this->objDB->flushQueryCache(); return false; } } // --- DATABASE-SYNCHRONIZATION ------------------------------------------------------------------------- /** * Saves the current object to the database. Determines, whether the current object has to be inserted * or updated to the database. * In case of an update, the objects' updateStateToDb() method is being called (as required by class_model). * In the case of a new object, a blank record is being created. Therefore, all tables returned by class' doc comment * will be filled with a new record (using the same new systemid as the primary key). * The newly created systemid is being set as the current objects' one and can be used in the afterwards * called updateStateToDb() method to reference the correct rows. * * @param string|bool $strPrevId The prev-id of the records, either to be used for the insert or to be used during the update of the record * @return bool * @since 3.3.0 * @throws class_exception * @see interface_model * * @todo move to class_orm_objectupdate completely */ public function updateObjectToDb($strPrevId = false) { $bitCommit = true; /** @var $this class_root|interface_model */ if(!$this instanceof interface_model) throw new class_exception("current object must implemented interface_model", class_exception::$level_FATALERROR); if(!$this->getLockManager()->isAccessibleForCurrentUser()) { $objUser = new class_module_user_user($this->getLockManager()->getLockId()); throw new class_exception("current object is locked by user ".$objUser->getStrDisplayName(), class_exception::$level_ERROR); } if(is_object($strPrevId) && $strPrevId instanceof class_root) $strPrevId = $strPrevId->getSystemid(); $this->objDB->transactionBegin(); //current systemid given? if not, create a new record. $bitRecordCreated = false; if(!validateSystemid($this->getSystemid())) { $bitRecordCreated = true; if($strPrevId === false || $strPrevId === "" || $strPrevId === null) { //try to find the current modules-one if(isset($this->arrModule["modul"])) { $strPrevId = class_module_system_module::getModuleByName($this->getArrModule("modul"), true)->getSystemid(); if(!validateSystemid($strPrevId)) throw new class_exception("automatic determination of module-id failed ", class_exception::$level_FATALERROR); } else throw new class_exception("insert with no previd ", class_exception::$level_FATALERROR); } if(!validateSystemid($strPrevId) && $strPrevId !== "0") { throw new class_exception("insert with erroneous prev-id ", class_exception::$level_FATALERROR); } //create the new systemrecord //store date-bit temporary $bitDates = $this->bitDatesChanges; $this->createSystemRecord($strPrevId, $this->getStrDisplayName()); $this->bitDatesChanges = $bitDates; if(validateSystemid($this->getStrSystemid())) { //Create the foreign records $objAnnotations = new class_reflection($this); $arrTargetTables = $objAnnotations->getAnnotationValuesFromClass("@targetTable"); if(count($arrTargetTables) > 0) { foreach($arrTargetTables as $strOneConfig) { $arrSingleTable = explode(".", $strOneConfig); $strQuery = "INSERT INTO ".$this->objDB->encloseTableName(_dbprefix_.$arrSingleTable[0])." (".$this->objDB->encloseColumnName($arrSingleTable[1]).") VALUES (?) "; if(!$this->objDB->_pQuery($strQuery, array($this->getStrSystemid()))) $bitCommit = false; } } if(!$this->onInsertToDb()) $bitCommit = false; } else throw new class_exception("creation of systemrecord failed", class_exception::$level_FATALERROR); //all updates are done, start the "real" update class_carrier::getInstance()->flushCache(class_carrier::INT_CACHE_TYPE_DBQUERIES); } //new prev-id? if($strPrevId !== false && $this->getSystemid() != $strPrevId && (validateSystemid($strPrevId) || $strPrevId == "0")) { //validate the new prev id - it is not allowed to set a parent-node as a sub-node of its own child if(!$this->isSystemidChildNode($this->getSystemid(), $strPrevId)) $this->setStrPrevId($strPrevId); } //new comment? $this->setStrRecordComment($this->getStrDisplayName()); //Keep old and new status here, status changed event is being fired after record is completely updated (so after updateStateToDb()) $intOldStatus = $this->intOldRecordStatus; $intNewStatus = $this->intRecordStatus; //save back to the database $bitCommit = $bitCommit && $this->updateSystemrecord(); //update ourselves to the database if($bitCommit && !$this->updateStateToDb()) $bitCommit = false; //now fire the status changed event if($intOldStatus != $intNewStatus && $intOldStatus != -1) { class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_STATUSCHANGED, array($this->getSystemid(), $this, $intOldStatus, $intNewStatus)); } if($bitCommit) { $this->objDB->transactionCommit(); //unlock the record $this->getLockManager()->unlockRecord(); class_logger::getInstance()->addLogRow("updateObjectToDb() succeeded for systemid ".$this->getSystemid()." (".$this->getRecordComment().")", class_logger::$levelInfo); } else { $this->objDB->transactionRollback(); class_logger::getInstance()->addLogRow("updateObjectToDb() failed for systemid ".$this->getSystemid()." (".$this->getRecordComment().")", class_logger::$levelWarning); } //call the recordUpdated-Listeners class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDUPDATED, array($this, $bitRecordCreated)); class_carrier::getInstance()->flushCache(class_carrier::INT_CACHE_TYPE_DBQUERIES); return $bitCommit; } /** * A default implementation for copy-operations. * Overwrite this method if you want to execute additional statements. * Please be aware that you are working on the new object afterwards! * * @param string $strNewPrevid * @param bool $bitChangeTitle * @param bool $bitCopyChilds * * @throws class_exception * @return bool */ public function copyObject($strNewPrevid = "", $bitChangeTitle = true, $bitCopyChilds = true) { $this->objDB->transactionBegin(); $strOldSysid = $this->getSystemid(); if($strNewPrevid == "") $strNewPrevid = $this->strPrevId; //any date-objects to copy? if($this->objStartDate != null || $this->objEndDate != null || $this->objSpecialDate != null) $this->bitDatesChanges = true; //check if there's a title field, in most cases that could be used to change the title if($bitChangeTitle) { $objReflection = new class_reflection($this); $strGetter = $objReflection->getGetter("strTitle"); $strSetter = $objReflection->getSetter("strTitle"); if($strGetter != null && $strSetter != null) { $strTitle = call_user_func(array($this, $strGetter)); if($strTitle != "") { call_user_func(array($this, $strSetter), $strTitle."_copy"); } } } //prepare the current object $this->unsetSystemid(); $this->arrInitRow = null; $bitReturn = $this->updateObjectToDb($strNewPrevid); //call event listeners $bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDCOPIED, array($strOldSysid, $this->getSystemid(), $this)); if($bitCopyChilds) { //process subrecords //validate, if there are subrecords, so child nodes to be copied to the current record $arrChilds = $this->objDB->getPArray("SELECT system_id FROM "._dbprefix_."system where system_prev_id = ? ORDER BY system_sort ASC", array($strOldSysid)); foreach($arrChilds as $arrOneChild) { if(validateSystemid($arrOneChild["system_id"])) { $objInstance = class_objectfactory::getInstance()->getObject($arrOneChild["system_id"]); if($objInstance !== null) $objInstance->copyObject($this->getSystemid(), false); } } } if($bitReturn) $this->objDB->transactionCommit(); else $this->objDB->transactionRollback(); $this->objDB->flushQueryCache(); $bitReturn = $bitReturn && class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_RECORDCOPYFINISHED, array($strOldSysid, $this->getSystemid(), $this)); return $bitReturn; } /** * Internal helper, checks if a child-node is the descendant of a given base-node * * @param string $strBaseId * @param string $strChildId * * @return bool */ private function isSystemidChildNode($strBaseId, $strChildId) { while(validateSystemid($strChildId)) { $objCommon = new class_module_system_common($strChildId); if($objCommon->getSystemid() == $strBaseId) return true; else return $this->isSystemidChildNode($strBaseId, $objCommon->getPrevId()); } return false; } /** * Called whenever a update-request was fired. * Use this method to synchronize the current object with the database. * Use only updates, inserts are not required to be implemented. * Provides a default implementation based on the current objects column mappings. * Override this method whenever you want to perform additional actions or escaping. * * @throws class_exception * @return bool */ protected function updateStateToDb() { $objORMMapper = new class_orm_objectupdate($this); return $objORMMapper->updateStateToDb(); } /** * Overwrite this method if you want to trigger additional commands during the insert * of an object, e.g. to create additional objects / relations * * @return bool */ protected function onInsertToDb() { return true; } /** * Updates the current record to the database and saves all relevant fields. * Please note that this method is triggered internally. * * @return bool * @final * @since 3.4.1 * * @todo find ussages and make private */ protected final function updateSystemrecord() { if(!validateSystemid($this->getSystemid())) return true; class_logger::getInstance()->addLogRow("updated systemrecord ".$this->getStrSystemid()." data", class_logger::$levelInfo); if(class_module_system_module::getModuleByName("system") != null && version_compare(class_module_system_module::getModuleByName("system")->getStrVersion(), 4.5, "lt")) { $strQuery = "UPDATE "._dbprefix_."system SET system_prev_id = ?, system_module_nr = ?, system_sort = ?, system_owner = ?, system_lm_user = ?, system_lm_time = ?, system_lock_id = ?, system_lock_time = ?, system_status = ?, system_comment = ?, system_class = ?, system_create_date = ? WHERE system_id = ? "; $bitReturn = $this->objDB->_pQuery( $strQuery, array( $this->getStrPrevId(), (int)$this->getIntModuleNr(), (int)$this->getIntSort(), $this->getStrOwner(), $this->objSession->getUserID(), time(), $this->getStrLockId(), (int)$this->getIntLockTime(), (int)$this->getIntRecordStatus(), uniStrTrim($this->getStrRecordComment(), 245), $this->getStrRecordClass(), $this->getLongCreateDate(), $this->getSystemid() ) ); } else { $strQuery = "UPDATE "._dbprefix_."system SET system_prev_id = ?, system_module_nr = ?, system_sort = ?, system_owner = ?, system_lm_user = ?, system_lm_time = ?, system_lock_id = ?, system_lock_time = ?, system_status = ?, system_comment = ?, system_class = ?, system_create_date = ?, system_deleted = ? WHERE system_id = ? "; $bitReturn = $this->objDB->_pQuery( $strQuery, array( $this->getStrPrevId(), (int)$this->getIntModuleNr(), (int)$this->getIntSort(), $this->getStrOwner(), $this->objSession->getUserID(), time(), $this->getStrLockId(), (int)$this->getIntLockTime(), (int)$this->getIntRecordStatus(), uniStrTrim($this->getStrRecordComment(), 245), $this->getStrRecordClass(), $this->getLongCreateDate(), $this->getIntRecordDeleted(), $this->getSystemid() ) ); } if($this->bitDatesChanges) { $this->processDateChanges(); } class_carrier::getInstance()->flushCache(class_carrier::INT_CACHE_TYPE_DBQUERIES | class_carrier::INT_CACHE_TYPE_ORMCACHE); if($this->strOldPrevId != $this->strPrevId && $this->strOldPrevId != -1) { class_carrier::getInstance()->getObjRights()->rebuildRightsStructure($this->getSystemid()); class_core_eventdispatcher::getInstance()->notifyGenericListeners(class_system_eventidentifier::EVENT_SYSTEM_PREVIDCHANGED, array($this->getSystemid(), $this->strOldPrevId, $this->strPrevId)); } if($this->strOldPrevId != $this->strPrevId) { $this->objSortManager->fixSortOnPrevIdChange($this->strOldPrevId, $this->strPrevId); } $this->strOldPrevId = $this->strPrevId; $this->intOldRecordStatus = $this->intRecordStatus; return $bitReturn; } /** * Internal helper to fetch the next sort-id * @param string $strPrevId * * @return int */ private function getNextSortValue($strPrevId) { //determine the correct new sort-id - append by default if(class_module_system_module::getModuleByName("system") != null && version_compare(class_module_system_module::getModuleByName("system")->getStrVersion(), "4.7.5", "lt")) { $strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system WHERE system_prev_id = ? AND system_id != '0'"; } else { $strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system WHERE system_prev_id = ? AND system_id != '0' AND system_deleted = 0"; } $arrRow = $this->objDB->getPRow($strQuery, array($strPrevId), 0, false); $intSiblings = $arrRow["COUNT(*)"]; return (int)($intSiblings+1); } /** * Generates a new SystemRecord and, if needed, the corresponding record in the rights-table (here inheritance is default) * Returns the systemID used for this record * * @param string $strPrevId Previous ID in the tree-structure * @param string $strComment Comment to identify the record * @return string The ID used/generated * * * @todo find ussages and make private */ private function createSystemRecord($strPrevId, $strComment) { $strSystemId = generateSystemid(); $this->setStrSystemid($strSystemId); //Correct prevID if($strPrevId == "") $strPrevId = 0; $this->setStrPrevId($strPrevId); //determine the correct new sort-id - append by default if(class_module_system_module::getModuleByName("system") != null && version_compare(class_module_system_module::getModuleByName("system")->getStrVersion(), "4.7.5", "lt")) { $strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system WHERE system_prev_id = ? AND system_id != '0'"; } else { $strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system WHERE system_prev_id = ? AND system_id != '0' AND system_deleted = 0"; } $arrRow = $this->objDB->getPRow($strQuery, array($strPrevId), 0, false); $intSiblings = $arrRow["COUNT(*)"]; $strComment = uniStrTrim(strip_tags($strComment), 240); if(class_module_system_module::getModuleByName("system") != null && version_compare(class_module_system_module::getModuleByName("system")->getStrVersion(), "4.7.5", "lt")) { //So, lets generate the record $strQuery = "INSERT INTO "._dbprefix_."system ( system_id, system_prev_id, system_module_nr, system_owner, system_create_date, system_lm_user, system_lm_time, system_status, system_comment, system_sort, system_class) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; //Send the query to the db $this->objDB->_pQuery( $strQuery, array( $strSystemId, $strPrevId, $this->getIntModuleNr(), $this->objSession->getUserID(), class_date::getCurrentTimestamp(), $this->objSession->getUserID(), time(), (int)$this->getIntRecordStatus(), $strComment, $this->getNextSortValue($strPrevId), $this->getStrRecordClass() ) ); } else { //So, lets generate the record $strQuery = "INSERT INTO "._dbprefix_."system ( system_id, system_prev_id, system_module_nr, system_owner, system_create_date, system_lm_user, system_lm_time, system_status, system_comment, system_sort, system_class, system_deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; //Send the query to the db $this->objDB->_pQuery( $strQuery, array( $strSystemId, $strPrevId, $this->getIntModuleNr(), $this->objSession->getUserID(), class_date::getCurrentTimestamp(), $this->objSession->getUserID(), time(), (int)$this->getIntRecordStatus(), $strComment, (int)($intSiblings + 1), $this->getStrRecordClass(), $this->getIntRecordDeleted() ) ); } //we need a Rights-Record $this->objDB->_pQuery("INSERT INTO "._dbprefix_."system_right (right_id, right_inherit) VALUES (?, 1)", array($strSystemId)); //update rights to inherit class_carrier::getInstance()->getObjRights()->setInherited(true, $strSystemId); class_logger::getInstance()->addLogRow("new system-record created: ".$strSystemId ." (".$strComment.")", class_logger::$levelInfo); $this->objDB->flushQueryCache(); $this->internalInit(); //reset the old values since we're having a new record $this->strOldPrevId = -1; $this->intOldRecordStatus = -1; return $strSystemId; } /** * Process date changes handles the insert and update of date-objects. * It replaces the old createDate and updateDate methods * @return bool */ private function processDateChanges() { $intStart = 0; $intEnd = 0; $intSpecial = 0; if($this->objStartDate != null && $this->objStartDate instanceof class_date) $intStart = $this->objStartDate->getLongTimestamp(); if($this->objEndDate != null && $this->objEndDate instanceof class_date) $intEnd = $this->objEndDate->getLongTimestamp(); if($this->objSpecialDate != null && $this->objSpecialDate instanceof class_date) $intSpecial = $this->objSpecialDate->getLongTimestamp(); $arrRow = $this->objDB->getPRow("SELECT COUNT(*) FROM "._dbprefix_."system_date WHERE system_date_id = ?", array($this->getSystemid())); if($arrRow["COUNT(*)"] == 0) { //insert $strQuery = "INSERT INTO "._dbprefix_."system_date (system_date_id, system_date_start, system_date_end, system_date_special) VALUES (?, ?, ?, ?)"; return $this->objDB->_pQuery($strQuery, array($this->getSystemid(), $intStart, $intEnd, $intSpecial)); } else { $strQuery = "UPDATE "._dbprefix_."system_date SET system_date_start = ?, system_date_end = ?, system_date_special = ? WHERE system_date_id = ?"; return $this->objDB->_pQuery($strQuery, array($intStart, $intEnd, $intSpecial, $this->getSystemid())); } } /** * Creates a record in the date table. Make sure to use a proper system-id! * Up from Kajona V3.3, the signature changed. Pass instances of class_date instead of * int-values. * * @param string $strSystemid * @param class_date $objStartDate * @param class_date $objEndDate * @param class_date $objSpecialDate * @deprecated use the internal date-objects to have all dates handled automatically * @return bool */ public function createDateRecord($strSystemid, class_date $objStartDate = null, class_date $objEndDate = null, class_date $objSpecialDate = null) { $intStart = 0; $intEnd = 0; $intSpecial = 0; if($objStartDate != null && $objStartDate instanceof class_date) $intStart = $objStartDate->getLongTimestamp(); if($objEndDate != null && $objEndDate instanceof class_date) $intEnd = $objEndDate->getLongTimestamp(); if($objSpecialDate != null && $objSpecialDate instanceof class_date) $intSpecial = $objSpecialDate->getLongTimestamp(); $strQuery = "INSERT INTO "._dbprefix_."system_date (system_date_id, system_date_start, system_date_end, system_date_special) VALUES (?, ?, ?, ?)"; return $this->objDB->_pQuery($strQuery, array($strSystemid, $intStart, $intEnd, $intSpecial)); } /** * Updates a record in the date table. Make sure to use a proper system-id! * Up from Kajona V3.3, the signature changed. Pass instances of class_date instead of * int-values. * * @param string $strSystemid * @param class_date $objStartDate * @param class_date $objEndDate * @param class_date $objSpecialDate * @deprecated use the internal date-objects to have all dates handled automatically * @return bool */ public function updateDateRecord($strSystemid, class_date $objStartDate = null, class_date $objEndDate = null, class_date $objSpecialDate = null) { $intStart = 0; $intEnd = 0; $intSpecial = 0; if($objStartDate != null && $objStartDate instanceof class_date) $intStart = $objStartDate->getLongTimestamp(); if($objEndDate != null && $objEndDate instanceof class_date) $intEnd = $objEndDate->getLongTimestamp(); if($objSpecialDate != null && $objSpecialDate instanceof class_date) $intSpecial = $objSpecialDate->getLongTimestamp(); $strQuery = "UPDATE "._dbprefix_."system_date SET system_date_start = ?, system_date_end = ?, system_date_special = ? WHERE system_date_id = ?"; return $this->objDB->_pQuery($strQuery, array($intStart, $intEnd, $intSpecial, $strSystemid)); } /** * Returns the bool-value for the right to view this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightView() { return class_carrier::getInstance()->getObjRights()->rightView($this->getSystemid()); } /** * Returns the bool-value for the right to edit this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightEdit() { return class_carrier::getInstance()->getObjRights()->rightEdit($this->getSystemid()); } /** * Returns the bool-value for the right to delete this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightDelete() { return class_carrier::getInstance()->getObjRights()->rightDelete($this->getSystemid()); } /** * Returns the bool-value for the right to change rights of this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightRight() { return class_carrier::getInstance()->getObjRights()->rightRight($this->getSystemid()); } /** * Returns the bool-value for the right1 of this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightRight1() { return class_carrier::getInstance()->getObjRights()->rightRight1($this->getSystemid()); } /** * Returns the bool-value for the right2 of this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightRight2() { return class_carrier::getInstance()->getObjRights()->rightRight2($this->getSystemid()); } /** * Returns the bool-value for the right3 of this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightRight3() { return class_carrier::getInstance()->getObjRights()->rightRight3($this->getSystemid()); } /** * Returns the bool-value for the right4 of this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightRight4() { return class_carrier::getInstance()->getObjRights()->rightRight4($this->getSystemid()); } /** * Returns the bool-value for the right5 of this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightRight5() { return class_carrier::getInstance()->getObjRights()->rightRight5($this->getSystemid()); } /** * Returns the bool-value for the changelog permissions of this record, * Systemid MUST be given, otherwise false * * @return bool */ public function rightChangelog() { return class_carrier::getInstance()->getObjRights()->rightChangelog($this->getSystemid()); } // --- SystemID & System-Table Methods ------------------------------------------------------------------ /** * Fetches the number of siblings belonging to the passed systemid * * @param string $strSystemid * @param bool $bitUseCache * @return int * @deprecated */ public function getNumberOfSiblings($strSystemid = "", $bitUseCache = true) { if($strSystemid == "") $strSystemid = $this->getSystemid(); $strQuery = "SELECT COUNT(*) FROM "._dbprefix_."system as sys1, "._dbprefix_."system as sys2 WHERE sys1.system_id=? AND sys2.system_prev_id = sys1.system_prev_id"; $arrRow = $this->objDB->getPRow($strQuery, array($strSystemid), 0, $bitUseCache); return $arrRow["COUNT(*)"]; } /** * Fetches the records placed as child nodes of the current / passed id. * <b> Only the IDs are fetched since the current object-context is not available!!! </b> * * @param string $strSystemid * @return string[] * @deprecated */ public function getChildNodesAsIdArray($strSystemid = "") { if($strSystemid == "") $strSystemid = $this->getSystemid(); $objORM = new class_orm_objectlist(); $strQuery = "SELECT system_id FROM "._dbprefix_."system WHERE system_prev_id=? AND system_id != '0' ".$objORM->getDeletedWhereRestriction()." ORDER BY system_sort ASC"; $arrReturn = array(); $arrTemp = $this->objDB->getPArray($strQuery, array($strSystemid)); if(count($arrTemp) > 0) foreach($arrTemp as $arrOneRow) $arrReturn[] = $arrOneRow["system_id"]; return $arrReturn; } /** * Fetches all child nodes recusrsively of the current / passed id. * <b> Only the IDs are fetched since the current object-context is not available!!! </b> * * @param string $strSystemid * @return string[] * @deprecated */ public function getAllSubChildNodesAsIdArray($strSystemid = "") { $arrReturn = $this->getChildNodesAsIdArray($strSystemid); if(count($arrReturn) > 0) { foreach($arrReturn as $strId) { $arrReturn = array_merge($arrReturn, $this->getAllSubChildNodesAsIdArray($strId)); } } return $arrReturn; } /** * Sets the Position of a SystemRecord in the currect level one position upwards or downwards * * @param string $strDirection upwards || downwards * @return void * @deprecated */ public function setPosition($strDirection = "upwards") { $this->objSortManager->setPosition($strDirection); } /** * Sets the position of systemid using a given value. * * @param int $intNewPosition * @param array|bool $arrRestrictionModules If an array of module-ids is passed, the determination of siblings will be limited to the module-records matching one of the module-ids * * @return void */ public function setAbsolutePosition($intNewPosition, $arrRestrictionModules = false) { $this->objSortManager->setAbsolutePosition($intNewPosition, $arrRestrictionModules); } /** * Return a complete SystemRecord * * @param string $strSystemid * @return mixed */ public function getSystemRecord($strSystemid = "") { if($strSystemid == "") $strSystemid = $this->getSystemid(); $strQuery = "SELECT * FROM "._dbprefix_."system LEFT JOIN "._dbprefix_."system_right ON system_id = right_id LEFT JOIN "._dbprefix_."system_date ON system_id = system_date_id WHERE system_id = ?"; return $this->objDB->getPRow($strQuery, array($strSystemid)); } /** * Returns the data for a registered module * * @param string $strName * @param bool $bitCache * @return mixed * @deprecated * @see class_module_system_module::getPlainModuleData($strName, $bitCache) */ public function getModuleData($strName, $bitCache = true) { return class_module_system_module::getPlainModuleData($strName, $bitCache); } /** * Deletes a record from the SystemTable * * @param string $strSystemid * @param bool $bitRight * @param bool $bitDate * @return bool * @todo: remove first params, is always the current systemid. maybe mark as protected, currently only called by the test-classes * * * @todo find ussages and make private * */ public final function deleteSystemRecord($strSystemid, $bitRight = true, $bitDate = true) { $bitResult = true; //Start a tx before deleting anything $this->objDB->transactionBegin(); $strQuery = "DELETE FROM "._dbprefix_."system WHERE system_id = ?"; $bitResult = $bitResult && $this->objDB->_pQuery($strQuery, array($strSystemid)); if($bitRight) { $strQuery = "DELETE FROM "._dbprefix_."system_right WHERE right_id = ?"; $bitResult = $bitResult && $this->objDB->_pQuery($strQuery, array($strSystemid)); } if($bitDate) { $strQuery = "DELETE FROM "._dbprefix_."system_date WHERE system_date_id = ?"; $bitResult = $bitResult && $this->objDB->_pQuery($strQuery, array($strSystemid)); } //end tx if($bitResult) { $this->objDB->transactionCommit(); class_logger::getInstance()->addLogRow("deleted system-record with id ".$strSystemid, class_logger::$levelInfo); } else { $this->objDB->transactionRollback();; class_logger::getInstance()->addLogRow("deletion of system-record with id ".$strSystemid." failed", class_logger::$levelWarning); } //flush the cache $this->flushCompletePagesCache(); return $bitResult; } /** * Deletes a record from the rights-table * * @param string $strSystemid * @return bool */ public function deleteRight($strSystemid) { $strQuery = "DELETE FROM "._dbprefix_."system_right WHERE right_id = ?"; return $this->objDB->_pQuery($strQuery, array($strSystemid)); } /** * Generates a sorted array of systemids, reaching from the passed systemid up * until the assigned module-id * * @param string $strSystemid * @param string $strStopSystemid * @return mixed */ public function getPathArray($strSystemid = "", $strStopSystemid = "0") { $arrReturn = array(); if($strSystemid == "") { $strSystemid = $this->getSystemid(); } //loop over all parent-records $strTempId = $strSystemid; while($strTempId != "0" && $strTempId != "" && $strTempId != -1 && $strTempId != $strStopSystemid) { $arrReturn[] = $strTempId; $objCommon = class_objectfactory::getInstance()->getObject($strTempId); if($objCommon === null) { break; } $strTempId = $objCommon->getPrevId(); } $arrReturn = array_reverse($arrReturn); return $arrReturn; } /** * Returns a value from the $arrModule array. * If the requested key not exists, returns "" * * @param string $strKey * @return string */ public function getArrModule($strKey) { if(isset($this->arrModule[$strKey])) return $this->arrModule[$strKey]; else return ""; } // --- TextMethods -------------------------------------------------------------------------------------- /** * Used to load a property. * If you want to provide a list of parameters but no module (automatic loading), pass * the parameters array as the second argument (an array). In this case the module is resolved * internally. * * @param string $strName * @param string|array $strModule Either the module name (if required) or an array of parameters * @param array $arrParameters * * @return string */ public function getLang($strName, $strModule = "", $arrParameters = array()) { if(is_array($strModule)) $arrParameters = $strModule; if($strModule == "" || is_array($strModule)) { $strModule = $this->getArrModule("modul"); } //Now we have to ask the Text-Object to return the text return $this->objLang->getLang($strName, $strModule, $arrParameters); } /** * Returns the current Text-Object Instance * * @return class_lang */ protected function getObjLang() { return $this->objLang; } // --- PageCache Features ------------------------------------------------------------------------------- /** * Deletes the complete Pages-Cache * * @return bool */ public function flushCompletePagesCache() { return class_cache::flushCache("class_element_portal"); } /** * Removes one page from the cache * * @param string $strPagename * @return bool */ public function flushPageFromPagesCache($strPagename) { return class_cache::flushCache("class_element_portal", $strPagename); } // --- Portal-Language ---------------------------------------------------------------------------------- /** * Returns the language to display contents on the portal * * @return string */ public final function getStrPortalLanguage() { $objLanguage = new class_module_languages_language(); return $objLanguage->getPortalLanguage(); } // --- Admin-Language ---------------------------------------------------------------------------------- /** * Returns the language to display contents or to edit contents on adminside * NOTE: THIS ARE THE CONTENTS, NOT THE TEXTS * * @return string */ public final function getStrAdminLanguageToWorkOn() { $objLanguage = new class_module_languages_language(); return $objLanguage->getAdminLanguage(); } // --- GETTERS / SETTERS ---------------------------------------------------------------------------- /** * Sets the current SystemID * * @param string $strID * @return bool */ public function setSystemid($strID) { if(validateSystemid($strID)) { $this->strSystemid = $strID; return true; } else return false; } /** * Resets the current systemid * @return void */ public function unsetSystemid() { $this->strSystemid = ""; } /** * Returns the current SystemID * * @return string */ public function getSystemid() { return $this->strSystemid; } /** * @return string */ public function getStrSystemid() { return $this->strSystemid; } /** * @param string $strSystemid * @return void */ public function setStrSystemid($strSystemid) { if(validateSystemid($strSystemid)) { $this->strSystemid = $strSystemid; } } /** * Gets the Prev-ID of a record * * @param string $strSystemid * * @throws class_exception * @return string */ public function getPrevId($strSystemid = "") { if($strSystemid != "") throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR); return $this->getStrPrevId(); } /** * @return string */ public function getStrPrevId() { return $this->strPrevId; } /** * @param string $strPrevId * @return void */ public function setStrPrevId($strPrevId) { if(validateSystemid($strPrevId) || $strPrevId === "0") { $this->strPrevId = $strPrevId; } } /** * Gets the module id / module nr of a systemRecord * * @param string $strSystemid * * @throws class_exception * @return int */ public function getRecordModuleNr($strSystemid = "") { if($strSystemid != "") throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR); return $this->getIntModuleNr(); } /** * @return int */ public function getIntModuleNr() { return $this->intModuleNr; } /** * @param int $intModuleNr * @return void */ public function setIntModuleNr($intModuleNr) { $this->intModuleNr = $intModuleNr; } /** * @return int */ public function getIntSort() { return $this->intSort; } /** * @param int $intSort * @return void */ public function setIntSort($intSort) { $this->intSort = $intSort; } /** * Returns the name of the user who last edited the record * * @param string $strSystemid * * @throws class_exception * @return string */ public function getLastEditUser($strSystemid = "") { if($strSystemid != "") throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR); if(validateSystemid($this->getStrLmUser())) { $objUser = new class_module_user_user($this->getStrLmUser()); return $objUser->getStrDisplayName(); } else return "System"; } /** * @return string string */ public function getStrLmUser() { return $this->strLmUser; } /** * Returns the id of the user who last edited the record * * @return string */ public function getLastEditUserId() { return $this->getStrLmUser(); } /** * @param string $strLmUser * @return void */ public function setStrLmUser($strLmUser) { $this->strLmUser = $strLmUser; } /** * @return int */ public function getIntLmTime() { return $this->intLmTime; } /** * @param int $strLmTime * @return void */ public function setIntLmTime($strLmTime) { $this->intLmTime = $strLmTime; } /** * @return string */ public function getStrLockId() { return $this->strLockId; } /** * @param string $strLockId * @return void */ public function setStrLockId($strLockId) { $this->strLockId = $strLockId; } /** * @return int */ public function getIntLockTime() { return $this->intLockTime; } /** * @param int $intLockTime * @return void */ public function setIntLockTime($intLockTime) { $this->intLockTime = $intLockTime; } /** * @return int */ public function getLongCreateDate() { return $this->longCreateDate; } /** * Returns the creation-date of the current record * * @param string $strSystemid * * @throws class_exception * @return class_date */ public function getObjCreateDate($strSystemid = "") { if($strSystemid != "") throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR); return new class_date($this->getLongCreateDate()); } /** * @param int $longCreateDate * @return void */ public function setLongCreateDate($longCreateDate) { $this->longCreateDate = $longCreateDate; } /** * @return string */ public function getStrOwner() { return $this->strOwner; } /** * @param string $strOwner * @return void */ public function setStrOwner($strOwner) { $this->strOwner = $strOwner; } /** * Gets the id of the user currently being the owner of the record * * @param string $strSystemid * * @throws class_exception * @return string */ public final function getOwnerId($strSystemid = "") { if($strSystemid != "") throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR); return $this->getStrOwner(); } /** * Sets the id of the user who owns this record. * Please note that since 4.4, setting an owner-id no longer fires an updateObjectToDb()! * * @param string $strOwner * @param string $strSystemid * @deprecated * * @throws class_exception * @return bool */ public final function setOwnerId($strOwner, $strSystemid = "") { if($strSystemid != "") throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR); $this->setStrOwner($strOwner); return true; } /** * @return int */ public function getIntRecordStatus() { return $this->intRecordStatus; } /** * @return int */ public function getIntRecordDeleted() { return $this->intRecordDeleted; } /** * Gets the status of a systemRecord * * @param string $strSystemid * * @throws class_exception * @return int * @deprecated use class_root::getIntRecordStatus() instead * @see class_root::getIntRecordStatus() */ public function getStatus($strSystemid = "") { if($strSystemid != "") throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR); return $this->getIntRecordStatus(); } /** * Sets the internal status. Fires a status-changed event. * * @param int $intRecordStatus */ public function setIntRecordStatus($intRecordStatus) { $this->intRecordStatus = $intRecordStatus; } /** * Gets comment saved with the record * * @param string $strSystemid * * @throws class_exception * @return string */ public function getRecordComment($strSystemid = "") { if($strSystemid != "") throw new class_exception("unsupported param @ ".__METHOD__, class_exception::$level_FATALERROR); return $this->getStrRecordComment(); } /** * @return string */ public function getStrRecordComment() { return $this->strRecordComment; } /** * @param string $strRecordComment * @return void */ public function setStrRecordComment($strRecordComment) { if(uniStrlen($strRecordComment) > 254) $strRecordComment = uniStrTrim($strRecordComment, 250); $this->strRecordComment = $strRecordComment; } /** * @param string $strRecordClass * @return void */ public function setStrRecordClass($strRecordClass) { $this->strRecordClass = $strRecordClass; } /** * @return string * @return void */ public function getStrRecordClass() { return $this->strRecordClass; } /** * Writes a value to the params-array * * @param string $strKey * @param mixed $mixedValue Value * @return void */ public function setParam($strKey, $mixedValue) { class_carrier::getInstance()->setParam($strKey, $mixedValue); } /** * Returns a value from the params-Array * * @param string $strKey * @return string else "" */ public function getParam($strKey) { return class_carrier::getInstance()->getParam($strKey); } /** * Returns the complete Params-Array * * @return mixed */ public final function getAllParams() { return class_carrier::getAllParams(); } /** * returns the action used for the current request * * @return string */ public final function getAction() { return (string)$this->strAction; } /** * Returns an instance of the lockmanager, initialized * with the current systemid. * * @return class_lockmanager */ public function getLockManager() { return new class_lockmanager($this->getSystemid(), $this); } /** * Writes a key-value-pair to the arrModule * * @param string $strKey * @param mixed $strValue * @return void */ public function setArrModuleEntry($strKey, $strValue) { $this->arrModule[$strKey] = $strValue; } /** * Use this method to set an array of values, e.g. fetched by your own init-method. * If given, the root-class uses this array to set the internal fields instead of * triggering another query to the database. * On high-performance systems or large object-nets, this could reduce the amount of database-queries * fired drastically. * For best performance, include the matching row of the tables system, system_date and system_rights * * @param array $arrInitRow * @return void */ public function setArrInitRow($arrInitRow) { if(isset($arrInitRow["system_id"])) { $this->arrInitRow = $arrInitRow; } } /** * Returns the set of internal values marked as init-values * @return null|array */ public function getArrInitRow() { return $this->arrInitRow; } /** * @param \class_date $objEndDate * @return void */ public function setObjEndDate($objEndDate = null) { if($objEndDate === 0) $objEndDate = null; if(!$objEndDate instanceof class_date && $objEndDate != "" && $objEndDate != null) $objEndDate = new class_date($objEndDate); $this->objEndDate = $objEndDate; $this->bitDatesChanges = true; } /** * @return class_date */ public function getObjEndDate() { return $this->objEndDate; } /** * @param \class_date $objSpecialDate * @return void */ public function setObjSpecialDate($objSpecialDate = null) { if($objSpecialDate === 0) $objSpecialDate = null; if(!$objSpecialDate instanceof class_date && $objSpecialDate != "" && $objSpecialDate != null) $objSpecialDate = new class_date($objSpecialDate); $this->objSpecialDate = $objSpecialDate; $this->bitDatesChanges = true; } /** * @return class_date */ public function getObjSpecialDate() { return $this->objSpecialDate; } /** * @param class_date $objStartDate * @return void */ public function setObjStartDate($objStartDate = null) { if($objStartDate === 0) $objStartDate = null; if(!$objStartDate instanceof class_date && $objStartDate != "" && $objStartDate != null) $objStartDate = new class_date($objStartDate); $this->bitDatesChanges = true; $this->objStartDate = $objStartDate; } /** * @return class_date */ public function getObjStartDate() { return $this->objStartDate; } }
jinshana/kajonacms
module_system/system/class_root.php
PHP
lgpl-2.1
70,858
<?php /** * @package copix * @subpackage taglib * @author Salleyron Julien * @copyright 2000-2006 CopixTeam * @link http://www.copix.org * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file */ /** * Génération de fenetre confirm * @package copix * @subpackage taglib */ class TemplateTagConfirm extends CopixTemplateTag { public function process ($pParams, $pContent=null){ $toReturn = ' '.$pContent.'<br /><br />'; $toReturn .= ' <a href="'.CopixUrl::get($pParams['yes']).'">'._i18n('copix:common.buttons.yes').'</a>'; $toReturn .= ' <a href="'.CopixUrl::get($pParams['no']).'">'._i18n('copix:common.buttons.no').'</a>'; _tag('mootools'); CopixHTMLHeader::addJsCode (" window.addEvent('domready', function () { var elem = new Element('div'); elem.setStyles({'z-index':99999,'background-color':'white','border':'1px solid black','width':'200px','height':'100px','top': window.getScrollTop().toInt()+window.getHeight ().toInt()/2-100+'px','left':window.getScrollLeft().toInt()+window.getWidth ().toInt()/2-100+'px','position':'absolute','text-align':'center'}); elem.setHTML ('$toReturn'); elem.injectInside(document.body); }); "); return null; } } ?>
Copix/Copix3
utils/copix/taglib/confirm.templatetag.php
PHP
lgpl-2.1
1,308
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.annotations.cascade.circle.identity; /** * No Documentation */ @javax.persistence.Entity public class C extends AbstractEntity { private static final long serialVersionUID = 1226955752L; /** * No documentation */ @javax.persistence.ManyToOne(cascade = { javax.persistence.CascadeType.MERGE, javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REFRESH} , optional = false) private A a; /** * No documentation */ @javax.persistence.ManyToOne(cascade = { javax.persistence.CascadeType.MERGE, javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REFRESH} ) private G g; /** * No documentation */ @javax.persistence.ManyToOne(cascade = { javax.persistence.CascadeType.MERGE, javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REFRESH} , optional = false) private B b; public A getA() { return a; } public void setA(A parameter) { this.a = parameter; } public G getG() { return g; } public void setG(G parameter) { this.g = parameter; } public B getB() { return b; } public void setB(B parameter) { this.b = parameter; } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/cascade/circle/identity/C.java
Java
lgpl-2.1
1,549
// --------------------------------------------------------------------------- // DeviceŠÖ˜AƒNƒ‰ƒX // Original : cisc // Modification : Yumitaro // --------------------------------------------------------------------------- #include <string.h> #include <new> #include "device.h" //////////////////////////////////////////////////////////////// // DeviceList //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // ƒRƒ“ƒXƒgƒ‰ƒNƒ^ //////////////////////////////////////////////////////////////// DeviceList::DeviceList( void ) : node(NULL) {} //////////////////////////////////////////////////////////////// // ƒfƒXƒgƒ‰ƒNƒ^ //////////////////////////////////////////////////////////////// DeviceList::~DeviceList( void ) { Cleanup(); } //////////////////////////////////////////////////////////////// // ƒm[ƒhŒŸõ //////////////////////////////////////////////////////////////// DeviceList::Node *DeviceList::FindNode( const ID id ) { for( Node *n = node; n; n = n->next ){ if( n->entry->GetID() == id ) return n; } return NULL; } //////////////////////////////////////////////////////////////// // ƒfƒoƒCƒXƒŠƒXƒg‘SÁ‹Ž //////////////////////////////////////////////////////////////// void DeviceList::Cleanup( void ) { Node *n = node; while( n ){ Node *nx = n->next; delete n; n = nx; } node = NULL; } //////////////////////////////////////////////////////////////// // ƒfƒoƒCƒX’ljÁ //////////////////////////////////////////////////////////////// bool DeviceList::Add( IDevice *t ) { ID id = t->GetID(); if( !id ) return false; Node *n = FindNode( id ); if( n ){ n->count++; return true; }else{ n = new Node; if( !n ) return false; n->entry = t; n->next = node; n->count = 1; node = n; return true; } } //////////////////////////////////////////////////////////////// // ƒfƒoƒCƒXíœ(ƒ|ƒCƒ“ƒ^) //////////////////////////////////////////////////////////////// bool DeviceList::Del( IDevice *t ) { return t->GetID() ? Del( t->GetID() ) : false; } //////////////////////////////////////////////////////////////// // ƒfƒoƒCƒXíœ(ID) //////////////////////////////////////////////////////////////// bool DeviceList::Del( const ID id ) { for( Node **r = &node; *r; r = &((*r)->next) ){ if( ((*r)->entry->GetID() == id) && ((*r)->count) ){ ((*r)->count)--; // if( (*r)->entry->GetID() == id ){ // Node* d = *r; // if( !--d->count ){ // *r = d->next; // delete d; // } return true; } } return false; } //////////////////////////////////////////////////////////////// // ƒfƒoƒCƒXŒŸõ //////////////////////////////////////////////////////////////// IDevice *DeviceList::Find( const ID id ) { Node *n = FindNode( id ); return n ? n->entry : NULL; }
meesokim/p6001v
src/device.cpp
C++
lgpl-2.1
2,818
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ch.unizh.ini.jaer.projects.eventbasedfeatures; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.JFrame; import net.sf.jaer.Description; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.graphics.ImageDisplay; /** This class develops an intensity map representation of the incoming AE events. A ring buffer * is maintained at each pixel to keep track of the history of the events at that position. * A score is calculated for each pixel position - +1 for every ON event that enters the ring buffer (hence, -1 * for every ON event that leaves) and -1 for every OFF event that enters the ring buffer (hence, -1 * for every OFF event that leaves) * * @author Varad */ @Description("Creates an intensity map representation of AE events") public class PixelBuffer extends EventFilter2D { public int RingBufferSize = getPrefs().getInt("PixelBuffer.RingBufferSize", 1); public boolean renderBufferMap = getPrefs().getBoolean("PixelBuffer.renderBufferMap", false); public boolean hasKernelImplementor = false; public boolean hasConvolutionFeatureScheme = false; public boolean hasBinaryFeatureDetector = false; KernelImplementor kernelimplement; ConvolutionFeatureScheme featurescheme; BinaryFeatureDetector bindetect; public float max ; public float min ; public float base; public int sizex; public int sizey; public int maplength; public float[] colorv; public int[] map; public RingBuffer[] rbarr; ImageDisplay disp; JFrame frame; public PixelBuffer (AEChip chip){ super(chip); this.chip = chip; final String sz = "Size"; setPropertyTooltip(sz, "RingBufferSize", "sets size of ring buffer"); sizex = chip.getSizeX(); sizey = chip.getSizeY(); disp = ImageDisplay.createOpenGLCanvas(); // makde a new ImageDisplay GLCanvas with default OpenGL capabilities frame = new JFrame("ImageFrame"); // make a JFrame to hold it frame.setPreferredSize(new Dimension(sizex, sizey)); // set the window size frame.getContentPane().add(disp, BorderLayout.CENTER); // add the GLCanvas to the center of the window frame.pack(); // otherwise it wont fill up the display initFilter(); resetFilter(); } synchronized public boolean isRenderBufferMapEnabled(){ return renderBufferMap; } synchronized public void setRenderBufferMapEnabled( boolean renderBufferMap ) { this.renderBufferMap = renderBufferMap; getPrefs().putBoolean("PixelBuffer.renderBufferMap", renderBufferMap); getSupport().firePropertyChange("renderBufferMap", this.renderBufferMap, renderBufferMap); resetFilter(); } synchronized public int getRingBufferSize (){ return RingBufferSize; } synchronized public void setRingBufferSize( int RingBufferSize){ this.RingBufferSize = RingBufferSize; getPrefs().putInt("PixelBuffer.RingBufferSize", RingBufferSize); getSupport().firePropertyChange("RingBufferSize", this.RingBufferSize, RingBufferSize); resetFilter(); } synchronized public void setKernelImplementor(KernelImplementor kernelimplement){ this.hasKernelImplementor = true; this.kernelimplement = kernelimplement; } synchronized public void setConvolutionFeatureScheme(ConvolutionFeatureScheme featurescheme){ this.hasConvolutionFeatureScheme = true; this.featurescheme = featurescheme; } synchronized public void setBinaryFeatureDetector(BinaryFeatureDetector bindetect){ this.hasBinaryFeatureDetector = true; this.bindetect = bindetect; } synchronized private void checkMaps (){ if ( rbarr == null || rbarr.length != (chip.getSizeX()*chip.getSizeY()) ) resetRingBuffers(); } synchronized private void resetRingBuffers(){ max = 1; min = 0; maplength = sizex*sizey; base = ((max+min)/2); int size = 128; disp.setImageSize(size, size); // set dimensions of image disp.resetFrame(base); frame.setVisible(true); // make the frame visible map = new int[maplength]; rbarr = new RingBuffer[maplength]; colorv = new float[maplength]; for (int a = 0; a < maplength; a++){ rbarr[a] = new RingBuffer( getRingBufferSize() ); } } public class RingBuffer{ public final int length; // buffer length public int[] buffer; // an array of fixed length public int leadPointer, trailPointer ; public boolean fullflag; public RingBuffer(int cap){ length = cap; resetBuffer(); } public void resetBuffer(){ buffer = new int[length]; this.leadPointer = 0; this.fullflag = false; } public int incrIndex(int i){ i++; if(i>=length)i=0; return i; } public void insert( PolarityEvent e){ buffer[leadPointer] = e.getType(); leadPointer = incrIndex(leadPointer); if(leadPointer == 0) this.fullflag = true; } public int getOldest(){ return buffer[leadPointer]; } } @Override synchronized public EventPacket filterPacket(EventPacket in) { sizex = chip.getSizeX(); sizey = chip.getSizeY(); if ( in == null ){ return null; } if ( enclosedFilter != null ){ in = enclosedFilter.filterPacket(in); } checkMaps(); if(hasKernelImplementor) kernelimplement.kernel.checkMaps(); if(hasConvolutionFeatureScheme) featurescheme.detector.checkMaps(); if(hasBinaryFeatureDetector){ bindetect.kernel.checkMaps(); bindetect.binaryMethod.checkMaps(); } for ( Object ein:in ){ PolarityEvent e = (PolarityEvent)ein; int type = e.getType(); int x = e.getX(); int y = e.getY(); int index = getIndex(x, y); if( !rbarr[index].fullflag){ //partially or unfilled buffer if( type == 1){ //ON event map[index] += 1; if(hasKernelImplementor && kernelimplement.kernel!= null) kernelimplement.kernel.updateMap(x, y, 1); if(hasConvolutionFeatureScheme && featurescheme.kernel!= null) featurescheme.detector.getFeatures(x, y, 1, featurescheme.RelativeThreshold, e); if(hasBinaryFeatureDetector && bindetect.kernel!=null){ bindetect.kernel.updateMap(x, y, 1); bindetect.binaryMethod.getFeatures(x, y); } } else{ //OFF event map[index] -= 1; if(hasKernelImplementor && kernelimplement.kernel!= null) kernelimplement.kernel.updateMap(x, y, -1); if(hasConvolutionFeatureScheme && featurescheme.kernel!= null) featurescheme.detector.getFeatures(x, y, -1, featurescheme.RelativeThreshold, e); if(hasBinaryFeatureDetector && bindetect.kernel!=null){ bindetect.kernel.updateMap(x, y, -1); bindetect.binaryMethod.getFeatures(x, y); } } checkMax(index); checkMin(index); } else{ //filled to the capacity at least once if ( type == rbarr[index].getOldest() ){ //if incoming event is same ; //as one being pushed out ; } else{ if( type == 1 ){ //ON event map[index] += 2; if(hasKernelImplementor && kernelimplement.kernel!= null) kernelimplement.kernel.updateMap(x, y, 2); if(hasConvolutionFeatureScheme && featurescheme.kernel!= null){ featurescheme.detector.getFeatures(x, y, 2, featurescheme.RelativeThreshold, e); } if(hasBinaryFeatureDetector && bindetect.kernel!=null){ bindetect.kernel.updateMap(x, y, 2); bindetect.binaryMethod.getFeatures(x, y); } } else{ //OFF event map[index] -= 2; if(hasKernelImplementor && kernelimplement.kernel!= null) kernelimplement.kernel.updateMap(x, y, -2); if(hasConvolutionFeatureScheme && featurescheme.kernel!= null) featurescheme.detector.getFeatures(x, y, -2, featurescheme.RelativeThreshold, e); if(hasBinaryFeatureDetector && bindetect.kernel!=null){ bindetect.kernel.updateMap(x, y, -2); bindetect.binaryMethod.getFeatures(x, y); } } checkMax(index); checkMin(index); } } if(isRenderBufferMapEnabled()){ colorv[index] = (float)((map[index] - min)/(max - min)); disp.checkPixmapAllocation(); // make sure we have a pixmaps (not resally necessary since setting size will allocate pixmap disp.setPixmapRGB(x, y, colorv[index], colorv[index], colorv[index]); } rbarr[index].insert(e); } if(hasKernelImplementor){ kernelimplement.kernel.display.setPixmapArray(kernelimplement.kernel.grayvalue); kernelimplement.kernel.display.repaint(); // kernelimplement.kernel.updateFeatures(kernelimplement.kernel.keypoints, kernelimplement.RelativeThreshold); } if(hasConvolutionFeatureScheme){ featurescheme.detector.display.setPixmapArray(featurescheme.detector.grayvalue); featurescheme.detector.display.repaint(); // featurescheme.kernel.updateFeatures(featurescheme.kernel.keypoints, featurescheme.RelativeThreshold); } // if(hasBinaryFeatureDetector){ // bindetect.kernel.display.setPixmapArray(bindetect.kernel.grayvalue); // bindetect.kernel.display.repaint(); //// bindetect.binaryMethod.updateFeatures(bindetect.binaryMethod.keypoints); // // } disp.repaint(); return in; } public void checkMax(int index){ if ( map[index] > max ){ max = map[index]; } } public void checkMin(int index){ if ( map[index] < min ){ min = map[index]; } } public int getIndex(int x, int y){ int index = (x + (y*sizex)); return index; } @Override public void resetFilter() { if(!isFilterEnabled()) return; resetRingBuffers(); } @Override public void initFilter() { resetFilter(); } } //public class RingBuffer extends AbstractList<PolarityEvent> implements RandomAccess { //or extends Object // // private final int n; // buffer length // private final List<PolarityEvent> buf; // a List implementing RandomAccess // private int leader = 0; // private int size = 0; // // // // // public RingBuffer(int capacity) { //constructor for the ring buffer with size as argument // n = capacity + 1; // buf = new ArrayList<PolarityEvent>(Collections.nCopies(n, (PolarityEvent) null)); // } // // private int wrapIndex(int i) { //implementing circularity // int m = i % n; // if (m < 0) { // m += n; // } // return m; // } // // @Override // public int size() { // return this.size; // } // // @Override // public PolarityEvent get(int i) { //PolarityEvent is a defined return type // //this code returns the buffer member at the requested index // if (i < 0 || i >= n-1) throw new IndexOutOfBoundsException(); // // if(i > size()) throw new NullPointerException("Index is greater than size."); // // return buf.get(wrapIndex(leader + i)); // } // // @Override // public PolarityEvent set(int i, PolarityEvent e) { //this code sets the buffer member at the requested index // if (i < 0 || i >= n-1) { // throw new IndexOutOfBoundsException(); // } // if(i == size()) // assume leader's position as invalid (should use insert(e)) // throw new IndexOutOfBoundsException("The size of the list is " + size() + " while the index was " + i // +""); // return buf.set(wrapIndex(leader - size + i), e); // } // // public void insert(PolarityEvent e) //adds a new element // { // int s = size(); // buf.set(wrapIndex(leader), e); // leader = wrapIndex(++leader); // buf.set(leader, null); // if(s == n-1){ // fullflag[e.x][e.y] = true; // return; // we have replaced the eldest element. // } // // this.size++; // // } // // public PolarityEvent getOldest(){ //returns oldest member i.e. index 99 of the buffer // int i = wrapIndex(leader+1); // PolarityEvent a = null; // // for(;;i = wrapIndex(++i)) { // if(buf.get(i) != null) break; // if(i == leader) //break; // throw new IllegalStateException("Cannot remove element." // + " CircularArrayList is empty."); // } //// if( i!= leader ) //// a = buf.get(i); // return buf.get(i); // } // } ///* // * To change this template, choose Tools | Templates // * and open the template in the editor. // */ //package ch.unizh.ini.jaer.projects.eventbasedfeatures; // // ///** // * // * @author Varad // */ //public class PixelTimeBuffer extends EventFilter2D{ // // public int RingBufferSize = getPrefs().getInt("PixelTimeBuffer.RingBufferSize", 1); // public int dt = getPrefs().getInt("PixelTimeBuffer.dt", 500); // // public int sizex; // public int sizey; // // public float max ; // public float min ; // // public float[][] map; // public RingBuffer[][] rbarr; // // public float[][] colorv; // // ImageDisplay disp; // JFrame frame; // // public PixelTimeBuffer (AEChip chip){ // // super(chip); // this.chip = chip; // // final String sz = "Size", tim = "Timing"; // // setPropertyTooltip(sz, "RingBufferSize", "sets size of ring buffer"); // setPropertyTooltip(tim, "dt", "Events with less than this delta time in us to neighbors pass through"); // // sizex = chip.getSizeX(); // sizey = chip.getSizeY(); // // disp = ImageDisplay.createOpenGLCanvas(); // makde a new ImageDisplay GLCanvas with default OpenGL capabilities // frame = new JFrame("ImageFrame"); // make a JFrame to hold it // frame.setPreferredSize(new Dimension(sizex, sizey)); // set the window size // frame.getContentPane().add(disp, BorderLayout.CENTER); // add the GLCanvas to the center of the window // frame.pack(); // otherwise it wont fill up the display // } // // synchronized public int getRingBufferSize (){ // return RingBufferSize; // } // // synchronized public void setRingBufferSize( int RingBufferSize){ // this.RingBufferSize = RingBufferSize; // getPrefs().putInt("PixelTimeBuffer.RingBufferSize", RingBufferSize); // getSupport().firePropertyChange("RingBufferSize", this.RingBufferSize, RingBufferSize); // resetFilter(); // } // // public int getDt() { // return this.dt; // } // // public void setDt(final int dt) { // this.dt = dt; // getPrefs().putInt("PixelTimeBuffer.dt", dt); // getSupport().firePropertyChange("dt", this.dt, dt); // resetFilter(); // } // // synchronized public void checkMaps (){ // if ( rbarr == null || rbarr.length != chip.getSizeX() || rbarr[0].length != chip.getSizeY() ) // resetRingBuffers(); // } // // public void resetRingBuffers(){ // // int size = 128; // disp.setImageSize(size, size); // set dimensions of image // frame.setVisible(true); // make the frame visible // // max = 1; // min = 0; // map = new float[sizex][sizey]; // rbarr = new RingBuffer[sizex][sizey]; // colorv = new float[sizex][sizey]; // // for (int a = 0; a < sizex; a++){ // for (int b = 0; b < sizey; b++){ // rbarr[a][b] = new RingBuffer( getRingBufferSize() ); // } // } // } // // public class RingBuffer{ // // public int length ; // public PolarityEvent[] buffer; // an array of fixed length // public int leadPointer, trailPointer ; // public boolean arrayEmpty; // public int typeOldest; // // public RingBuffer(int cap){ // length = cap; // resetBuffer(); // } // // public void resetBuffer(){ // buffer = new PolarityEvent[length]; // this.leadPointer = 0; // this.trailPointer = 0; // this.arrayEmpty = true; // this.typeOldest = 0; // } // // public int incrIndex(int i){ // // i++; // return(wrapIndex(i)); // } // // public int wrapIndex(int j){ // // if(j>=length)j=0; // return j; // } // // public void insert( PolarityEvent e){ // // buffer[leadPointer] = e; // leadPointer = incrIndex(leadPointer); // // if(this.arrayEmpty == true) // this.arrayEmpty = false; // // // // } // // public PolarityEvent getOldest(){ // // return buffer[this.trailPointer]; // } // // public void updateBuffer(PolarityEvent e){ // // int x = e.getX(); // int y = e.getY(); // //// if(buffer[this.trailPointer] != null){ // while( ((e.getTimestamp() - rbarr[x][y].getOldest().getTimestamp()) > dt) && (rbarr[x][y].leadPointer != rbarr[x][y].trailPointer)){ // // if( (rbarr[x][y].buffer[rbarr[x][y].trailPointer]).getType() == 1){ // map[x][y] -= 1; // } // else{ // map[x][y] += 1; // } // checkMax(e); // checkMin(e); // // removeEvent(); // } // // } // // public void removeEvent(){ // // buffer[this.trailPointer] = null; // this.trailPointer = incrIndex(this.trailPointer); // // if(this.leadPointer == this.trailPointer) // this.arrayEmpty = true; // } // // // } // @Override // public EventPacket<?> filterPacket(EventPacket<?> in) { // // sizex = chip.getSizeX(); // sizey = chip.getSizeY(); // // if ( in == null ){ // return null; // } // // if ( enclosedFilter != null ){ // in = enclosedFilter.filterPacket(in); // } // // checkMaps(); // // for ( Object ein:in ){ // // PolarityEvent e = (PolarityEvent)ein; // int type = e.getType(); // int x = e.getX(); // int y = e.getY(); // // if(rbarr[x][y].arrayEmpty == true){ // // if( type == 1 ){ //ON event // map[x][y] += 1; // } // else{ // map[x][y] -= 1; // } // checkMax(e); // checkMin(e); // // } // // else{ // //// if(rbarr[x][y].leadPointer == 0){ // // if((rbarr[x][y].leadPointer == rbarr[x][y].trailPointer) && rbarr[x][y].arrayEmpty == false){ // //// System.out.print(2+"\n"); // // rbarr[x][y].typeOldest = rbarr[x][y].getOldest().getType(); // rbarr[x][y].trailPointer = rbarr[x][y].incrIndex(rbarr[x][y].trailPointer); //// rbarr[x][y].removeEvent(); // // rbarr[x][y].updateBuffer(e); // // if(rbarr[x][y].arrayEmpty == true){ // // if( type == 1 ){ //ON event // map[x][y] += 1; // } // else{ // map[x][y] -= 1; // } // checkMax(e); // checkMin(e); // } // // else{ // // if(rbarr[x][y].trailPointer == rbarr[x][y].wrapIndex(rbarr[x][y].leadPointer + 1)){ // //// System.out.print(2+"\n"); // // if ( type == rbarr[x][y].typeOldest ) { //if incoming event is same // ; //// System.out.print(3+"\n"); // } // else{ // if( type == 1 ){ //ON event // map[x][y] += 2; // // } // else{ //OFF event // map[x][y] -= 2; // } // checkMax(e); // checkMin(e); // } // //// rbarr[x][y].removeEvent(); // // } // // else{ // if( type == 1 ){ //ON event // map[x][y] += 1; // } // else{ // map[x][y] -= 1; // } // // checkMax(e); // checkMin(e); // } // } // // } // // else{ // if( type == 1 ){ //ON event // map[x][y] += 1; // } // else{ // map[x][y] -= 1; // } // checkMax(e); // checkMin(e); // } // } // // colorv[x][y] = (float)((map[x][y] - min)/(max - min)); // disp.checkPixmapAllocation(); // make sure we have a pixmaps (not really necessary since setting size will allocate pixmap // disp.setPixmapRGB(x, y, colorv[x][y], colorv[x][y], colorv[x][y]); // rbarr[x][y].insert(e); // } // // disp.repaint(); // return in; // } // // // // synchronized public void checkMax(PolarityEvent e){ // // int x = e.getX(); // int y = e.getY(); // if ( map[x][y] > max ){ // max = map[x][y]; // // } // } // // synchronized public void checkMin(PolarityEvent e){ // // int x = e.getX(); // int y = e.getY(); // if ( map[x][y] < min ){ // min = map[x][y]; // // } // } // // // @Override // public void resetFilter() { // // if(!isFilterEnabled()) // return; // // disp.clearImage(); // resetRingBuffers(); // } // // @Override // public void initFilter() { // resetFilter(); // } // // //}
viktorbahr/jaer
src/ch/unizh/ini/jaer/projects/eventbasedfeatures/PixelBuffer.java
Java
lgpl-2.1
27,642
package iax.protocol.user.command; import iax.protocol.peer.Peer; /** * Facade to user commands. */ public class UserCommandFacade { /** * Method that indicates that user has answered an incoming call. * @param peer Current peer. * @param callingNumber the calling number of the call that is going to be accepted */ public static void answerCall(Peer peer, String callingNumber) { (new AnswerCall(peer, callingNumber)).execute(); } /** * Method to hang up a call. * @param peer Current peer. * @param calledNumber The number of the hung call. */ public static void hangupCall(Peer peer, String calledNumber) { (new HangupCall(peer, calledNumber)).execute(); } /** * Method to hold a call. * @param peer Current peer. * @param calledNumber The number of the muted call. */ public static void holdCall(Peer peer, String calledNumber) { (new HoldCall(peer, calledNumber)).execute(); } /** * Method to start a new call. * @param peer Current peer. * @param calledNumber Number to call to. */ public static void newCall(Peer peer, String calledNumber) { (new NewCall(peer, calledNumber)).execute(); } /** * Exit from the system * @param peer Current peer. */ public static void exit(Peer peer) { (new Exit(peer)).execute(); } /** * Method to mute a call. * @param peer Current peer. * @param calledNumber The number of the muted call. */ public static void muteCall(Peer peer, String calledNumber) { (new MuteCall(peer, calledNumber)).execute(); } /** * Method to unhold a call. * @param peer Current peer. * @param calledNumber The number of the muted call. */ public static void unHoldCall(Peer peer, String calledNumber) { (new UnHoldCall(peer, calledNumber)).execute(); } /** * Method to unmute a call. * @param peer Current peer. * @param calledNumber The number of the muted call. */ public static void unMuteCall(Peer peer, String calledNumber) { (new UnMuteCall(peer, calledNumber)).execute(); } /** * Method to send a DTMF tone. * @param peer Current peer. * @param calledNumber The number of the muted call. */ public static void sendDTMF(Peer peer, String calledNumber, char tone) { (new SendDTMF(peer, calledNumber, tone)).execute(); } /** * Method to transfer a call. * @param peer Current peer. * @param srcNumber the source number of the transfer * @param dstNumber the destination number of the transfer */ public static void transferCall(Peer peer, String srcNumber, String dstNumber) { (new TransferCall(peer, srcNumber, dstNumber)).execute(); } }
jonmersha/njiax
src/iax/protocol/user/command/UserCommandFacade.java
Java
lgpl-2.1
2,903
/****************************************************************************** jXEventUtil.cpp Useful functions for dealing with X events. Copyright © 1996 John Lindal. All rights reserved. ******************************************************************************/ #include <JXStdInc.h> #include <jXEventUtil.h> #include <JXDisplay.h> #include <JString.h> #include <jAssert.h> /****************************************************************************** JXIsPrint Returns kJTrue if the keysym is between 1 and 255 and isprint() returns kJTrue. ******************************************************************************/ JBoolean JXIsPrint ( const int keysym ) { return JConvertToBoolean( 0 < keysym && keysym <= 255 && JIsPrint(keysym) ); } /****************************************************************************** JXGetEventTime Return the time stamp of the event. Returns kJFalse if the given event doesn't contain a time stamp. Selection events contain a time field, but this is a timestamp generated by clients, not the current server time. ******************************************************************************/ JBoolean JXGetEventTime ( const XEvent& xEvent, Time* time ) { *time = 0; if (xEvent.type == KeyPress || xEvent.type == KeyRelease) { *time = xEvent.xkey.time; return kJTrue; } else if (xEvent.type == ButtonPress || xEvent.type == ButtonRelease) { *time = xEvent.xbutton.time; return kJTrue; } else if (xEvent.type == MotionNotify) { *time = xEvent.xmotion.time; return kJTrue; } else if (xEvent.type == EnterNotify || xEvent.type == LeaveNotify) { *time = xEvent.xcrossing.time; return kJTrue; } else if (xEvent.type == PropertyNotify) { *time = xEvent.xproperty.time; return kJTrue; } else { return kJFalse; // event doesn't contain the information } } /****************************************************************************** JXGetButtonAndModifierStates Return the button and key modifiers states of the event. Returns kJFalse if the given event doesn't contain the information. ******************************************************************************/ JBoolean JXGetButtonAndModifierStates ( const XEvent& xEvent, JXDisplay* display, unsigned int* state ) { *state = 0; if (xEvent.type == KeyPress) { *state = xEvent.xkey.state; JIndex modifierIndex; if (display->KeycodeToModifier(xEvent.xkey.keycode, &modifierIndex)) { *state = JXKeyModifiers::SetState(display, *state, modifierIndex, kJTrue); } return kJTrue; } else if (xEvent.type == KeyRelease) { *state = xEvent.xkey.state; JIndex modifierIndex; if (display->KeycodeToModifier(xEvent.xkey.keycode, &modifierIndex)) { *state = JXKeyModifiers::SetState(display, *state, modifierIndex, kJFalse); } return kJTrue; } else if (xEvent.type == ButtonPress) { const JXMouseButton currButton = (JXMouseButton) xEvent.xbutton.button; *state = JXButtonStates::SetState(xEvent.xbutton.state, currButton, kJTrue); return kJTrue; } else if (xEvent.type == ButtonRelease) { const JXMouseButton currButton = (JXMouseButton) xEvent.xbutton.button; *state = JXButtonStates::SetState(xEvent.xbutton.state, currButton, kJFalse); return kJTrue; } else if (xEvent.type == MotionNotify) { *state = xEvent.xmotion.state; return kJTrue; } else if (xEvent.type == EnterNotify || xEvent.type == LeaveNotify) { *state = xEvent.xcrossing.state; return kJTrue; } else { return kJFalse; // event doesn't contain the information } }
mbert/mulberry-lib-jx
libjx/code/jXEventUtil.cpp
C++
lgpl-2.1
3,644
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2022, by David Gilbert and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------- * XYSeriesLabelGenerator.java * --------------------------- * (C) Copyright 2004-2022, by David Gilbert. * * Original Author: David Gilbert; * Contributor(s): -; * */ package org.jfree.chart.labels; import org.jfree.data.xy.XYDataset; /** * A generator that creates labels for the series in an {@link XYDataset}. * <P> * Classes that implement this interface should be either (a) immutable, or * (b) cloneable via the {@code PublicCloneable} interface (defined in * the JCommon class library). This provides a mechanism for the referring * renderer to clone the generator if necessary. */ public interface XYSeriesLabelGenerator { /** * Generates a label for the specified series. This label will be * used for the chart legend. * * @param dataset the dataset ({@code null} not permitted). * @param series the series. * * @return A series label. */ String generateLabel(XYDataset dataset, int series); }
jfree/jfreechart
src/main/java/org/jfree/chart/labels/XYSeriesLabelGenerator.java
Java
lgpl-2.1
2,286
<?php namespace wcf\system\template\plugin; use wcf\system\exception\SystemException; use wcf\system\request\LinkHandler; use wcf\system\template\TemplateEngine; use wcf\system\WCF; use wcf\util\StringUtil; /** * Template function plugin which generates sliding pagers. * * Usage: * {pages pages=10 link='page-%d.html'} * {pages page=8 pages=10 link='page-%d.html'} * * assign to variable 'output'; do not print: * {pages page=8 pages=10 link='page-%d.html' assign='output'} * * assign to variable 'output' and do print also: * {pages page=8 pages=10 link='page-%d.html' assign='output' print=true} * * @author Marcel Werk * @copyright 2001-2014 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package com.woltlab.wcf * @subpackage system.template.plugin * @category Community Framework */ class PagesFunctionTemplatePlugin implements IFunctionTemplatePlugin { const SHOW_LINKS = 11; /** * Inserts the page number into the link. * * @param string $link * @param integer $pageNo * @return string final link */ protected static function insertPageNumber($link, $pageNo) { $startPos = mb_strpos($link, '%d'); if ($startPos !== null) $link = mb_substr($link, 0, $startPos) . $pageNo . mb_substr($link, $startPos + 2); return $link; } /** * Generates HTML code for a link. * * @param string $link * @param integer $pageNo * @param integer $activePage * @param integer $pages * @return string */ protected function makeLink($link, $pageNo, $activePage, $pages) { // first page if ($activePage != $pageNo) { return '<li class="button"><a href="'.$this->insertPageNumber($link, $pageNo).'" title="'.WCF::getLanguage()->getDynamicVariable('wcf.page.pageNo', array('pageNo' => $pageNo)).'">'.StringUtil::formatInteger($pageNo).'</a></li>'."\n"; } else { return '<li class="button active"><span>'.StringUtil::formatInteger($pageNo).'</span><span class="invisible">'.WCF::getLanguage()->getDynamicVariable('wcf.page.pagePosition', array('pageNo' => $pageNo, 'pages' => $pages)).'</span></li>'."\n"; } } /** * Generates HTML code for 'previous' link. * * @param type $link * @param type $pageNo * @return string */ protected function makePreviousLink($link, $pageNo) { if ($pageNo > 1) { return '<li class="button skip"><a href="'.$this->insertPageNumber($link, $pageNo - 1).'" title="'.WCF::getLanguage()->getDynamicVariable('wcf.global.page.previous').'" class="jsTooltip"><span class="icon icon16 icon-double-angle-left"></span></a></li>'."\n"; } else { return '<li class="skip disabled"><span class="icon icon16 icon-double-angle-left disabled"></span></li>'."\n"; } } /** * Generates HTML code for 'next' link. * * @param type $link * @param type $pageNo * @return string */ protected function makeNextLink($link, $pageNo, $pages) { if ($pageNo && $pageNo < $pages) { return '<li class="button skip"><a href="'.$this->insertPageNumber($link, $pageNo + 1).'" title="'.WCF::getLanguage()->getDynamicVariable('wcf.global.page.next').'" class="jsTooltip"><span class="icon icon16 icon-double-angle-right"></span></a></li>'."\n"; } else { return '<li class="skip disabled"><span class="icon icon16 icon-double-angle-right disabled"></span></li>'."\n"; } } /** * @see \wcf\system\template\IFunctionTemplatePlugin::execute() */ public function execute($tagArgs, TemplateEngine $tplObj) { // needed params: controller, link, page, pages if (!isset($tagArgs['link'])) throw new SystemException("missing 'link' argument in pages tag"); if (!isset($tagArgs['controller'])) throw new SystemException("missing 'controller' argument in pages tag"); if (!isset($tagArgs['pages'])) { if (($tagArgs['pages'] = $tplObj->get('pages')) === null) { throw new SystemException("missing 'pages' argument in pages tag"); } } $html = ''; if ($tagArgs['pages'] > 1) { // create and encode route link $parameters = array(); if (isset($tagArgs['id'])) $parameters['id'] = $tagArgs['id']; if (isset($tagArgs['title'])) $parameters['title'] = $tagArgs['title']; if (isset($tagArgs['object'])) $parameters['object'] = $tagArgs['object']; if (isset($tagArgs['application'])) $parameters['application'] = $tagArgs['application']; $link = StringUtil::encodeHTML(LinkHandler::getInstance()->getLink($tagArgs['controller'], $parameters, $tagArgs['link'])); if (!isset($tagArgs['page'])) { if (($tagArgs['page'] = $tplObj->get('pageNo')) === null) { $tagArgs['page'] = 0; } } // open div and ul $html .= "<nav class=\"pageNavigation\" data-link=\"".$link."\" data-pages=\"".$tagArgs['pages']."\">\n<ul>\n"; // previous page $html .= $this->makePreviousLink($link, $tagArgs['page']); // first page $html .= $this->makeLink($link, 1, $tagArgs['page'], $tagArgs['pages']); // calculate page links $maxLinks = static::SHOW_LINKS - 4; $linksBeforePage = $tagArgs['page'] - 2; if ($linksBeforePage < 0) $linksBeforePage = 0; $linksAfterPage = $tagArgs['pages'] - ($tagArgs['page'] + 1); if ($linksAfterPage < 0) $linksAfterPage = 0; if ($tagArgs['page'] > 1 && $tagArgs['page'] < $tagArgs['pages']) { $maxLinks--; } $half = $maxLinks / 2; $left = $right = $tagArgs['page']; if ($left < 1) $left = 1; if ($right < 1) $right = 1; if ($right > $tagArgs['pages'] - 1) $right = $tagArgs['pages'] - 1; if ($linksBeforePage >= $half) { $left -= $half; } else { $left -= $linksBeforePage; $right += $half - $linksBeforePage; } if ($linksAfterPage >= $half) { $right += $half; } else { $right += $linksAfterPage; $left -= $half - $linksAfterPage; } $right = intval(ceil($right)); $left = intval(ceil($left)); if ($left < 1) $left = 1; if ($right > $tagArgs['pages']) $right = $tagArgs['pages']; // left ... links if ($left > 1) { if ($left - 1 < 2) { $html .= $this->makeLink($link, 2, $tagArgs['page'], $tagArgs['pages']); } else { $html .= '<li class="button jumpTo"><a title="'.WCF::getLanguage()->getDynamicVariable('wcf.global.page.jumpTo').'" class="jsTooltip">'.StringUtil::HELLIP.'</a></li>'."\n"; } } // visible links for ($i = $left + 1; $i < $right; $i++) { $html .= $this->makeLink($link, $i, $tagArgs['page'], $tagArgs['pages']); } // right ... links if ($right < $tagArgs['pages']) { if ($tagArgs['pages'] - $right < 2) { $html .= $this->makeLink($link, $tagArgs['pages'] - 1, $tagArgs['page'], $tagArgs['pages']); } else { $html .= '<li class="button jumpTo"><a title="'.WCF::getLanguage()->getDynamicVariable('wcf.global.page.jumpTo').'" class="jsTooltip">'.StringUtil::HELLIP.'</a></li>'."\n"; } } // last page $html .= $this->makeLink($link, $tagArgs['pages'], $tagArgs['page'], $tagArgs['pages']); // next page $html .= $this->makeNextLink($link, $tagArgs['page'], $tagArgs['pages']); // close div and ul $html .= "</ul></nav>\n"; } // assign html output to template var if (isset($tagArgs['assign'])) { $tplObj->assign($tagArgs['assign'], $html); if (!isset($tagArgs['print']) || !$tagArgs['print']) return ''; } return $html; } }
PhrozenByte/WCF2
wcfsetup/install/files/lib/system/template/plugin/PagesFunctionTemplatePlugin.class.php
PHP
lgpl-2.1
7,411
/* * Copyright (C) 2004 The Concord Consortium, Inc., * 10 Concord Crossing, Concord, MA 01742 * * Web Site: http://www.concord.org * Email: info@concord.org * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * END LICENSE */ package org.concord.framework.otrunk; import java.util.Vector; public interface OTControllerService { /** * This method is typically not used. Typically controller classes are * registered in a OTPackage implementation. * * If a controller class is only registered using this method then it will need to be * registered each time a new view wants to use it. If it is registered in the OTPackage * then new views don't need to worry about registering it. * * This method takes a controllerClass. * Controller classes take OTObjects and create * real objects from them. * */ public void registerControllerClass(Class<? extends OTController> viewClass); /** * This is a helper method. The real object class of a controller class should * be in a public final static Class [] realObjectClasses * field of the interface. This method just looks up that field and returns * the value. * * @param controllerClass * @return */ public Class<?> [] getRealObjectClasses(Class<? extends OTController> controllerClass); /** * This searches an internal table of realObjects to * see if an OTObject has been created for this object. * It returns it if it has. * * If the OTObject has not been created then the * registered OTController classes are searched to see if there * is one that can work with this realObject class. * The OTController class needs to define a * public final static Class [] realObjectClasses * field. If it matches, that controller is used to make the * OTObject. * * The {@link OTController} registerRealObject is called. * followed by saveRealObject. * * In the OTController object the saveRealObject method can and should * call getOTObject when it needs to save a reference to another * realObject. * * Note: getOTObject will only call saveRealObject if this is the first time the * realObject is seen by this service. * * Note to implementors: a weak map should be used so that if all the * references to the real object are gone then the real object * can be garbage collected. If the real object is needed again for * some reason then it will just be created again. * * @param realObject * @return */ public OTObject getOTObject(Object realObject); /** * Look to see if this realObject has been created already or added with * getOTObject. If so return that previous realObject. * * Otherwise, use the controller registered for the class of this otObject * to create the realObject, and load the * state from the otObject into the realObject. * * The implementation should use a weak map so that if all the * references to the real object are gone then the real object * can be garbage collected. If the real object is needed again for * some reason then it will just be created again. * * If the controller service is in the middle of disposing then this will * return null for real objects that haven't already been created. * * @param otObject * @return */ public Object getRealObject(OTObject otObject); /** * Take a real object which was created else * where and connect it to an otObject and * load the state of otObject into the realObject * * @param realObject * @param otObject */ public Object getRealObject(OTObject otObject, Object realObject); /** * A helper method to get a Vector of real objects from an * OTObjectList, so that we don't have to first get the OTObjectList * and then create all the RealObjects ourselves. * * @param otObjectList * @return */ public Vector<Object> getRealObjects(OTObjectList otObjectList); /** * This saves the state of realObject into this ot object. It needs * to lookup the controller for this realObject and otObject. * * This is very similar to getOTObject, which calls saveRealObject * at the end. Exposing it here allows others to use this * functionality without having to directly access the controller * or otObject directly * * TODO it is not clear how much state should be saved here and whether it should * be recursive. If listeners are being used on all the sub objects then when * this is called after the object has been registered it doesn't need to be * recursive. If this is called to store a realObject that wasn't created by * the controllerservice this will need to recursively save all the sub objects. * * It should not mess up anything if the method is recursive. It is just a waste of * time in some cases. However there is a danger of infinite loops with circular * references. * * @param otObject * @param realObject */ public void saveRealObject(Object realObject, OTObject otObject); /** * This loads the state of this ot object into the realObject. It needs * to lookup the controller for this realObject and otObject. * * This is very similar to getRealObject but getRealObject only calls * loadRealObject on the controller when it's called the first time * * TODO it is not clear how much state should be loaded here and whether it should * be recursive. If listeners are being used on all the sub objects then when * this is called after the object has been registered it doesn't need to be * recursive. If this is called to load a realObject that wasn't created by * the controllerservice this will need to recursively load all the sub objects. * * It should not mess up anything if the method is recursive. It is just a waste of * time in some cases. However there is a danger of infinite loops with circular * references. * * @param otObject * @param realObject */ public void loadRealObject(OTObject otObject, Object realObject); /** * This saves the state of realObject into this ot object. It needs * to lookup the controller for this realObject and otObject. * * This method is called both by getOTObject and getRealObject. You should * only need to call it explicitly if you don't want the other side effects * of those methods. For example if the realObject needs to be managed by * some parent object instead of the standard controller for the realObject * * A possible alternative solution to this is to make a custom controller. * but that alternative hasn't been tried yet, so it might need more * framework support to be possible. */ public void registerRealObject(Object realObject, OTObject otObject); /** * Return the controller instance that has been or would be be used to create a * real object. You should not call any of the public methods of OTController * these methods should only be called by the controller service. * * @param otObject * @return */ public OTController getController(OTObject otObject); /** * Calling this will call dispose on all of the controllers this controller * service knows about. That will give them a chance to clean up any * listeners they've added. */ public void dispose(); /** * provide a service which other controllers can use. * this allows views which use controllers to provide custom services to those * controllers. * * @param serviceClass * @param service */ public void addService(Class<?> serviceClass, Object service); /** * Lookup a service that was provided to this controllerService * * @param serviceClass * @return */ public <T> T getService(Class<T> serviceClass); }
concord-consortium/framework
src/org/concord/framework/otrunk/OTControllerService.java
Java
lgpl-2.1
8,453
// The UpdateCheck plug-in // Copyright (C) 2004-2016 Maurits Rijk // // Renderer.cs // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // using System; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Xml; namespace Gimp.UpdateCheck { public class Renderer : BaseRenderer { static ManualResetEvent allDone= new ManualResetEvent(false); const int BUFFER_SIZE = 1024; const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout public Renderer(VariableSet variables) : base(variables) { } public void Render() { bool enableProxy = GetValue<bool>("enable_proxy"); string httpProxy = GetValue<string>("http_proxy"); string port = GetValue<string>("port"); if (enableProxy) { Gimp.RcSet("update-enable-proxy", (enableProxy) ? "true" : "false"); Gimp.RcSet("update-http-proxy", httpProxy); Gimp.RcSet("update-port", port); } var assembly = Assembly.GetAssembly(typeof(Plugin)); Console.WriteLine(assembly.GetName().Version); var doc = new XmlDocument(); try { var myRequest = (HttpWebRequest) WebRequest.Create("http://gimp-sharp.sourceforge.net/version.xml"); // Create a proxy object, needed for mono behind a firewall?! if (enableProxy) { var myProxy = new WebProxy() {Address = new Uri(httpProxy + ":" + port)}; myRequest.Proxy = myProxy; } var requestState = new RequestState(myRequest); // Start the asynchronous request. IAsyncResult result= (IAsyncResult) myRequest.BeginGetResponse (new AsyncCallback(RespCallback), requestState); // this line implements the timeout, if there is a timeout, // the callback fires and the request becomes aborted ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myRequest, DefaultTimeout, true); // The response came in the allowed time. The work processing will // happen in the callback function. allDone.WaitOne(); // Release the HttpWebResponse resource. requestState.Response.Close(); } catch (Exception e) { Console.WriteLine("Exception!"); Console.WriteLine(e.StackTrace); return; } } static void TimeoutCallback(object state, bool timedOut) { if (timedOut) { var request = state as HttpWebRequest; request?.Abort(); } } static void RespCallback(IAsyncResult asynchronousResult) { try { // State of request is asynchronous. var requestState = (RequestState) asynchronousResult.AsyncState; var myHttpWebRequest = requestState.Request; requestState.Response = (HttpWebResponse) myHttpWebRequest.EndGetResponse(asynchronousResult); // Read the response into a Stream object. var responseStream = requestState.Response.GetResponseStream(); requestState.StreamResponse = responseStream; var asynchronousInputRead = responseStream.BeginRead(requestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), requestState); return; } catch(WebException e) { Console.WriteLine("\nRespCallback Exception raised!"); Console.WriteLine("\nMessage:{0}",e.Message); Console.WriteLine("\nStatus:{0}",e.Status); } allDone.Set(); } static void ReadCallBack(IAsyncResult asyncResult) { try { var requestState = (RequestState) asyncResult.AsyncState; var responseStream = requestState.StreamResponse; int read = responseStream.EndRead(asyncResult); if (read > 0) { requestState.RequestData.Append (Encoding.ASCII.GetString(requestState.BufferRead, 0, read)); IAsyncResult asynchronousResult = responseStream.BeginRead(requestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), requestState); return; } else { if (requestState.RequestData.Length > 1) { string stringContent = requestState.RequestData.ToString(); Console.WriteLine(stringContent); } responseStream.Close(); } } catch (WebException e) { Console.WriteLine("\nReadCallBack Exception raised!"); Console.WriteLine("\nMessage:{0}",e.Message); Console.WriteLine("\nStatus:{0}",e.Status); } allDone.Set(); } } }
mrijk/gimp-sharp
plug-ins/UpdateCheck/Renderer.cs
C#
lgpl-2.1
5,050
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QXmlStreamReader> #include "fluidlauncher.h" #define DEFAULT_INPUT_TIMEOUT 10000 #define SIZING_FACTOR_HEIGHT 6/10 #define SIZING_FACTOR_WIDTH 6/10 FluidLauncher::FluidLauncher(QStringList* args) { pictureFlowWidget = new PictureFlow(); slideShowWidget = new SlideShow(); inputTimer = new QTimer(); addWidget(pictureFlowWidget); addWidget(slideShowWidget); setCurrentWidget(pictureFlowWidget); pictureFlowWidget->setFocus(); QRect screen_size = QApplication::desktop()->screenGeometry(); QObject::connect(pictureFlowWidget, SIGNAL(itemActivated(int)), this, SLOT(launchApplication(int))); QObject::connect(pictureFlowWidget, SIGNAL(inputReceived()), this, SLOT(resetInputTimeout())); QObject::connect(slideShowWidget, SIGNAL(inputReceived()), this, SLOT(switchToLauncher())); QObject::connect(inputTimer, SIGNAL(timeout()), this, SLOT(inputTimedout())); inputTimer->setSingleShot(true); inputTimer->setInterval(DEFAULT_INPUT_TIMEOUT); const int h = screen_size.height() * SIZING_FACTOR_HEIGHT; const int w = screen_size.width() * SIZING_FACTOR_WIDTH; const int hh = qMin(h, w); const int ww = hh / 3 * 2; pictureFlowWidget->setSlideSize(QSize(ww, hh)); bool success; int configIndex = args->indexOf("-config"); if ( (configIndex != -1) && (configIndex != args->count()-1) ) success = loadConfig(args->at(configIndex+1)); else success = loadConfig("config.xml"); if (success) { populatePictureFlow(); showFullScreen(); inputTimer->start(); } else { pictureFlowWidget->setAttribute(Qt::WA_DeleteOnClose, true); pictureFlowWidget->close(); } } FluidLauncher::~FluidLauncher() { delete pictureFlowWidget; delete slideShowWidget; } bool FluidLauncher::loadConfig(QString configPath) { QFile xmlFile(configPath); if (!xmlFile.exists() || (xmlFile.error() != QFile::NoError)) { qDebug() << "ERROR: Unable to open config file " << configPath; return false; } slideShowWidget->clearImages(); xmlFile.open(QIODevice::ReadOnly); QXmlStreamReader reader(&xmlFile); while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { if (reader.name() == "demos") parseDemos(reader); else if(reader.name() == "slideshow") parseSlideshow(reader); } } if (reader.hasError()) { qDebug() << QString("Error parsing %1 on line %2 column %3: \n%4") .arg(configPath) .arg(reader.lineNumber()) .arg(reader.columnNumber()) .arg(reader.errorString()); } // Append an exit Item DemoApplication* exitItem = new DemoApplication(QString(), QLatin1String("Exit Embedded Demo"), QString(), QStringList()); demoList.append(exitItem); return true; } void FluidLauncher::parseDemos(QXmlStreamReader& reader) { while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement() && reader.name() == "example") { QXmlStreamAttributes attrs = reader.attributes(); QStringRef filename = attrs.value("filename"); if (!filename.isEmpty()) { QStringRef name = attrs.value("name"); QStringRef image = attrs.value("image"); QStringRef args = attrs.value("args"); DemoApplication* newDemo = new DemoApplication( filename.toString(), name.isEmpty() ? "Unamed Demo" : name.toString(), image.toString(), args.toString().split(" ")); demoList.append(newDemo); } } else if(reader.isEndElement() && reader.name() == "demos") { return; } } } void FluidLauncher::parseSlideshow(QXmlStreamReader& reader) { QXmlStreamAttributes attrs = reader.attributes(); QStringRef timeout = attrs.value("timeout"); bool valid; if (!timeout.isEmpty()) { int t = timeout.toString().toInt(&valid); if (valid) inputTimer->setInterval(t); } QStringRef interval = attrs.value("interval"); if (!interval.isEmpty()) { int i = interval.toString().toInt(&valid); if (valid) slideShowWidget->setSlideInterval(i); } while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { QXmlStreamAttributes attrs = reader.attributes(); if (reader.name() == "imagedir") { QStringRef dir = attrs.value("dir"); slideShowWidget->addImageDir(dir.toString()); } else if(reader.name() == "image") { QStringRef image = attrs.value("image"); slideShowWidget->addImage(image.toString()); } } else if(reader.isEndElement() && reader.name() == "slideshow") { return; } } } void FluidLauncher::populatePictureFlow() { pictureFlowWidget->setSlideCount(demoList.count()); for (int i=demoList.count()-1; i>=0; --i) { pictureFlowWidget->setSlide(i, *(demoList[i]->getImage())); pictureFlowWidget->setSlideCaption(i, demoList[i]->getCaption()); } pictureFlowWidget->setCurrentSlide(demoList.count()/2); } void FluidLauncher::launchApplication(int index) { // NOTE: Clearing the caches will free up more memory for the demo but will cause // a delay upon returning, as items are reloaded. //pictureFlowWidget->clearCaches(); if (index == demoList.size() -1) { qApp->quit(); return; } inputTimer->stop(); QObject::connect(demoList[index], SIGNAL(demoFinished()), this, SLOT(demoFinished())); demoList[index]->launch(); } void FluidLauncher::switchToLauncher() { slideShowWidget->stopShow(); inputTimer->start(); setCurrentWidget(pictureFlowWidget); } void FluidLauncher::resetInputTimeout() { if (inputTimer->isActive()) inputTimer->start(); } void FluidLauncher::inputTimedout() { switchToSlideshow(); } void FluidLauncher::switchToSlideshow() { inputTimer->stop(); slideShowWidget->startShow(); setCurrentWidget(slideShowWidget); } void FluidLauncher::demoFinished() { setCurrentWidget(pictureFlowWidget); inputTimer->start(); // Bring the Fluidlauncher to the foreground to allow selecting another demo raise(); activateWindow(); } void FluidLauncher::changeEvent(QEvent* event) { if (event->type() == QEvent::ActivationChange) { if (isActiveWindow()) { if(currentWidget() == pictureFlowWidget) { resetInputTimeout(); } else { slideShowWidget->startShow(); } } else { inputTimer->stop(); slideShowWidget->stopShow(); } } QStackedWidget::changeEvent(event); }
radekp/qt
demos/embedded/fluidlauncher/fluidlauncher.cpp
C++
lgpl-2.1
8,555
""" This file shows how to use pyDatalog using facts stored in python objects. It has 3 parts : 1. define python class and business rules 2. create python objects for 2 employees 3. Query the objects using the datalog engine """ from pyDatalog import pyDatalog """ 1. define python class and business rules """ class Employee(pyDatalog.Mixin): # --> Employee inherits the pyDatalog capability to use logic clauses def __init__(self, name, manager, salary): # method to initialize Employee instances super(Employee, self).__init__() # calls the initialization method of the Mixin class self.name = name self.manager = manager # direct manager of the employee, or None self.salary = salary # monthly salary of the employee def __repr__(self): # specifies how to display an Employee return self.name @pyDatalog.program() # indicates that the following method contains pyDatalog clauses def Employee(self): # the salary class N of employee X is computed as a function of his/her salary # this statement is a logic equality, not an assignment ! Employee.salary_class[X] = Employee.salary[X]//1000 # all the indirect managers Y of employee X are derived from his manager, recursively Employee.indirect_manager(X,Y) <= (Employee.manager[X]==Y) & (Y != None) Employee.indirect_manager(X,Y) <= (Employee.manager[X]==Z) & Employee.indirect_manager(Z,Y) & (Y != None) # count the number of reports of X (Employee.report_count[X] == len(Y)) <= Employee.indirect_manager(Y,X) """ 2. create python objects for 3 employees """ # John is the manager of Mary, who is the manager of Sam John = Employee('John', None, 6800) Mary = Employee('Mary', John, 6300) Sam = Employee('Sam', Mary, 5900) """ 3. Query the objects using the datalog engine """ # the following python statements implicitly use the datalog clauses in the class definition # What is the salary class of John ? print(John.salary_class) # prints 6 # who has a salary of 6300 ? pyDatalog.create_terms('X') Employee.salary[X] == 6300 # notice the similarity to a pyDatalog query print(X) # prints [Mary] print(X.v()) # prints Mary # who are the indirect managers of Mary ? Employee.indirect_manager(Mary, X) print(X) # prints [John] # Who are the employees of John with a salary below 6000 ? result = (Employee.salary[X] < 6000) & Employee.indirect_manager(X, John) print(result) # Sam is in the result print(X) # prints [Sam] print((Employee.salary_class[X] == 5) & Employee.indirect_manager(X, John) >= X) # Sam # verify that the manager of Mary is John assert Employee.manager[Mary]==John # who is his own indirect manager ? Employee.indirect_manager(X, X) print(X) # prints [] # who has 2 reports ? Employee.report_count[X] == 2 print(X) # prints [John] # what is the total salary of the employees of John ? # note : it is better to place aggregation clauses in the class definition pyDatalog.load("(Employee.budget[X] == sum(N, for_each=Y)) <= (Employee.indirect_manager(Y, X)) & (Employee.salary[Y]==N)") Employee.budget[John]==X print(X) # prints [12200] # who has the lowest salary ? pyDatalog.load("(lowest[1] == min(X, order_by=N)) <= (Employee.salary[X]==N)") # must use ask() because inline queries cannot use unprefixed literals print(pyDatalog.ask("lowest[1]==X")) # prints set([(1, 'Sam')])
pcarbonn/pyDatalog
pyDatalog/examples/python.py
Python
lgpl-2.1
3,454
// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #include "bseitem.hh" #include "bsesuper.hh" #include "bsesnet.hh" #include "bsestorage.hh" #include "bseprocedure.hh" #include "bsemain.hh" #include "bseproject.hh" #include "bsesong.hh" // for song->musical_tuning #include "bseundostack.hh" #include <gobject/gvaluecollector.h> #include <string.h> enum { PROP_0, PROP_SEQID, }; /* --- prototypes --- */ static void bse_item_class_init_base (BseItemClass *klass); static void bse_item_class_finalize_base (BseItemClass *klass); static void bse_item_class_init (BseItemClass *klass); static void bse_item_init (BseItem *item); static void bse_item_set_property_internal (GObject *object, uint param_id, const GValue *value, GParamSpec *pspec); static void bse_item_get_property_internal (GObject *object, uint param_id, GValue *value, GParamSpec *pspec); static void bse_item_update_state (BseItem *self); static gboolean bse_item_real_needs_storage (BseItem *self, BseStorage *storage); static void bse_item_do_dispose (GObject *object); static void bse_item_do_finalize (GObject *object); static void bse_item_do_set_uname (BseObject *object, const char *uname); static uint bse_item_do_get_seqid (BseItem *item); static void bse_item_do_set_parent (BseItem *item, BseItem *parent); static BseUndoStack* bse_item_default_get_undo (BseItem *self); /* --- variables --- */ static GTypeClass *parent_class = NULL; static GSList *item_seqid_changed_queue = NULL; /* --- functions --- */ BSE_BUILTIN_TYPE (BseItem) { static const GTypeInfo item_info = { sizeof (BseItemClass), (GBaseInitFunc) bse_item_class_init_base, (GBaseFinalizeFunc) bse_item_class_finalize_base, (GClassInitFunc) bse_item_class_init, (GClassFinalizeFunc) NULL, NULL /* class_data */, sizeof (BseItem), 0 /* n_preallocs */, (GInstanceInitFunc) bse_item_init, }; assert_return (BSE_ITEM_FLAGS_USHIFT < BSE_OBJECT_FLAGS_MAX_SHIFT, 0); return bse_type_register_abstract (BSE_TYPE_OBJECT, "BseItem", "Base type for objects managed by a container", __FILE__, __LINE__, &item_info); } static void bse_item_class_init_base (BseItemClass *klass) { klass->get_candidates = NULL; } static void bse_item_class_finalize_base (BseItemClass *klass) { } static void bse_item_class_init (BseItemClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); BseObjectClass *object_class = BSE_OBJECT_CLASS (klass); parent_class = (GTypeClass*) g_type_class_peek_parent (klass); gobject_class->get_property = bse_item_get_property_internal; gobject_class->set_property = bse_item_set_property_internal; gobject_class->dispose = bse_item_do_dispose; gobject_class->finalize = bse_item_do_finalize; object_class->set_uname = bse_item_do_set_uname; klass->set_parent = bse_item_do_set_parent; klass->get_seqid = bse_item_do_get_seqid; klass->get_undo = bse_item_default_get_undo; klass->needs_storage = bse_item_real_needs_storage; bse_object_class_add_param (object_class, NULL, PROP_SEQID, sfi_pspec_int ("seqid", "Sequential ID", NULL, 0, 0, SFI_MAXINT, 1, "r")); } static void bse_item_init (BseItem *item) { item->parent = NULL; } static void bse_item_set_property_internal (GObject *object, uint param_id, const GValue *value, GParamSpec *pspec) { // BseItem *self = BSE_ITEM (object); switch (param_id) { default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } static void bse_item_get_property_internal (GObject *object, uint param_id, GValue *value, GParamSpec *pspec) { BseItem *self = BSE_ITEM (object); switch (param_id) { case PROP_SEQID: sfi_value_set_int (value, bse_item_get_seqid (self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); break; } } static void bse_item_do_dispose (GObject *gobject) { BseItem *item = BSE_ITEM (gobject); /* force removal from parent */ if (item->parent) bse_container_remove_item (BSE_CONTAINER (item->parent), item); /* chain parent class' handler */ G_OBJECT_CLASS (parent_class)->dispose (gobject); } static void bse_item_do_finalize (GObject *object) { BseItem *item = BSE_ITEM (object); item_seqid_changed_queue = g_slist_remove (item_seqid_changed_queue, item); /* chain parent class' handler */ G_OBJECT_CLASS (parent_class)->finalize (object); assert_return (item->use_count == 0); } static void bse_item_do_set_uname (BseObject *object, const char *uname) { BseItem *item = BSE_ITEM (object); /* ensure that item names within their container are unique, * and that we don't end up with a NULL uname */ if (!BSE_IS_CONTAINER (item->parent) || (uname && !bse_container_lookup_item (BSE_CONTAINER (item->parent), uname))) { /* chain parent class' set_uname handler */ BSE_OBJECT_CLASS (parent_class)->set_uname (object, uname); } } static void bse_item_do_set_parent (BseItem *self, BseItem *parent) { self->parent = parent; bse_item_update_state (self); } static gboolean recurse_update_state (BseItem *self, void *data) { bse_item_update_state (self); return TRUE; } static void bse_item_update_state (BseItem *self) { /* save original state */ gboolean old_internal = BSE_ITEM_INTERNAL (self); /* update state */ if ((BSE_OBJECT_FLAGS (self) & BSE_ITEM_FLAG_INTERN) || (self->parent && BSE_ITEM_INTERNAL (self->parent))) BSE_OBJECT_SET_FLAGS (self, BSE_ITEM_FLAG_INTERN_BRANCH); else BSE_OBJECT_UNSET_FLAGS (self, BSE_ITEM_FLAG_INTERN_BRANCH); /* compare state and recurse if necessary */ if (BSE_IS_CONTAINER (self) && (old_internal != BSE_ITEM_INTERNAL (self))) bse_container_forall_items ((BseContainer*) self, recurse_update_state, NULL); } /** * @param item valid BseItem * @param internal TRUE or FALSE * * Set whether an item should be considered internal to the BSE * implementation (or implementation of another BSE object). * Internal items are not stored with their parents and undo * is not recorded for internal items either. Marking containers * internal also affects any children they contain, in effect, * the whole posterity spawned by the container is considered * internal. */ void bse_item_set_internal (void *item, gboolean internal) { BseItem *self = BSE_ITEM (item); assert_return (BSE_IS_ITEM (self)); if (internal) BSE_OBJECT_SET_FLAGS (self, BSE_ITEM_FLAG_INTERN); else BSE_OBJECT_UNSET_FLAGS (self, BSE_ITEM_FLAG_INTERN); bse_item_update_state (self); } static gboolean bse_item_real_needs_storage (BseItem *self, BseStorage *storage) { return TRUE; } gboolean bse_item_needs_storage (BseItem *self, BseStorage *storage) { assert_return (BSE_IS_ITEM (self), FALSE); assert_return (BSE_IS_STORAGE (storage), FALSE); return BSE_ITEM_GET_CLASS (self)->needs_storage (self, storage); } void bse_item_compat_setup (BseItem *self, uint vmajor, uint vminor, uint vmicro) { assert_return (BSE_IS_ITEM (self)); if (BSE_ITEM_GET_CLASS (self)->compat_setup) BSE_ITEM_GET_CLASS (self)->compat_setup (self, vmajor, vminor, vmicro); } struct GatherData { BseItem *item; void *data; Bse::ItemSeq &iseq; GType base_type; BseItemCheckContainer ccheck; BseItemCheckProxy pcheck; GatherData (Bse::ItemSeq &is) : iseq (is) {} }; static gboolean gather_child (BseItem *child, void *data) { GatherData *gdata = (GatherData*) data; if (child != gdata->item && !BSE_ITEM_INTERNAL (child) && g_type_is_a (G_OBJECT_TYPE (child), gdata->base_type) && (!gdata->pcheck || gdata->pcheck (child, gdata->item, gdata->data))) gdata->iseq.push_back (child->as<Bse::ItemIfaceP>()); return TRUE; } /** * @param item valid BseItem from which to start gathering * @param items sequence of items to append to * @param base_type base type of the items to gather * @param ccheck container filter function * @param pcheck proxy filter function * @param data @a data pointer to @a ccheck and @a pcheck * * This function gathers items from an object hierachy, walking upwards, * starting out with @a item. For each container passing @a ccheck(), all * immediate children are tested for addition with @a pcheck. */ static void bse_item_gather_items (BseItem *item, Bse::ItemSeq &iseq, GType base_type, BseItemCheckContainer ccheck, BseItemCheckProxy pcheck, void *data) { GatherData gdata (iseq); assert_return (BSE_IS_ITEM (item)); assert_return (g_type_is_a (base_type, BSE_TYPE_ITEM)); gdata.item = item; gdata.data = data; gdata.base_type = base_type; gdata.ccheck = ccheck; gdata.pcheck = pcheck; item = BSE_IS_CONTAINER (item) ? item : item->parent; while (item) { BseContainer *container = BSE_CONTAINER (item); if (!gdata.ccheck || gdata.ccheck (container, gdata.item, gdata.data)) bse_container_forall_items (container, gather_child, &gdata); item = item->parent; } } static gboolean gather_typed_ccheck (BseContainer *container, BseItem *item, void *data) { GType type = (GType) data; return g_type_is_a (G_OBJECT_TYPE (container), type); } static gboolean gather_typed_acheck (BseItem *proxy, BseItem *item, void *data) { return proxy != item && !bse_item_has_ancestor (item, proxy); } /** * @param item valid BseItem from which to start gathering * @param items sequence of items to append to * @param proxy_type base type of the items to gather * @param container_type base type of the containers to check for items * @param allow_ancestor if FALSE, ancestors of @a item are omitted * * Variant of bse_item_gather_items(), the containers and items * are simply filtered by checking derivation from @a container_type * and @a proxy_type respectively. Gathered items may not be ancestors * of @a item if @a allow_ancestor is @a false. */ void bse_item_gather_items_typed (BseItem *item, Bse::ItemSeq &iseq, GType proxy_type, GType container_type, bool allow_ancestor) { if (allow_ancestor) bse_item_gather_items (item, iseq, proxy_type, gather_typed_ccheck, NULL, (void*) container_type); else bse_item_gather_items (item, iseq, proxy_type, gather_typed_ccheck, gather_typed_acheck, (void*) container_type); } gboolean bse_item_get_candidates (BseItem *item, const Bse::String &property, Bse::PropertyCandidates &pc) { BseItemClass *klass; GParamSpec *pspec; assert_return (BSE_IS_ITEM (item), FALSE); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (item), property.c_str()); if (!pspec) return FALSE; klass = (BseItemClass*) g_type_class_peek (pspec->owner_type); if (klass && klass->get_candidates) klass->get_candidates (item, pspec->param_id, pc, pspec); return TRUE; } BseItem* bse_item_use (BseItem *item) { assert_return (BSE_IS_ITEM (item), NULL); assert_return (G_OBJECT (item)->ref_count > 0, NULL); if (!item->use_count) g_object_ref (item); item->use_count++; return item; } void bse_item_unuse (BseItem *item) { assert_return (BSE_IS_ITEM (item)); assert_return (item->use_count > 0); item->use_count--; if (!item->use_count) { if (!item->parent) g_object_run_dispose (G_OBJECT (item)); g_object_unref (item); } } void bse_item_set_parent (BseItem *item, BseItem *parent) { assert_return (BSE_IS_ITEM (item)); if (parent) { assert_return (item->parent == NULL); assert_return (BSE_IS_CONTAINER (parent)); } else assert_return (item->parent != NULL); assert_return (BSE_ITEM_GET_CLASS (item)->set_parent != NULL); /* paranoid */ g_object_ref (item); if (parent) g_object_ref (parent); BSE_ITEM_GET_CLASS (item)->set_parent (item, parent); if (parent) g_object_unref (parent); else g_object_run_dispose (G_OBJECT (item)); g_object_unref (item); } static uint bse_item_do_get_seqid (BseItem *item) { if (item->parent) return bse_container_get_item_seqid (BSE_CONTAINER (item->parent), item); else return 0; } static gboolean idle_handler_seqid_changed (void *data) { BSE_THREADS_ENTER (); while (item_seqid_changed_queue) { BseItem *item = (BseItem*) g_slist_pop_head (&item_seqid_changed_queue); g_object_notify (G_OBJECT (item), "seqid"); } BSE_THREADS_LEAVE (); return FALSE; } void bse_item_queue_seqid_changed (BseItem *item) { assert_return (BSE_IS_ITEM (item)); assert_return (BSE_ITEM (item)->parent != NULL); if (!item_seqid_changed_queue) bse_idle_notify (idle_handler_seqid_changed, NULL); if (!g_slist_find (item_seqid_changed_queue, item)) item_seqid_changed_queue = g_slist_prepend (item_seqid_changed_queue, item); } uint bse_item_get_seqid (BseItem *item) { assert_return (BSE_IS_ITEM (item), 0); assert_return (BSE_ITEM_GET_CLASS (item)->get_seqid != NULL, 0); /* paranoid */ return BSE_ITEM_GET_CLASS (item)->get_seqid (item); } BseItem* bse_item_common_ancestor (BseItem *item1, BseItem *item2) { assert_return (BSE_IS_ITEM (item1), NULL); assert_return (BSE_IS_ITEM (item2), NULL); do { BseItem *item = item2; do { if (item == item1) return item; item = item->parent; } while (item); item1 = item1->parent; } while (item1); return NULL; } /** * @param owner reference owner * @param link item to be referenced by @a owner * @param uncross_func notifier to be executed on uncrossing * * Install a weak cross reference from @a owner to @a link. * The two items must have a common ancestor when the cross * link is installed. Once their ancestry changes so that * they don't have a common ancestor anymore, @a uncross_func() * is executed. */ void bse_item_cross_link (BseItem *owner, BseItem *link, BseItemUncross uncross_func) { BseItem *container; assert_return (BSE_IS_ITEM (owner)); assert_return (BSE_IS_ITEM (link)); assert_return (uncross_func != NULL); container = bse_item_common_ancestor (owner, link); if (container) _bse_container_cross_link (BSE_CONTAINER (container), owner, link, uncross_func); else Bse::warning ("%s: %s and %s have no common anchestor", G_STRLOC, bse_object_debug_name (owner), bse_object_debug_name (link)); } /** * @param owner reference owner * @param link item referenced by @a owner * @param uncross_func notifier queued to be executed on uncrossing * * Removes a cross link previously installed via * bse_item_cross_link() without executing @a uncross_func(). */ void bse_item_cross_unlink (BseItem *owner, BseItem *link, BseItemUncross uncross_func) { BseItem *container; assert_return (BSE_IS_ITEM (owner)); assert_return (BSE_IS_ITEM (link)); assert_return (uncross_func != NULL); container = bse_item_common_ancestor (owner, link); if (container) _bse_container_cross_unlink (BSE_CONTAINER (container), owner, link, uncross_func); else Bse::warning ("%s: `%s' and `%s' have no common anchestor", G_STRLOC, BSE_OBJECT_TYPE_NAME (owner), BSE_OBJECT_TYPE_NAME (link)); } /** * @param owner reference owner * @param link item referenced by @a owner * * Destroys all existing cross links from @a owner to * @a link by executing the associated notifiers. */ void bse_item_uncross_links (BseItem *owner, BseItem *link) { BseItem *container; assert_return (BSE_IS_ITEM (owner)); assert_return (BSE_IS_ITEM (link)); container = bse_item_common_ancestor (owner, link); if (container) _bse_container_uncross (BSE_CONTAINER (container), owner, link); } BseSuper* bse_item_get_super (BseItem *item) { assert_return (BSE_IS_ITEM (item), NULL); while (!BSE_IS_SUPER (item) && item) item = item->parent; return item ? BSE_SUPER (item) : NULL; } BseSNet* bse_item_get_snet (BseItem *item) { assert_return (BSE_IS_ITEM (item), NULL); while (!BSE_IS_SNET (item) && item) item = item->parent; return item ? BSE_SNET (item) : NULL; } BseItem* bse_item_get_toplevel (BseItem *item) { assert_return (BSE_IS_ITEM (item), NULL); while (item->parent) item = item->parent; return item; } BseProject* bse_item_get_project (BseItem *item) { assert_return (BSE_IS_ITEM (item), NULL); while (item->parent) item = item->parent; return BSE_IS_PROJECT (item) ? (BseProject*) item : NULL; } gboolean bse_item_has_ancestor (BseItem *item, BseItem *ancestor) { assert_return (BSE_IS_ITEM (item), FALSE); assert_return (BSE_IS_ITEM (ancestor), FALSE); while (item->parent) { item = item->parent; if (item == ancestor) return TRUE; } return FALSE; } /** * @param self a valid Item * @return the current BseMusicalTuningType, defaulting to BSE_MUSICAL_TUNING_12_TET * Find out about the musical tuning that is currently used for this item. * The musical tuning depends on project wide settings that may change after * this funciton has been called, so the result should be used with caution. */ Bse::MusicalTuning bse_item_current_musical_tuning (BseItem *self) { assert_return (BSE_IS_ITEM (self), Bse::MusicalTuning::OD_12_TET); /* finding the musical tuning *should* be possible by just visiting * an items parents. however, .bse objects are not currently (0.7.1) * structured that way, so we get the tuning from the first song in * a project, or simply provide a default. */ BseProject *project = bse_item_get_project (self); if (project) { GSList *slist; for (slist = project->supers; slist; slist = slist->next) if (BSE_IS_SONG (slist->data)) return BSE_SONG (slist->data)->musical_tuning; } return Bse::MusicalTuning::OD_12_TET; } static inline GType find_method_procedure (GType object_type, const char *method_name) { uint l2 = strlen (method_name); GType proc_type, type = object_type; /* assumed to be *derived* from BSE_TYPE_ITEM */ do { const char *type_name = g_type_name (type); uint l1 = strlen (type_name); char *name = g_new (char, l1 + 1 + l2 + 1); memcpy (name, type_name, l1); name[l1] = '+'; memcpy (name + l1 + 1, method_name, l2); name[l1 + 1 + l2] = 0; proc_type = bse_procedure_lookup (name); g_free (name); if (proc_type) break; type = g_type_parent (type); } while (type != BSE_TYPE_ITEM); /* type will become BSE_TYPE_ITEM eventually */ return proc_type; } static inline Bse::Error bse_item_execva_i (BseItem *item, const char *procedure, va_list var_args, gboolean skip_oparams) { Bse::Error error; GType proc_type = find_method_procedure (BSE_OBJECT_TYPE (item), procedure); GValue obj_value; if (!proc_type) { Bse::warning ("no such method \"%s\" of item %s", procedure, bse_object_debug_name (item)); return Bse::Error::INTERNAL; } /* setup first arg (the object) */ obj_value.g_type = 0; g_value_init (&obj_value, BSE_TYPE_ITEM); g_value_set_object (&obj_value, item); /* invoke procedure */ error = bse_procedure_marshal_valist (proc_type, &obj_value, NULL, NULL, skip_oparams, var_args); g_value_unset (&obj_value); return error; } Bse::Error bse_item_exec (void *_item, const char *procedure, ...) { BseItem *item = (BseItem*) _item; va_list var_args; Bse::Error error; assert_return (BSE_IS_ITEM (item), Bse::Error::INTERNAL); assert_return (procedure != NULL, Bse::Error::INTERNAL); va_start (var_args, procedure); error = bse_item_execva_i (item, procedure, var_args, FALSE); va_end (var_args); return error; } Bse::Error bse_item_exec_void (void *_item, const char *procedure, ...) { BseItem *item = (BseItem*) _item; va_list var_args; Bse::Error error; assert_return (BSE_IS_ITEM (item), Bse::Error::INTERNAL); assert_return (procedure != NULL, Bse::Error::INTERNAL); va_start (var_args, procedure); error = bse_item_execva_i (item, procedure, var_args, TRUE); va_end (var_args); return error; } static GValue* pack_value_for_undo (GValue *value, BseUndoStack *ustack) { GType type = G_VALUE_TYPE (value); if (G_TYPE_IS_OBJECT (type)) { char *p = bse_undo_pointer_pack (g_value_get_object (value), ustack); g_value_unset (value); g_value_init (value, BSE_TYPE_PACKED_POINTER); sfi_value_take_string (value, p); } return value; } static GValue* unpack_value_from_undo (GValue *value, BseUndoStack *ustack) { GType type = G_VALUE_TYPE (value); if (type == BSE_TYPE_PACKED_POINTER) { BseItem *item = (BseItem*) bse_undo_pointer_unpack (g_value_get_string (value), ustack); g_value_unset (value); g_value_init (value, G_TYPE_OBJECT); g_value_set_object (value, item); } return value; } static void unde_free_proc (BseUndoStep *ustep) { BseProcedureClass *proc = (BseProcedureClass*) ustep->data[0].v_pointer; GValue *ivalues = (GValue*) ustep->data[1].v_pointer; /* may or may not packed for undo */ if (ivalues && proc) { uint i; for (i = 0; i < proc->n_in_pspecs; i++) g_value_unset (ivalues + i); g_free (ivalues); g_type_class_unref (proc); } } static void undo_call_proc (BseUndoStep *ustep, BseUndoStack *ustack) { BseProcedureClass *proc = (BseProcedureClass*) ustep->data[0].v_pointer; GValue *ivalues = (GValue*) ustep->data[1].v_pointer; /* packed for undo */ gboolean commit_as_redo = ustep->data[2].v_long; if (commit_as_redo) { const char *packed_item_pointer = g_value_get_string (ivalues + 0); BseItem *item = (BseItem*) bse_undo_pointer_unpack (packed_item_pointer, ustack); BseUndoStack *redo_stack = bse_item_undo_open (item, "%s", BSE_PROCEDURE_NAME (proc)); BseUndoStep *redo_step; redo_step = bse_undo_step_new (undo_call_proc, unde_free_proc, 3); redo_step->data[0].v_pointer = proc; redo_step->data[1].v_pointer = ivalues; redo_step->data[2].v_long = FALSE; /* not commit_as_redo again */ bse_undo_stack_push (redo_stack, redo_step); bse_item_undo_close (redo_stack); /* prevent premature deletion */ ustep->data[0].v_pointer = NULL; ustep->data[1].v_pointer = NULL; } else /* invoke procedure */ { GValue ovalue = { 0, }; Bse::Error error; uint i; /* convert values from undo */ for (i = 0; i < proc->n_in_pspecs; i++) unpack_value_from_undo (ivalues + i, ustack); /* setup return value (maximum one) */ if (proc->n_out_pspecs) g_value_init (&ovalue, G_PARAM_SPEC_VALUE_TYPE (proc->out_pspecs[0])); /* invoke procedure */ error = bse_procedure_marshal (BSE_PROCEDURE_TYPE (proc), ivalues, &ovalue, NULL, NULL); /* clenup return value */ if (proc->n_out_pspecs) { /* check returned error if any */ if (G_PARAM_SPEC_VALUE_TYPE (proc->out_pspecs[0]) == BSE_TYPE_ERROR_TYPE && error == 0) error = Bse::Error (g_value_get_enum (&ovalue)); g_value_unset (&ovalue); } /* we're not tolerating any errors */ if (error != 0) Bse::warning ("while executing undo method \"%s\" of item %s: %s", BSE_PROCEDURE_NAME (proc), bse_object_debug_name (g_value_get_object (ivalues + 0)), bse_error_blurb (error)); } } static void bse_item_push_undo_proc_valist (void *item, const char *procedure, gboolean commit_as_redo, va_list var_args) { GType proc_type = find_method_procedure (BSE_OBJECT_TYPE (item), procedure); BseUndoStack *ustack = bse_item_undo_open (item, "%s: %s", commit_as_redo ? "redo-proc" : "undo-proc", procedure); BseProcedureClass *proc; GValue *ivalues; Bse::Error error; uint i; if (BSE_UNDO_STACK_VOID (ustack) || BSE_ITEM_INTERNAL (item)) { bse_item_undo_close (ustack); return; } if (!proc_type) { Bse::warning ("no such method \"%s\" of item %s", procedure, bse_object_debug_name (item)); bse_item_undo_close (ustack); return; } proc = (BseProcedureClass*) g_type_class_ref (proc_type); /* we allow one return value */ if (proc->n_out_pspecs > 1) { Bse::warning ("method \"%s\" of item %s called with more than one return value", procedure, bse_object_debug_name (item)); g_type_class_unref (proc); bse_item_undo_close (ustack); return; } ivalues = g_new (GValue, proc->n_in_pspecs); /* setup first arg (the object) */ ivalues[0].g_type = 0; g_value_init (ivalues + 0, BSE_TYPE_ITEM); g_value_set_object (ivalues + 0, item); /* collect procedure args */ error = bse_procedure_collect_input_args (proc, ivalues + 0, var_args, ivalues); if (error == 0) { BseUndoStep *ustep = bse_undo_step_new (undo_call_proc, unde_free_proc, 3); /* convert values for undo */ for (i = 0; i < proc->n_in_pspecs; i++) pack_value_for_undo (ivalues + i, ustack); ustep->data[0].v_pointer = proc; ustep->data[1].v_pointer = ivalues; ustep->data[2].v_long = commit_as_redo; bse_undo_stack_push (ustack, ustep); } else /* urg shouldn't happen */ { Bse::warning ("while collecting arguments for method \"%s\" of item %s: %s", procedure, bse_object_debug_name (item), bse_error_blurb (error)); for (i = 0; i < proc->n_in_pspecs; i++) g_value_unset (ivalues + i); g_free (ivalues); g_type_class_unref (proc); } bse_item_undo_close (ustack); } void bse_item_push_undo_proc (void *item, const char *procedure, ...) { va_list var_args; assert_return (BSE_IS_ITEM (item)); assert_return (procedure != NULL); va_start (var_args, procedure); bse_item_push_undo_proc_valist (item, procedure, FALSE, var_args); va_end (var_args); } void bse_item_push_redo_proc (void *item, const char *procedure, ...) { va_list var_args; assert_return (BSE_IS_ITEM (item)); assert_return (procedure != NULL); va_start (var_args, procedure); bse_item_push_undo_proc_valist (item, procedure, TRUE, var_args); va_end (var_args); } void bse_item_set_undoable (void *object, const char *first_property_name, ...) { va_list var_args; assert_return (BSE_IS_ITEM (object)); va_start (var_args, first_property_name); bse_item_set_valist_undoable (object, first_property_name, var_args); va_end (var_args); } void bse_item_set_valist_undoable (void *object, const char *first_property_name, va_list var_args) { BseItem *self = BSE_ITEM (object); const char *name; assert_return (BSE_IS_ITEM (self)); g_object_ref (object); g_object_freeze_notify (G_OBJECT (object)); name = first_property_name; while (name) { GValue value = { 0, }; GParamSpec *pspec; char *error = NULL; pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (self), name); if (!pspec) { Bse::warning ("item %s has no property named `%s'", bse_object_debug_name (self), name); break; } g_value_init (&value, G_PARAM_SPEC_VALUE_TYPE (pspec)); G_VALUE_COLLECT (&value, var_args, 0, &error); if (error) { Bse::warning ("while setting property `%s' on %s: %s", name, bse_object_debug_name (self), error); g_free (error); g_value_unset (&value); break; } bse_item_set_property_undoable (self, pspec->name, &value); g_value_unset (&value); name = va_arg (var_args, char*); } g_object_thaw_notify (G_OBJECT (object)); g_object_unref (object); } static BseUndoStack* bse_item_default_get_undo (BseItem *self) { if (self->parent) return BSE_ITEM_GET_CLASS (self->parent)->get_undo (self->parent); else return NULL; } static gboolean values_equal_for_undo (const GValue *v1, const GValue *v2) { SfiSCategory sc1 = sfi_categorize_type (G_VALUE_TYPE (v1)); SfiSCategory sc2 = sfi_categorize_type (G_VALUE_TYPE (v2)); if (sc1 != sc2) return FALSE; switch (sc1) { case SFI_SCAT_BOOL: return sfi_value_get_bool (v1) == sfi_value_get_bool (v2); case SFI_SCAT_INT: return sfi_value_get_int (v1) == sfi_value_get_int (v2); case SFI_SCAT_NUM: return sfi_value_get_num (v1) == sfi_value_get_num (v2); case SFI_SCAT_REAL: return sfi_value_get_real (v1) == sfi_value_get_real (v2); /* *no* epsilon! */ case SFI_SCAT_CHOICE: case SFI_SCAT_STRING: return bse_string_equals (sfi_value_get_string (v1), sfi_value_get_string (v2)); default: if (G_TYPE_IS_OBJECT (G_VALUE_TYPE (v1)) && G_TYPE_IS_OBJECT (G_VALUE_TYPE (v2))) return g_value_get_object (v1) == g_value_get_object (v2); } return FALSE; } static void undo_set_property (BseUndoStep *ustep, BseUndoStack *ustack) { bse_item_set_property_undoable ((BseItem*) bse_undo_pointer_unpack ((const char*) ustep->data[0].v_pointer, ustack), (const char*) ustep->data[1].v_pointer, unpack_value_from_undo ((GValue*) ustep->data[2].v_pointer, ustack)); } static void unde_free_property (BseUndoStep *ustep) { g_free (ustep->data[0].v_pointer); g_free (ustep->data[1].v_pointer); g_value_unset ((GValue*) ustep->data[2].v_pointer); /* may or may not be unpacked */ g_free (ustep->data[2].v_pointer); } static inline gboolean item_property_check_skip_undo (BseItem *self, const char *name) { GParamSpec *pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (self), name); return pspec && sfi_pspec_check_option (pspec, "skip-undo"); } void bse_item_set_property_undoable (BseItem *self, const char *name, const GValue *value) { BseUndoStack *ustack = bse_item_undo_open (self, "set-property(%s,\"%s\")", bse_object_debug_name (self), name); BseUndoStep *ustep; GValue *tvalue = g_new0 (GValue, 1); g_value_init (tvalue, G_VALUE_TYPE (value)); g_object_get_property (G_OBJECT (self), name, tvalue); if (BSE_ITEM_INTERNAL (self) || item_property_check_skip_undo (self, name) || values_equal_for_undo (value, tvalue)) { /* we're about to set a value on an internal item or * to set the same value again => skip undo */ g_value_unset (tvalue); g_free (tvalue); bse_item_undo_close (ustack); g_object_set_property (G_OBJECT (self), name, value); return; } g_object_set_property (G_OBJECT (self), name, value); /* pointer-pack must be called *after* property update (could be "uname") */ ustep = bse_undo_step_new (undo_set_property, unde_free_property, 3); ustep->data[0].v_pointer = bse_undo_pointer_pack (self, ustack); ustep->data[1].v_pointer = g_strdup (name); ustep->data[2].v_pointer = pack_value_for_undo (tvalue, ustack); bse_undo_stack_push (ustack, ustep); bse_item_undo_close (ustack); } BseUndoStack* bse_item_undo_open_str (void *item, const std::string &string) { BseItem *self = BSE_ITEM (item); BseUndoStack *ustack = BSE_ITEM_GET_CLASS (self)->get_undo (self); if (ustack) bse_undo_group_open (ustack, string.c_str()); else { ustack = bse_undo_stack_dummy (); bse_undo_group_open (ustack, Bse::string_format ("DUMMY-GROUP(%s)", string).c_str()); } return ustack; } void bse_item_undo_close (BseUndoStack *ustack) { if (ustack) bse_undo_group_close (ustack); } static void undo_restore_item (BseUndoStep *ustep, BseUndoStack *ustack) { BseItem *item = (BseItem*) bse_undo_pointer_unpack ((const char*) ustep->data[0].v_pointer, ustack); BseStorage *storage = BSE_STORAGE (ustep->data[1].v_pointer); GTokenType expected_token = G_TOKEN_NONE; expected_token = bse_storage_restore_item (storage, item); if (expected_token != G_TOKEN_NONE) bse_storage_unexp_token (storage, expected_token); bse_storage_finish_parsing (storage); } static void unde_free_item (BseUndoStep *ustep) { BseStorage *storage = BSE_STORAGE (ustep->data[1].v_pointer); g_free (ustep->data[0].v_pointer); bse_storage_reset (storage); g_object_unref (storage); } void bse_item_push_undo_storage (BseItem *self, BseUndoStack *ustack, BseStorage *storage) { if (!BSE_ITEM_INTERNAL (self) && !BSE_UNDO_STACK_VOID (ustack)) { BseUndoStep *ustep = bse_undo_step_new (undo_restore_item, unde_free_item, 2); bse_storage_turn_readable (storage, "<undo-storage>"); ustep->data[0].v_pointer = bse_undo_pointer_pack (self, ustack); ustep->data[1].v_pointer = g_object_ref (storage); bse_undo_stack_push (ustack, ustep); } else bse_storage_reset (storage); } void bse_item_backup_to_undo (BseItem *self, BseUndoStack *ustack) { if (!BSE_UNDO_STACK_VOID (ustack)) { BseStorage *storage = (BseStorage*) bse_object_new (BSE_TYPE_STORAGE, NULL); bse_storage_prepare_write (storage, BseStorageMode (BSE_STORAGE_DBLOCK_CONTAINED | BSE_STORAGE_SELF_CONTAINED)); bse_storage_store_item (storage, self); bse_item_push_undo_storage (self, ustack, storage); g_object_unref (storage); } } namespace Bse { ItemImpl::ItemImpl (BseObject *bobj) : ObjectImpl (bobj) {} ItemImpl::~ItemImpl () {} ItemIfaceP ItemImpl::use () { BseItem *self = as<BseItem*>(); ItemIfaceP iface = self->as<ItemIfaceP>(); assert_return (self->parent || self->use_count, iface); bse_item_use (self); return iface; } void ItemImpl::unuse () { BseItem *self = as<BseItem*>(); assert_return (self->use_count >= 1); bse_item_unuse (self); } void ItemImpl::set_name (const std::string &name) { BseItem *self = as<BseItem*>(); if (name != BSE_OBJECT_UNAME (self)) bse_item_set (self, "uname", name.c_str(), NULL); } bool ItemImpl::editable_property (const std::string &property) { BseItem *self = as<BseItem*>(); return bse_object_editable_property (self, property.c_str()); } ContainerImpl* ItemImpl::parent () { BseItem *self = as<BseItem*>(); return self->parent ? self->parent->as<ContainerImpl*>() : NULL; } ItemImpl::UndoDescriptorData ItemImpl::make_undo_descriptor_data (ItemImpl &item) { // sync with bse_undo_pointer_pack UndoDescriptorData udd; BseItem *bitem = item.as<BseItem*>(); BseProject *bproject = bse_item_get_project (this->as<BseItem*>()); if (!bproject) // may happen during destruction return udd; // this UndoDescriptorData is constructed but will never be used assert_return (bproject == bse_item_get_project (bitem), udd); // undo descriptors work only for items within same project ProjectImpl *project = bproject->as<ProjectImpl*>(); udd.projectid = ptrdiff_t (project); if (&item == project) udd.upath = "\002project\003"; else { gchar *upath = bse_container_make_upath (bproject, bitem); udd.upath = upath; g_free (upath); } return udd; } ItemImpl& ItemImpl::resolve_undo_descriptor_data (const UndoDescriptorData &udd) { // sync with bse_undo_pointer_unpack ItemImpl &nullitem = *(ItemImpl*) NULL; assert_return (udd.projectid != 0, nullitem); BseProject *bproject = bse_item_get_project (this->as<BseItem*>()); ProjectImpl *project = bproject ? bproject->as<ProjectImpl*>() : NULL; assert_return (udd.projectid == ptrdiff_t (project), nullitem); // undo cannot work on orphans if (udd.upath == "\002project\003") return *project; BseItem *bitem = bse_container_resolve_upath (bproject, udd.upath.c_str()); assert_return (bitem != NULL, nullitem); // undo descriptor for NULL objects is not currently supported return *bitem->as<ItemImpl*>(); } static void undo_lambda_free (BseUndoStep *ustep) { delete (ItemImpl::UndoDescriptor<ItemImpl>*) ustep->data[0].v_pointer; delete (ItemImpl::UndoLambda*) ustep->data[1].v_pointer; delete (String*) ustep->data[2].v_pointer; } static void undo_lambda_call (BseUndoStep *ustep, BseUndoStack *ustack) { ProjectImpl &project = *ustack->project->as<ProjectImpl*>(); ItemImpl &self = project.undo_resolve (*(ItemImpl::UndoDescriptor<ItemImpl>*) ustep->data[0].v_pointer); auto *lambda = (ItemImpl::UndoLambda*) ustep->data[1].v_pointer; // invoke undo function const Bse::Error error = (*lambda) (self, ustack); if (error != 0) // undo errors shouldn't happen { String *blurb = (String*) ustep->data[2].v_pointer; Bse::warning ("error during undo '%s' of item %s: %s", blurb->c_str(), self.debug_name().c_str(), bse_error_blurb (error)); } } void ItemImpl::push_item_undo (const String &blurb, const UndoLambda &lambda) { BseItem *self = as<BseItem*>(); BseUndoStack *ustack = bse_item_undo_open (self, "undo: %s", blurb.c_str()); if (BSE_UNDO_STACK_VOID (ustack) || BSE_ITEM_INTERNAL (self)) { bse_item_undo_close (ustack); return; } BseUndoStep *ustep = bse_undo_step_new (undo_lambda_call, undo_lambda_free, 3); ustep->data[0].v_pointer = new UndoDescriptor<ItemImpl> (undo_descriptor (*this)); ustep->data[1].v_pointer = new UndoLambda (lambda); ustep->data[2].v_pointer = new String (blurb); bse_undo_stack_push (ustack, ustep); bse_item_undo_close (ustack); } void ItemImpl::push_property_undo (const String &property_name) { assert_return (property_name.empty() == false); Any saved_value = __aida_get__ (property_name); if (saved_value.empty()) Bse::warning ("%s: invalid property name: %s", __func__, property_name); else { auto lambda = [property_name, saved_value] (ItemImpl &self, BseUndoStack *ustack) -> Error { const bool success = self.__aida_set__ (property_name, saved_value); if (!success) Bse::warning ("%s: failed to undo property change for '%s': %s", __func__, property_name, saved_value.repr()); return Error::NONE; }; push_undo (__func__, *this, lambda); } } ProjectIfaceP ItemImpl::get_project () { BseItem *self = as<BseItem*>(); BseProject *project = bse_item_get_project (self); return project ? project->as<Bse::ProjectIfaceP>() : NULL; } ItemIfaceP ItemImpl::common_ancestor (ItemIface &other) { BseItem *self = as<BseItem*>(); BseItem *bo = other.as<BseItem*>(); BseItem *common = bse_item_common_ancestor (self, bo); return common->as<ItemIfaceP>(); } bool ItemImpl::check_is_a (const String &type_name) { BseItem *self = as<BseItem*>(); const GType type = g_type_from_name (type_name.c_str()); const bool is_a = g_type_is_a (G_OBJECT_TYPE (self), type); return is_a; } void ItemImpl::group_undo (const std::string &name) { BseItem *self = as<BseItem*>(); BseUndoStack *ustack = bse_item_undo_open (self, "item-group-undo"); bse_undo_stack_add_merger (ustack, name.c_str()); bse_item_undo_close (ustack); } void ItemImpl::ungroup_undo () { BseItem *self = as<BseItem*>(); BseUndoStack *ustack = bse_item_undo_open (self, "item-ungroup-undo"); bse_undo_stack_remove_merger (ustack); bse_item_undo_close (ustack); } class CustomIconKey : public DataKey<Icon*> { virtual void destroy (Icon *icon) override { delete icon; } }; static CustomIconKey custom_icon_key; Icon ItemImpl::icon () const { BseItem *self = const_cast<ItemImpl*> (this)->as<BseItem*>(); Icon *icon = get_data (&custom_icon_key); return icon ? *icon : bse_object_get_icon (self); } void ItemImpl::icon (const Icon &icon) { Icon *custom_icon = new Icon (icon); icon_sanitize (custom_icon); if (custom_icon->width != 0) set_data (&custom_icon_key, custom_icon); else { delete custom_icon; delete_data (&custom_icon_key); } } ItemIfaceP ItemImpl::get_parent () { return parent() ? parent()->as<ContainerIfaceP>() : NULL; } int ItemImpl::get_seqid () { BseItem *self = as<BseItem*>(); return bse_item_get_seqid (self); } String ItemImpl::get_type () { BseItem *self = as<BseItem*>(); return g_type_name (G_OBJECT_TYPE (self)); } String ItemImpl::get_type_authors () { BseItem *self = as<BseItem*>(); return bse_type_get_authors (G_OBJECT_TYPE (self)); } String ItemImpl::get_type_blurb () { BseItem *self = as<BseItem*>(); return bse_type_get_blurb (G_OBJECT_TYPE (self)); } String ItemImpl::get_type_license () { BseItem *self = as<BseItem*>(); return bse_type_get_license (G_OBJECT_TYPE (self)); } String ItemImpl::get_type_name () { BseItem *self = as<BseItem*>(); return g_type_name (G_OBJECT_TYPE (self)); } String ItemImpl::get_uname_path () { BseItem *self = as<BseItem*>(); BseProject *project = bse_item_get_project (self); gchar *upath = project ? bse_container_make_upath (BSE_CONTAINER (project), self) : NULL; const String result = upath ? upath : ""; g_free (upath); return result; } String ItemImpl::get_name () { BseItem *self = as<BseItem*>(); return BSE_OBJECT_UNAME (self); } String ItemImpl::get_name_or_type () { BseItem *self = as<BseItem*>(); const char *name = BSE_OBJECT_UNAME (self); const String result = name ? name : BSE_OBJECT_TYPE_NAME (self); return result; } bool ItemImpl::internal () { BseItem *self = as<BseItem*>(); return BSE_ITEM_INTERNAL (self); } PropertyCandidates ItemImpl::get_property_candidates (const String &property_name) { BseItem *self = as<BseItem*>(); PropertyCandidates pc; if (bse_item_get_candidates (self, property_name, pc)) return pc; return PropertyCandidates(); } } // Bse
GNOME/beast
bse/bseitem.cc
C++
lgpl-2.1
44,851
// dummy file needed by the build system because // main is in main.cpp rather than fil-sdk-example.cpp
einon/affymetrix-power-tools
sdk/mas5-stat/example/mas5-stat-example.cpp
C++
lgpl-2.1
104
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.06.12 at 12:19:07 PM EDT // package org.hl7.fhir; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ConstraintSeverity-list. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ConstraintSeverity-list"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="error"/> * &lt;enumeration value="warning"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "ConstraintSeverity-list") @XmlEnum public enum ConstraintSeverityList { /** * If the constraint is violated, the resource is not conformant. * */ @XmlEnumValue("error") ERROR("error"), /** * If the constraint is violated, the resource is conformant, but it is not necessarily following best practice. * */ @XmlEnumValue("warning") WARNING("warning"); private final java.lang.String value; ConstraintSeverityList(java.lang.String v) { value = v; } public java.lang.String value() { return value; } public static ConstraintSeverityList fromValue(java.lang.String v) { for (ConstraintSeverityList c: ConstraintSeverityList.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
attunetc/ehr
src/org/hl7/fhir/ConstraintSeverityList.java
Java
lgpl-2.1
1,835
/** * This file is part of TelepathyQt4 * * @copyright Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/> * @copyright Copyright (C) 2008 Nokia Corporation * @license LGPL 2.1 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/Channel> #include "TelepathyQt4/channel-internal.h" #include "TelepathyQt4/_gen/cli-channel-body.hpp" #include "TelepathyQt4/_gen/cli-channel.moc.hpp" #include "TelepathyQt4/_gen/channel.moc.hpp" #include "TelepathyQt4/_gen/channel-internal.moc.hpp" #include "TelepathyQt4/debug-internal.h" #include "TelepathyQt4/future-internal.h" #include <TelepathyQt4/ChannelFactory> #include <TelepathyQt4/Connection> #include <TelepathyQt4/ConnectionCapabilities> #include <TelepathyQt4/ConnectionLowlevel> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/PendingContacts> #include <TelepathyQt4/PendingFailure> #include <TelepathyQt4/PendingOperation> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/PendingSuccess> #include <TelepathyQt4/StreamTubeChannel> #include <TelepathyQt4/ReferencedHandles> #include <TelepathyQt4/Constants> #include <QHash> #include <QQueue> #include <QSharedData> #include <QTimer> namespace Tp { using TpFuture::Client::ChannelInterfaceMergeableConferenceInterface; using TpFuture::Client::ChannelInterfaceSplittableInterface; struct TELEPATHY_QT4_NO_EXPORT Channel::Private { Private(Channel *parent, const ConnectionPtr &connection, const QVariantMap &immutableProperties); ~Private(); static void introspectMain(Private *self); void introspectMainProperties(); void introspectMainFallbackChannelType(); void introspectMainFallbackHandle(); void introspectMainFallbackInterfaces(); void introspectGroup(); void introspectGroupFallbackFlags(); void introspectGroupFallbackMembers(); void introspectGroupFallbackLocalPendingWithInfo(); void introspectGroupFallbackSelfHandle(); void introspectConference(); static void introspectConferenceInitialInviteeContacts(Private *self); void continueIntrospection(); void extractMainProps(const QVariantMap &props); void extract0176GroupProps(const QVariantMap &props); void nowHaveInterfaces(); void nowHaveInitialMembers(); bool setGroupFlags(uint groupFlags); void buildContacts(); void doMembersChangedDetailed(const UIntList &, const UIntList &, const UIntList &, const UIntList &, const QVariantMap &); void processMembersChanged(); void updateContacts(const QList<ContactPtr> &contacts = QList<ContactPtr>()); bool fakeGroupInterfaceIfNeeded(); void setReady(); QString groupMemberChangeDetailsTelepathyError( const GroupMemberChangeDetails &details); inline ChannelInterfaceMergeableConferenceInterface *mergeableConferenceInterface( InterfaceSupportedChecking check = CheckInterfaceSupported) const { return parent->optionalInterface<ChannelInterfaceMergeableConferenceInterface>(check); } inline ChannelInterfaceSplittableInterface *splittableInterface( InterfaceSupportedChecking check = CheckInterfaceSupported) const { return parent->optionalInterface<ChannelInterfaceSplittableInterface>(check); } void processConferenceChannelRemoved(); struct GroupMembersChangedInfo; struct ConferenceChannelRemovedInfo; // Public object Channel *parent; // Instance of generated interface class Client::ChannelInterface *baseInterface; // Mandatory properties interface proxy Client::DBus::PropertiesInterface *properties; // Owning connection - it can be a SharedPtr as Connection does not cache // channels ConnectionPtr connection; QVariantMap immutableProperties; // Optional interface proxies Client::ChannelInterfaceGroupInterface *group; Client::ChannelInterfaceConferenceInterface *conference; ReadinessHelper *readinessHelper; // Introspection QQueue<void (Private::*)()> introspectQueue; // Introspected properties // Main interface QString channelType; uint targetHandleType; uint targetHandle; QString targetId; ContactPtr targetContact; bool requested; uint initiatorHandle; ContactPtr initiatorContact; // Group flags uint groupFlags; bool usingMembersChangedDetailed; // Group member introspection bool groupHaveMembers; bool buildingContacts; // Queue of received MCD signals to process QQueue<GroupMembersChangedInfo *> groupMembersChangedQueue; GroupMembersChangedInfo *currentGroupMembersChangedInfo; // Pending from the MCD signal currently processed, but contacts not yet built QSet<uint> pendingGroupMembers; QSet<uint> pendingGroupLocalPendingMembers; QSet<uint> pendingGroupRemotePendingMembers; UIntList groupMembersToRemove; UIntList groupLocalPendingMembersToRemove; UIntList groupRemotePendingMembersToRemove; // Initial members UIntList groupInitialMembers; LocalPendingInfoList groupInitialLP; UIntList groupInitialRP; // Current members QHash<uint, ContactPtr> groupContacts; QHash<uint, ContactPtr> groupLocalPendingContacts; QHash<uint, ContactPtr> groupRemotePendingContacts; // Stored change info QHash<uint, GroupMemberChangeDetails> groupLocalPendingContactsChangeInfo; GroupMemberChangeDetails groupSelfContactRemoveInfo; // Group handle owners bool groupAreHandleOwnersAvailable; HandleOwnerMap groupHandleOwners; // Group self identity bool pendingRetrieveGroupSelfContact; bool groupIsSelfHandleTracked; uint groupSelfHandle; ContactPtr groupSelfContact; // Conference bool introspectingConference; QHash<QString, ChannelPtr> conferenceChannels; QHash<QString, ChannelPtr> conferenceInitialChannels; QString conferenceInvitationMessage; QHash<uint, ChannelPtr> conferenceOriginalChannels; UIntList conferenceInitialInviteeHandles; Contacts conferenceInitialInviteeContacts; QQueue<ConferenceChannelRemovedInfo *> conferenceChannelRemovedQueue; bool buildingConferenceChannelRemovedActorContact; static const QString keyActor; }; struct TELEPATHY_QT4_NO_EXPORT Channel::Private::GroupMembersChangedInfo { GroupMembersChangedInfo(const UIntList &added, const UIntList &removed, const UIntList &localPending, const UIntList &remotePending, const QVariantMap &details) : added(added), removed(removed), localPending(localPending), remotePending(remotePending), details(details), // TODO most of these probably should be removed once the rest of the code using them is sanitized actor(qdbus_cast<uint>(details.value(keyActor))), reason(qdbus_cast<uint>(details.value(keyChangeReason))), message(qdbus_cast<QString>(details.value(keyMessage))) { } UIntList added; UIntList removed; UIntList localPending; UIntList remotePending; QVariantMap details; uint actor; uint reason; QString message; static const QString keyChangeReason; static const QString keyMessage; static const QString keyContactIds; }; struct TELEPATHY_QT4_NO_EXPORT Channel::Private::ConferenceChannelRemovedInfo { ConferenceChannelRemovedInfo(const QDBusObjectPath &channelPath, const QVariantMap &details) : channelPath(channelPath), details(details) { } QDBusObjectPath channelPath; QVariantMap details; }; const QString Channel::Private::keyActor(QLatin1String("actor")); const QString Channel::Private::GroupMembersChangedInfo::keyChangeReason( QLatin1String("change-reason")); const QString Channel::Private::GroupMembersChangedInfo::keyMessage(QLatin1String("message")); const QString Channel::Private::GroupMembersChangedInfo::keyContactIds(QLatin1String("contact-ids")); Channel::Private::Private(Channel *parent, const ConnectionPtr &connection, const QVariantMap &immutableProperties) : parent(parent), baseInterface(new Client::ChannelInterface(parent)), properties(parent->interface<Client::DBus::PropertiesInterface>()), connection(connection), immutableProperties(immutableProperties), group(0), conference(0), readinessHelper(parent->readinessHelper()), targetHandleType(0), targetHandle(0), requested(false), initiatorHandle(0), groupFlags(0), usingMembersChangedDetailed(false), groupHaveMembers(false), buildingContacts(false), currentGroupMembersChangedInfo(0), groupAreHandleOwnersAvailable(false), pendingRetrieveGroupSelfContact(false), groupIsSelfHandleTracked(false), groupSelfHandle(0), introspectingConference(false), buildingConferenceChannelRemovedActorContact(false) { debug() << "Creating new Channel:" << parent->objectPath(); if (connection->isValid()) { debug() << " Connecting to Channel::Closed() signal"; parent->connect(baseInterface, SIGNAL(Closed()), SLOT(onClosed())); debug() << " Connection to owning connection's lifetime signals"; parent->connect(connection.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SLOT(onConnectionInvalidated())); } else { warning() << "Connection given as the owner for a Channel was " "invalid! Channel will be stillborn."; parent->invalidate(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT), QLatin1String("Connection given as the owner of this channel was invalid")); } ReadinessHelper::Introspectables introspectables; // As Channel does not have predefined statuses let's simulate one (0) ReadinessHelper::Introspectable introspectableCore( QSet<uint>() << 0, // makesSenseForStatuses Features(), // dependsOnFeatures QStringList(), // dependsOnInterfaces (ReadinessHelper::IntrospectFunc) &Private::introspectMain, this); introspectables[FeatureCore] = introspectableCore; // As Channel does not have predefined statuses let's simulate one (0) ReadinessHelper::Introspectable introspectableConferenceInitialInviteeContacts( QSet<uint>() << 0, // makesSenseForStatuses Features() << FeatureCore, // dependsOnFeatures QStringList() << TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE, // dependsOnInterfaces (ReadinessHelper::IntrospectFunc) &Private::introspectConferenceInitialInviteeContacts, this); introspectables[FeatureConferenceInitialInviteeContacts] = introspectableConferenceInitialInviteeContacts; readinessHelper->addIntrospectables(introspectables); } Channel::Private::~Private() { delete currentGroupMembersChangedInfo; foreach (GroupMembersChangedInfo *info, groupMembersChangedQueue) { delete info; } foreach (ConferenceChannelRemovedInfo *info, conferenceChannelRemovedQueue) { delete info; } } void Channel::Private::introspectMain(Channel::Private *self) { // Make sure connection object is ready, as we need to use some methods that // are only available after connection object gets ready. debug() << "Calling Connection::becomeReady()"; self->parent->connect(self->connection->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onConnectionReady(Tp::PendingOperation*))); } void Channel::Private::introspectMainProperties() { QVariantMap props; QString key; bool needIntrospectMainProps = false; const unsigned numNames = 8; const static QString names[numNames] = { QLatin1String("ChannelType"), QLatin1String("Interfaces"), QLatin1String("TargetHandleType"), QLatin1String("TargetHandle"), QLatin1String("TargetID"), QLatin1String("Requested"), QLatin1String("InitiatorHandle"), QLatin1String("InitiatorID") }; const static QString qualifiedNames[numNames] = { QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Interfaces"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Requested"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".InitiatorHandle"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".InitiatorID") }; for (unsigned i = 0; i < numNames; ++i) { const QString &qualified = qualifiedNames[i]; if (!immutableProperties.contains(qualified)) { needIntrospectMainProps = true; break; } props.insert(names[i], immutableProperties.value(qualified)); } // Save Requested and InitiatorHandle here, so even if the GetAll return doesn't have them but // the given immutable props do (eg. due to the PendingChannel fallback guesses) we use them requested = qdbus_cast<bool>(props[QLatin1String("Requested")]); initiatorHandle = qdbus_cast<uint>(props[QLatin1String("InitiatorHandle")]); if (props.contains(QLatin1String("InitiatorID"))) { QString initiatorId = qdbus_cast<QString>(props[QLatin1String("InitiatorID")]); connection->lowlevel()->injectContactId(initiatorHandle, initiatorId); } if (needIntrospectMainProps) { debug() << "Calling Properties::GetAll(Channel)"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher( properties->GetAll(QLatin1String(TELEPATHY_INTERFACE_CHANNEL)), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotMainProperties(QDBusPendingCallWatcher*))); } else { extractMainProps(props); continueIntrospection(); } } void Channel::Private::introspectMainFallbackChannelType() { debug() << "Calling Channel::GetChannelType()"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(baseInterface->GetChannelType(), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotChannelType(QDBusPendingCallWatcher*))); } void Channel::Private::introspectMainFallbackHandle() { debug() << "Calling Channel::GetHandle()"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(baseInterface->GetHandle(), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotHandle(QDBusPendingCallWatcher*))); } void Channel::Private::introspectMainFallbackInterfaces() { debug() << "Calling Channel::GetInterfaces()"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(baseInterface->GetInterfaces(), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotInterfaces(QDBusPendingCallWatcher*))); } void Channel::Private::introspectGroup() { Q_ASSERT(properties != 0); if (!group) { group = parent->interface<Client::ChannelInterfaceGroupInterface>(); Q_ASSERT(group != 0); } debug() << "Introspecting Channel.Interface.Group for" << parent->objectPath(); parent->connect(group, SIGNAL(GroupFlagsChanged(uint,uint)), SLOT(onGroupFlagsChanged(uint,uint))); parent->connect(group, SIGNAL(MembersChanged(QString,Tp::UIntList, Tp::UIntList,Tp::UIntList, Tp::UIntList,uint,uint)), SLOT(onMembersChanged(QString,Tp::UIntList, Tp::UIntList,Tp::UIntList, Tp::UIntList,uint,uint))); parent->connect(group, SIGNAL(MembersChangedDetailed(Tp::UIntList, Tp::UIntList,Tp::UIntList, Tp::UIntList,QVariantMap)), SLOT(onMembersChangedDetailed(Tp::UIntList, Tp::UIntList,Tp::UIntList, Tp::UIntList,QVariantMap))); parent->connect(group, SIGNAL(HandleOwnersChanged(Tp::HandleOwnerMap, Tp::UIntList)), SLOT(onHandleOwnersChanged(Tp::HandleOwnerMap, Tp::UIntList))); parent->connect(group, SIGNAL(SelfHandleChanged(uint)), SLOT(onSelfHandleChanged(uint))); debug() << "Calling Properties::GetAll(Channel.Interface.Group)"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher( properties->GetAll(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP)), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotGroupProperties(QDBusPendingCallWatcher*))); } void Channel::Private::introspectGroupFallbackFlags() { Q_ASSERT(group != 0); debug() << "Calling Channel.Interface.Group::GetGroupFlags()"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(group->GetGroupFlags(), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotGroupFlags(QDBusPendingCallWatcher*))); } void Channel::Private::introspectGroupFallbackMembers() { Q_ASSERT(group != 0); debug() << "Calling Channel.Interface.Group::GetAllMembers()"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(group->GetAllMembers(), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotAllMembers(QDBusPendingCallWatcher*))); } void Channel::Private::introspectGroupFallbackLocalPendingWithInfo() { Q_ASSERT(group != 0); debug() << "Calling Channel.Interface.Group::GetLocalPendingMembersWithInfo()"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(group->GetLocalPendingMembersWithInfo(), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotLocalPendingMembersWithInfo(QDBusPendingCallWatcher*))); } void Channel::Private::introspectGroupFallbackSelfHandle() { Q_ASSERT(group != 0); debug() << "Calling Channel.Interface.Group::GetSelfHandle()"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(group->GetSelfHandle(), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotSelfHandle(QDBusPendingCallWatcher*))); } void Channel::Private::introspectConference() { Q_ASSERT(properties != 0); Q_ASSERT(conference == 0); debug() << "Introspecting Conference interface"; conference = parent->interface<Client::ChannelInterfaceConferenceInterface>(); Q_ASSERT(conference != 0); introspectingConference = true; debug() << "Connecting to Channel.Interface.Conference.ChannelMerged/Removed"; parent->connect(conference, SIGNAL(ChannelMerged(QDBusObjectPath,uint,QVariantMap)), SLOT(onConferenceChannelMerged(QDBusObjectPath,uint,QVariantMap))); parent->connect(conference, SIGNAL(ChannelRemoved(QDBusObjectPath,QVariantMap)), SLOT(onConferenceChannelRemoved(QDBusObjectPath,QVariantMap))); debug() << "Calling Properties::GetAll(Channel.Interface.Conference)"; QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher( properties->GetAll(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_CONFERENCE)), parent); parent->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), SLOT(gotConferenceProperties(QDBusPendingCallWatcher*))); } void Channel::Private::introspectConferenceInitialInviteeContacts(Private *self) { if (!self->conferenceInitialInviteeHandles.isEmpty()) { ContactManagerPtr manager = self->connection->contactManager(); PendingContacts *pendingContacts = manager->contactsForHandles( self->conferenceInitialInviteeHandles); self->parent->connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation *)), SLOT(gotConferenceInitialInviteeContacts(Tp::PendingOperation *))); } else { self->readinessHelper->setIntrospectCompleted( FeatureConferenceInitialInviteeContacts, true); } } void Channel::Private::continueIntrospection() { if (introspectQueue.isEmpty()) { // this should always be true, but let's make sure if (!parent->isReady(Channel::FeatureCore)) { if (groupMembersChangedQueue.isEmpty() && !buildingContacts && !introspectingConference) { debug() << "Both the IS and the MCD queue empty for the first time. Ready."; setReady(); } else { debug() << "Introspection done before contacts done - contacts sets ready"; } } } else { (this->*(introspectQueue.dequeue()))(); } } void Channel::Private::extractMainProps(const QVariantMap &props) { const static QString keyChannelType(QLatin1String("ChannelType")); const static QString keyInterfaces(QLatin1String("Interfaces")); const static QString keyTargetHandle(QLatin1String("TargetHandle")); const static QString keyTargetHandleType(QLatin1String("TargetHandleType")); bool haveProps = props.size() >= 4 && props.contains(keyChannelType) && !qdbus_cast<QString>(props[keyChannelType]).isEmpty() && props.contains(keyInterfaces) && props.contains(keyTargetHandle) && props.contains(keyTargetHandleType); if (!haveProps) { warning() << "Channel properties specified in 0.17.7 not found"; introspectQueue.enqueue(&Private::introspectMainFallbackChannelType); introspectQueue.enqueue(&Private::introspectMainFallbackHandle); introspectQueue.enqueue(&Private::introspectMainFallbackInterfaces); } else { parent->setInterfaces(qdbus_cast<QStringList>(props[keyInterfaces])); readinessHelper->setInterfaces(parent->interfaces()); channelType = qdbus_cast<QString>(props[keyChannelType]); targetHandle = qdbus_cast<uint>(props[keyTargetHandle]); targetHandleType = qdbus_cast<uint>(props[keyTargetHandleType]); const static QString keyTargetId(QLatin1String("TargetID")); const static QString keyRequested(QLatin1String("Requested")); const static QString keyInitiatorHandle(QLatin1String("InitiatorHandle")); const static QString keyInitiatorId(QLatin1String("InitiatorID")); if (props.contains(keyTargetId)) { targetId = qdbus_cast<QString>(props[keyTargetId]); if (targetHandleType == HandleTypeContact) { connection->lowlevel()->injectContactId(targetHandle, targetId); } } if (props.contains(keyRequested)) { requested = qdbus_cast<uint>(props[keyRequested]); } if (props.contains(keyInitiatorHandle)) { initiatorHandle = qdbus_cast<uint>(props[keyInitiatorHandle]); } if (props.contains(keyInitiatorId)) { QString initiatorId = qdbus_cast<QString>(props[keyInitiatorId]); connection->lowlevel()->injectContactId(initiatorHandle, initiatorId); } if (!fakeGroupInterfaceIfNeeded() && !parent->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP)) && initiatorHandle) { // No group interface, so nobody will build the poor fellow for us. Will do it ourselves // out of pity for him. // TODO: needs testing. I would imagine some of the elaborate updateContacts logic // tripping over with just this. buildContacts(); } nowHaveInterfaces(); } debug() << "Have initiator handle:" << (initiatorHandle ? "yes" : "no"); } void Channel::Private::extract0176GroupProps(const QVariantMap &props) { const static QString keyGroupFlags(QLatin1String("GroupFlags")); const static QString keyHandleOwners(QLatin1String("HandleOwners")); const static QString keyLPMembers(QLatin1String("LocalPendingMembers")); const static QString keyMembers(QLatin1String("Members")); const static QString keyRPMembers(QLatin1String("RemotePendingMembers")); const static QString keySelfHandle(QLatin1String("SelfHandle")); bool haveProps = props.size() >= 6 && (props.contains(keyGroupFlags) && (qdbus_cast<uint>(props[keyGroupFlags]) & ChannelGroupFlagProperties)) && props.contains(keyHandleOwners) && props.contains(keyLPMembers) && props.contains(keyMembers) && props.contains(keyRPMembers) && props.contains(keySelfHandle); if (!haveProps) { warning() << " Properties specified in 0.17.6 not found"; warning() << " Handle owners and self handle tracking disabled"; introspectQueue.enqueue(&Private::introspectGroupFallbackFlags); introspectQueue.enqueue(&Private::introspectGroupFallbackMembers); introspectQueue.enqueue(&Private::introspectGroupFallbackLocalPendingWithInfo); introspectQueue.enqueue(&Private::introspectGroupFallbackSelfHandle); } else { debug() << " Found properties specified in 0.17.6"; groupAreHandleOwnersAvailable = true; groupIsSelfHandleTracked = true; setGroupFlags(qdbus_cast<uint>(props[keyGroupFlags])); groupHandleOwners = qdbus_cast<HandleOwnerMap>(props[keyHandleOwners]); groupInitialMembers = qdbus_cast<UIntList>(props[keyMembers]); groupInitialLP = qdbus_cast<LocalPendingInfoList>(props[keyLPMembers]); groupInitialRP = qdbus_cast<UIntList>(props[keyRPMembers]); uint propSelfHandle = qdbus_cast<uint>(props[keySelfHandle]); // Don't overwrite the self handle we got from the Connection with 0 if (propSelfHandle) { groupSelfHandle = propSelfHandle; } nowHaveInitialMembers(); } } void Channel::Private::nowHaveInterfaces() { debug() << "Channel has" << parent->interfaces().size() << "optional interfaces:" << parent->interfaces(); QStringList interfaces = parent->interfaces(); if (interfaces.contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { introspectQueue.enqueue(&Private::introspectGroup); } if (interfaces.contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_CONFERENCE))) { introspectQueue.enqueue(&Private::introspectConference); } } void Channel::Private::nowHaveInitialMembers() { // Must be called with no contacts anywhere in the first place Q_ASSERT(!parent->isReady(Channel::FeatureCore)); Q_ASSERT(!buildingContacts); Q_ASSERT(pendingGroupMembers.isEmpty()); Q_ASSERT(pendingGroupLocalPendingMembers.isEmpty()); Q_ASSERT(pendingGroupRemotePendingMembers.isEmpty()); Q_ASSERT(groupContacts.isEmpty()); Q_ASSERT(groupLocalPendingContacts.isEmpty()); Q_ASSERT(groupRemotePendingContacts.isEmpty()); // Set groupHaveMembers so we start queueing fresh MCD signals Q_ASSERT(!groupHaveMembers); groupHaveMembers = true; // Synthesize MCD for current + RP groupMembersChangedQueue.enqueue(new GroupMembersChangedInfo( groupInitialMembers, // Members UIntList(), // Removed - obviously, none UIntList(), // LP - will be handled separately, see below groupInitialRP, // Remote pending QVariantMap())); // No details for members + RP // Synthesize one MCD for each initial LP member - they might have different details foreach (const LocalPendingInfo &info, groupInitialLP) { QVariantMap details; if (info.actor != 0) { details.insert(QLatin1String("actor"), info.actor); } if (info.reason != ChannelGroupChangeReasonNone) { details.insert(QLatin1String("change-reason"), info.reason); } if (!info.message.isEmpty()) { details.insert(QLatin1String("message"), info.message); } groupMembersChangedQueue.enqueue(new GroupMembersChangedInfo(UIntList(), UIntList(), UIntList() << info.toBeAdded, UIntList(), details)); } // At least our added MCD event to process processMembersChanged(); } bool Channel::Private::setGroupFlags(uint newGroupFlags) { if (groupFlags == newGroupFlags) { return false; } groupFlags = newGroupFlags; // this shouldn't happen but let's make sure if (!parent->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { return false; } if ((groupFlags & ChannelGroupFlagMembersChangedDetailed) && !usingMembersChangedDetailed) { usingMembersChangedDetailed = true; debug() << "Starting to exclusively listen to MembersChangedDetailed for" << parent->objectPath(); parent->disconnect(group, SIGNAL(MembersChanged(QString,Tp::UIntList, Tp::UIntList,Tp::UIntList, Tp::UIntList,uint,uint)), parent, SLOT(onMembersChanged(QString,Tp::UIntList, Tp::UIntList,Tp::UIntList, Tp::UIntList,uint,uint))); } else if (!(groupFlags & ChannelGroupFlagMembersChangedDetailed) && usingMembersChangedDetailed) { warning() << " Channel service did spec-incompliant removal of MCD from GroupFlags"; usingMembersChangedDetailed = false; parent->connect(group, SIGNAL(MembersChanged(QString,Tp::UIntList, Tp::UIntList,Tp::UIntList, Tp::UIntList,uint,uint)), parent, SLOT(onMembersChanged(QString,Tp::UIntList, Tp::UIntList,Tp::UIntList, Tp::UIntList,uint,uint))); } return true; } void Channel::Private::buildContacts() { buildingContacts = true; ContactManagerPtr manager = connection->contactManager(); UIntList toBuild = QSet<uint>(pendingGroupMembers + pendingGroupLocalPendingMembers + pendingGroupRemotePendingMembers).toList(); if (currentGroupMembersChangedInfo && currentGroupMembersChangedInfo->actor != 0) { toBuild.append(currentGroupMembersChangedInfo->actor); } if (!initiatorContact && initiatorHandle) { // No initiator contact, but Yes initiator handle - might do something about it with just // that information toBuild.append(initiatorHandle); } if (!targetContact && targetHandleType == HandleTypeContact && targetHandle != 0) { toBuild.append(targetHandle); } // always try to retrieve selfContact and check if it changed on // updateContacts or on gotContacts, in case we were not able to retrieve it if (groupSelfHandle) { toBuild.append(groupSelfHandle); } // group self handle changed to 0 <- strange but it may happen, and contacts // were being built at the time, so check now if (toBuild.isEmpty()) { if (!groupSelfHandle && groupSelfContact) { groupSelfContact.reset(); if (parent->isReady(Channel::FeatureCore)) { emit parent->groupSelfContactChanged(); } } buildingContacts = false; return; } PendingContacts *pendingContacts = manager->contactsForHandles( toBuild); parent->connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation*)), SLOT(gotContacts(Tp::PendingOperation*))); } void Channel::Private::processMembersChanged() { Q_ASSERT(!buildingContacts); if (groupMembersChangedQueue.isEmpty()) { if (pendingRetrieveGroupSelfContact) { pendingRetrieveGroupSelfContact = false; // nothing queued but selfContact changed buildContacts(); return; } if (!parent->isReady(Channel::FeatureCore)) { if (introspectQueue.isEmpty()) { debug() << "Both the MCD and the introspect queue empty for the first time. Ready!"; if (initiatorHandle && !initiatorContact) { warning() << " Unable to create contact object for initiator with handle" << initiatorHandle; } if (targetHandleType == HandleTypeContact && targetHandle != 0 && !targetContact) { warning() << " Unable to create contact object for target with handle" << targetHandle; } if (groupSelfHandle && !groupSelfContact) { warning() << " Unable to create contact object for self handle" << groupSelfHandle; } continueIntrospection(); } else { debug() << "Contact queue empty but introspect queue isn't. IS will set ready."; } } return; } Q_ASSERT(pendingGroupMembers.isEmpty()); Q_ASSERT(pendingGroupLocalPendingMembers.isEmpty()); Q_ASSERT(pendingGroupRemotePendingMembers.isEmpty()); // always set this to false here, as buildContacts will always try to // retrieve the selfContact and updateContacts will check if the built // contact is the same as the current contact. pendingRetrieveGroupSelfContact = false; currentGroupMembersChangedInfo = groupMembersChangedQueue.dequeue(); foreach (uint handle, currentGroupMembersChangedInfo->added) { if (!groupContacts.contains(handle)) { pendingGroupMembers.insert(handle); } // the member was added to current members, check if it was in the // local/pending lists and if true, schedule for removal from that list if (groupLocalPendingContacts.contains(handle)) { groupLocalPendingMembersToRemove.append(handle); } else if(groupRemotePendingContacts.contains(handle)) { groupRemotePendingMembersToRemove.append(handle); } } foreach (uint handle, currentGroupMembersChangedInfo->localPending) { if (!groupLocalPendingContacts.contains(handle)) { pendingGroupLocalPendingMembers.insert(handle); } } foreach (uint handle, currentGroupMembersChangedInfo->remotePending) { if (!groupRemotePendingContacts.contains(handle)) { pendingGroupRemotePendingMembers.insert(handle); } } foreach (uint handle, currentGroupMembersChangedInfo->removed) { groupMembersToRemove.append(handle); } // Always go through buildContacts - we might have a self/initiator/whatever handle to build buildContacts(); } void Channel::Private::updateContacts(const QList<ContactPtr> &contacts) { Contacts groupContactsAdded; Contacts groupLocalPendingContactsAdded; Contacts groupRemotePendingContactsAdded; ContactPtr actorContact; bool selfContactUpdated = false; debug() << "Entering Chan::Priv::updateContacts() with" << contacts.size() << "contacts"; // FIXME: simplify. Some duplication of logic present. foreach (ContactPtr contact, contacts) { uint handle = contact->handle()[0]; if (pendingGroupMembers.contains(handle)) { groupContactsAdded.insert(contact); groupContacts[handle] = contact; } else if (pendingGroupLocalPendingMembers.contains(handle)) { groupLocalPendingContactsAdded.insert(contact); groupLocalPendingContacts[handle] = contact; // FIXME: should set the details and actor here too groupLocalPendingContactsChangeInfo[handle] = GroupMemberChangeDetails(); } else if (pendingGroupRemotePendingMembers.contains(handle)) { groupRemotePendingContactsAdded.insert(contact); groupRemotePendingContacts[handle] = contact; } if (groupSelfHandle == handle && groupSelfContact != contact) { groupSelfContact = contact; selfContactUpdated = true; } if (!initiatorContact && initiatorHandle == handle) { // No initiator contact stored, but there's a contact for the initiator handle // We can use that! initiatorContact = contact; } if (!targetContact && targetHandleType == HandleTypeContact && targetHandle == handle) { targetContact = contact; if (targetId.isEmpty()) { // For some reason, TargetID was missing from the property map. We can initialize it // here in that case. targetId = targetContact->id(); } } if (currentGroupMembersChangedInfo && currentGroupMembersChangedInfo->actor == contact->handle()[0]) { actorContact = contact; } } if (!groupSelfHandle && groupSelfContact) { groupSelfContact.reset(); selfContactUpdated = true; } pendingGroupMembers.clear(); pendingGroupLocalPendingMembers.clear(); pendingGroupRemotePendingMembers.clear(); // FIXME: This shouldn't be needed. Clearer would be to first scan for the actor being present // in the contacts supplied. foreach (ContactPtr contact, contacts) { uint handle = contact->handle()[0]; if (groupLocalPendingContactsChangeInfo.contains(handle)) { groupLocalPendingContactsChangeInfo[handle] = GroupMemberChangeDetails(actorContact, currentGroupMembersChangedInfo ? currentGroupMembersChangedInfo->details : QVariantMap()); } } Contacts groupContactsRemoved; ContactPtr contactToRemove; foreach (uint handle, groupMembersToRemove) { if (groupContacts.contains(handle)) { contactToRemove = groupContacts[handle]; groupContacts.remove(handle); } else if (groupLocalPendingContacts.contains(handle)) { contactToRemove = groupLocalPendingContacts[handle]; groupLocalPendingContacts.remove(handle); } else if (groupRemotePendingContacts.contains(handle)) { contactToRemove = groupRemotePendingContacts[handle]; groupRemotePendingContacts.remove(handle); } if (groupLocalPendingContactsChangeInfo.contains(handle)) { groupLocalPendingContactsChangeInfo.remove(handle); } if (contactToRemove) { groupContactsRemoved.insert(contactToRemove); } } groupMembersToRemove.clear(); // FIXME: drop the LPToRemove and RPToRemove sets - they're redundant foreach (uint handle, groupLocalPendingMembersToRemove) { groupLocalPendingContacts.remove(handle); } groupLocalPendingMembersToRemove.clear(); foreach (uint handle, groupRemotePendingMembersToRemove) { groupRemotePendingContacts.remove(handle); } groupRemotePendingMembersToRemove.clear(); if (!groupContactsAdded.isEmpty() || !groupLocalPendingContactsAdded.isEmpty() || !groupRemotePendingContactsAdded.isEmpty() || !groupContactsRemoved.isEmpty()) { GroupMemberChangeDetails details( actorContact, currentGroupMembersChangedInfo ? currentGroupMembersChangedInfo->details : QVariantMap()); if (currentGroupMembersChangedInfo && currentGroupMembersChangedInfo->removed.contains(groupSelfHandle)) { // Update groupSelfContactRemoveInfo with the proper actor in case // the actor was not available by the time onMembersChangedDetailed // was called. groupSelfContactRemoveInfo = details; } if (parent->isReady(Channel::FeatureCore)) { // Channel is ready, we can signal membership changes to the outside world without // confusing anyone's fragile logic. emit parent->groupMembersChanged( groupContactsAdded, groupLocalPendingContactsAdded, groupRemotePendingContactsAdded, groupContactsRemoved, details); } } delete currentGroupMembersChangedInfo; currentGroupMembersChangedInfo = 0; if (selfContactUpdated && parent->isReady(Channel::FeatureCore)) { emit parent->groupSelfContactChanged(); } processMembersChanged(); } bool Channel::Private::fakeGroupInterfaceIfNeeded() { if (parent->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { return false; } else if (targetHandleType != HandleTypeContact) { return false; } // fake group interface if (connection->selfHandle() && targetHandle) { // Fake groupSelfHandle and initial members, let the MCD handling take care of the rest // TODO connect to Connection::selfHandleChanged groupSelfHandle = connection->selfHandle(); groupInitialMembers = UIntList() << groupSelfHandle << targetHandle; debug().nospace() << "Faking a group on channel with self handle=" << groupSelfHandle << " and other handle=" << targetHandle; nowHaveInitialMembers(); } else { warning() << "Connection::selfHandle is 0 or targetHandle is 0, " "not faking a group on channel"; } return true; } void Channel::Private::setReady() { Q_ASSERT(!parent->isReady(Channel::FeatureCore)); debug() << "Channel fully ready"; debug() << " Channel type" << channelType; debug() << " Target handle" << targetHandle; debug() << " Target handle type" << targetHandleType; if (parent->interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { debug() << " Group: flags" << groupFlags; if (groupAreHandleOwnersAvailable) { debug() << " Group: Number of handle owner mappings" << groupHandleOwners.size(); } else { debug() << " Group: No handle owners property present"; } debug() << " Group: Number of current members" << groupContacts.size(); debug() << " Group: Number of local pending members" << groupLocalPendingContacts.size(); debug() << " Group: Number of remote pending members" << groupRemotePendingContacts.size(); debug() << " Group: Self handle" << groupSelfHandle << "tracked:" << (groupIsSelfHandleTracked ? "yes" : "no"); } readinessHelper->setIntrospectCompleted(FeatureCore, true); } QString Channel::Private::groupMemberChangeDetailsTelepathyError( const GroupMemberChangeDetails &details) { QString error; uint reason = details.reason(); switch (reason) { case ChannelGroupChangeReasonOffline: error = QLatin1String(TELEPATHY_ERROR_OFFLINE); break; case ChannelGroupChangeReasonKicked: error = QLatin1String(TELEPATHY_ERROR_CHANNEL_KICKED); break; case ChannelGroupChangeReasonBanned: error = QLatin1String(TELEPATHY_ERROR_CHANNEL_BANNED); break; case ChannelGroupChangeReasonBusy: error = QLatin1String(TELEPATHY_ERROR_BUSY); break; case ChannelGroupChangeReasonNoAnswer: error = QLatin1String(TELEPATHY_ERROR_NO_ANSWER); break; case ChannelGroupChangeReasonPermissionDenied: error = QLatin1String(TELEPATHY_ERROR_PERMISSION_DENIED); break; case ChannelGroupChangeReasonInvalidContact: error = QLatin1String(TELEPATHY_ERROR_DOES_NOT_EXIST); break; // The following change reason are being mapped to default // case ChannelGroupChangeReasonNone: // case ChannelGroupChangeReasonInvited: // shouldn't happen // case ChannelGroupChangeReasonError: // case ChannelGroupChangeReasonRenamed: // case ChannelGroupChangeReasonSeparated: // shouldn't happen default: // let's use the actor handle and selfHandle here instead of the // contacts, as the contacts may not be ready. error = ((qdbus_cast<uint>(details.allDetails().value(QLatin1String("actor"))) == groupSelfHandle) ? QLatin1String(TELEPATHY_ERROR_CANCELLED) : QLatin1String(TELEPATHY_ERROR_TERMINATED)); break; } return error; } void Channel::Private::processConferenceChannelRemoved() { if (buildingConferenceChannelRemovedActorContact || conferenceChannelRemovedQueue.isEmpty()) { return; } ConferenceChannelRemovedInfo *info = conferenceChannelRemovedQueue.first(); if (!conferenceChannels.contains(info->channelPath.path())) { info = conferenceChannelRemovedQueue.dequeue(); delete info; processConferenceChannelRemoved(); return; } buildingConferenceChannelRemovedActorContact = true; if (info->details.contains(keyActor)) { ContactManagerPtr manager = connection->contactManager(); PendingContacts *pendingContacts = manager->contactsForHandles( UIntList() << qdbus_cast<uint>(info->details.value(keyActor))); parent->connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation*)), SLOT(gotConferenceChannelRemovedActorContact(Tp::PendingOperation*))); } else { parent->gotConferenceChannelRemovedActorContact(0); } } struct TELEPATHY_QT4_NO_EXPORT Channel::GroupMemberChangeDetails::Private : public QSharedData { Private(const ContactPtr &actor, const QVariantMap &details) : actor(actor), details(details) {} ContactPtr actor; QVariantMap details; }; /** * \class Channel::GroupMemberChangeDetails * \ingroup clientchannel * \headerfile TelepathyQt4/channel.h <TelepathyQt4/Channel> * * \brief The Channel::GroupMemberChangeDetails class represents the details of a group membership * change. * * Extended information is not always available; this will be reflected by * the return value of isValid(). */ /** * Constructs a new invalid GroupMemberChangeDetails instance. */ Channel::GroupMemberChangeDetails::GroupMemberChangeDetails() { } /** * Copy constructor. */ Channel::GroupMemberChangeDetails::GroupMemberChangeDetails(const GroupMemberChangeDetails &other) : mPriv(other.mPriv) { } /** * Class destructor. */ Channel::GroupMemberChangeDetails::~GroupMemberChangeDetails() { } /** * Assigns all information (validity, details) from other to this. */ Channel::GroupMemberChangeDetails &Channel::GroupMemberChangeDetails::operator=( const GroupMemberChangeDetails &other) { this->mPriv = other.mPriv; return *this; } /** * \fn bool Channel::GroupMemberChangeDetails::isValid() const * * Return whether the details are valid (have actually been received from the service). * * \return \c true if valid, \c false otherwise. */ /** * Return whether the details specify an actor. * * If present, actor() will return the contact object representing the person who made the change. * * \return \c true if the actor is known, \c false otherwise. * \sa actor() */ bool Channel::GroupMemberChangeDetails::hasActor() const { return isValid() && !mPriv->actor.isNull(); } /** * Return the contact object representing the person who made the change (actor), if known. * * \return A pointer to the Contact object, or a null ContactPtr if the actor is unknown. * \sa hasActor() */ ContactPtr Channel::GroupMemberChangeDetails::actor() const { return isValid() ? mPriv->actor : ContactPtr(); } /** * \fn bool Channel::GroupMemberChangeDetails::hasReason() const * * Return whether the details specify the reason for the change. * * \return \c true if the reason is known, \c false otherwise. * \sa reason() */ /** * \fn ChannelGroupChangeReason Channel::GroupMemberChangeDetails::reason() const * * Return the reason for the change, if known. * * \return The change reason as #ChannelGroupChangeReason, or #ChannelGroupChangeReasonNone * if the reason is unknown. * \sa hasReason() */ /** * \fn bool Channel::GroupMemberChangeDetails::hasMessage() const * * Return whether the details specify a human-readable message from the contact represented by * actor() pertaining to the change. * * \return \c true if the message is known, \c false otherwise. * \sa message() */ /** * \fn QString Channel::GroupMemberChangeDetails::message() const * * Return a human-readable message from the contact represented by actor() pertaining to the change, * if known. * * \return The message, or an empty string if the message is unknown. * \sa hasMessage() */ /** * \fn bool Channel::GroupMemberChangeDetails::hasError() const * * Return whether the details specify a D-Bus error describing the change. * * \return \c true if the error is known, \c false otherwise. * \sa error() */ /** * \fn QString Channel::GroupMemberChangeDetails::error() const * * Return the D-Bus error describing the change, if known. * * The D-Bus error provides more specific information than the reason() and should be used if * applicable. * * \return A D-Bus error describing the change, or an empty string if the error is unknown. * \sa hasError() */ /** * \fn bool Channel::GroupMemberChangeDetails::hasDebugMessage() const * * Return whether the details specify a debug message. * * \return \c true if debug message is present, \c false otherwise. * \sa debugMessage() */ /** * \fn QString Channel::GroupMemberChangeDetails::debugMessage() const * * Return the debug message specified by the details, if any. * * The debug message is purely informational, offered for display for bug reporting purposes, and * should not be attempted to be parsed. * * \return The debug message, or an empty string if there is none. * \sa hasDebugMessage() */ /** * Return a map containing all details of the group members change. * * This is useful for accessing domain-specific additional details. * * \return The details of the group members change as QVariantMap. */ QVariantMap Channel::GroupMemberChangeDetails::allDetails() const { return isValid() ? mPriv->details : QVariantMap(); } Channel::GroupMemberChangeDetails::GroupMemberChangeDetails(const ContactPtr &actor, const QVariantMap &details) : mPriv(new Private(actor, details)) { } /** * \class Channel * \ingroup clientchannel * \headerfile TelepathyQt4/channel.h <TelepathyQt4/Channel> * * \brief The Channel class represents a Telepathy channel. * * All communication in the Telepathy framework is carried out via channel * objects. Specialized classes for some specific channel types such as * StreamedMediaChannel, TextChannel, FileTransferChannel are provided. * * The remote object accessor functions on this object (channelType(), targetHandleType(), * and so on) don't make any D-Bus calls; instead, they return/use * values cached from a previous introspection run. The introspection process * populates their values in the most efficient way possible based on what the * service implements. * * To avoid unnecessary D-Bus traffic, some accessors only return valid * information after specific features have been enabled. * For instance, to retrieve the initial invitee contacts in a conference channel, * it is necessary to enable the feature Channel::FeatureConferenceInitialInviteeContacts. * See the individual methods descriptions for more details. * * Channel features can be enabled by constructing a ChannelFactory and enabling * the desired features, and passing it to AccountManager, Account or ClientRegistrar * when creating them as appropriate. However, if a particular * feature is only ever used in a specific circumstance, such as an user opening * some settings dialog separate from the general view of the application, * features can be later enabled as needed by calling becomeReady() with the additional * features, and waiting for the resulting PendingOperation to finish. * * Each channel is owned by a connection. If the Connection object becomes invalidated * the Channel object will also get invalidated. * * \section chan_usage_sec Usage * * \subsection chan_create_sec Creating a channel object * * Channel objects can be created in various ways, but the preferred way is * trough Account channel creation methods such as Account::ensureTextChat(), * Account::createFileTransfer(), which uses the channel dispatcher. * * If you already know the object path, you can just call create(). * For example: * * \code * * ChannelPtr chan = Channel::create(connection, objectPath, * immutableProperties); * * \endcode * * \subsection chan_ready_sec Making channel ready to use * * A Channel object needs to become ready before usage, meaning that the * introspection process finished and the object accessors can be used. * * To make the object ready, use becomeReady() and wait for the * PendingOperation::finished() signal to be emitted. * * \code * * class MyClass : public QObject * { * QOBJECT * * public: * MyClass(QObject *parent = 0); * ~MyClass() { } * * private Q_SLOTS: * void onChannelReady(Tp::PendingOperation*); * * private: * ChannelPtr chan; * }; * * MyClass::MyClass(const ConnectionPtr &connection, * const QString &objectPath, const QVariantMap &immutableProperties) * : QObject(parent) * chan(Channel::create(connection, objectPath, immutableProperties)) * { * connect(chan->becomeReady(), * SIGNAL(finished(Tp::PendingOperation*)), * SLOT(onChannelReady(Tp::PendingOperation*))); * } * * void MyClass::onChannelReady(Tp::PendingOperation *op) * { * if (op->isError()) { * qWarning() << "Channel cannot become ready:" << * op->errorName() << "-" << op->errorMessage(); * return; * } * * // Channel is now ready * } * * \endcode * * See \ref async_model, \ref shared_ptr */ /** * Feature representing the core that needs to become ready to make the Channel * object usable. * * Note that this feature must be enabled in order to use most Channel methods. * See specific methods documentation for more details. * * When calling isReady(), becomeReady(), this feature is implicitly added * to the requested features. */ const Feature Channel::FeatureCore = Feature(QLatin1String(Channel::staticMetaObject.className()), 0, true); /** * Feature used in order to access the conference initial invitee contacts info. * * \sa conferenceInitialInviteeContacts() */ const Feature Channel::FeatureConferenceInitialInviteeContacts = Feature(QLatin1String(Channel::staticMetaObject.className()), 1, true); /** * Create a new Channel object. * * \param connection Connection owning this channel, and specifying the * service. * \param objectPath The channel object path. * \param immutableProperties The channel immutable properties. * \return A ChannelPtr object pointing to the newly created Channel object. * * \todo \a immutableProperties should be used to populate the corresponding accessors (such as * channelType()) already on construction, not only when making FeatureCore ready (fd.o #41654) */ ChannelPtr Channel::create(const ConnectionPtr &connection, const QString &objectPath, const QVariantMap &immutableProperties) { return ChannelPtr(new Channel(connection, objectPath, immutableProperties, Channel::FeatureCore)); } /** * Construct a new Channel object. * * \param connection Connection owning this channel, and specifying the * service. * \param objectPath The channel object path. * \param immutableProperties The channel immutable properties. * \param coreFeature The core feature of the channel type. The corresponding introspectable should * depend on Channel::FeatureCore. */ Channel::Channel(const ConnectionPtr &connection, const QString &objectPath, const QVariantMap &immutableProperties, const Feature &coreFeature) : StatefulDBusProxy(connection->dbusConnection(), connection->busName(), objectPath, coreFeature), OptionalInterfaceFactory<Channel>(this), mPriv(new Private(this, connection, immutableProperties)) { } /** * Class destructor. */ Channel::~Channel() { delete mPriv; } /** * Return the connection owning this channel. * * \return A pointer to the Connection object. */ ConnectionPtr Channel::connection() const { return mPriv->connection; } /** * Return the immutable properties of the channel. * * If the channel is ready (isReady(Channel::FeatureCore) returns true), the following keys are * guaranteed to be present: * org.freedesktop.Telepathy.Channel.ChannelType, * org.freedesktop.Telepathy.Channel.TargetHandleType, * org.freedesktop.Telepathy.Channel.TargetHandle and * org.freedesktop.Telepathy.Channel.Requested. * * The keys and values in this map are defined by the \telepathy_spec, * or by third-party extensions to that specification. * These are the properties that cannot change over the lifetime of the * channel; they're announced in the result of the request, for efficiency. * * \return The immutable properties as QVariantMap. */ QVariantMap Channel::immutableProperties() const { if (isReady(Channel::FeatureCore)) { QString key; key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"); if (!mPriv->immutableProperties.contains(key)) { mPriv->immutableProperties.insert(key, mPriv->channelType); } key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Interfaces"); if (!mPriv->immutableProperties.contains(key)) { mPriv->immutableProperties.insert(key, interfaces()); } key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"); if (!mPriv->immutableProperties.contains(key)) { mPriv->immutableProperties.insert(key, mPriv->targetHandleType); } key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"); if (!mPriv->immutableProperties.contains(key)) { mPriv->immutableProperties.insert(key, mPriv->targetHandle); } key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID"); if (!mPriv->immutableProperties.contains(key)) { mPriv->immutableProperties.insert(key, mPriv->targetId); } key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Requested"); if (!mPriv->immutableProperties.contains(key)) { mPriv->immutableProperties.insert(key, mPriv->requested); } key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".InitiatorHandle"); if (!mPriv->immutableProperties.contains(key)) { mPriv->immutableProperties.insert(key, mPriv->initiatorHandle); } key = QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".InitiatorID"); if (!mPriv->immutableProperties.contains(key) && !mPriv->initiatorContact.isNull()) { mPriv->immutableProperties.insert(key, mPriv->initiatorContact->id()); } } return mPriv->immutableProperties; } /** * Return the D-Bus interface name for the type of this channel. * * This method requires Channel::FeatureCore to be ready. * * \return The D-Bus interface name for the type of the channel. */ QString Channel::channelType() const { // Similarly, we don't want warnings triggered when using the type interface // proxies internally. if (!isReady(Channel::FeatureCore) && mPriv->channelType.isEmpty()) { warning() << "Channel::channelType() before the channel type has " "been received"; } else if (!isValid()) { warning() << "Channel::channelType() used with channel closed"; } return mPriv->channelType; } /** * Return the type of the handle returned by targetHandle() as specified in * #HandleType. * * This method requires Channel::FeatureCore to be ready. * * \return The target handle type as #HandleType. * \sa targetHandle(), targetId() */ HandleType Channel::targetHandleType() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::targetHandleType() used channel not ready"; } return (HandleType) mPriv->targetHandleType; } /** * Return the handle of the remote party with which this channel * communicates. * * This method requires Channel::FeatureCore to be ready. * * \return An integer representing the target handle, which is of the type * targetHandleType() indicates. * \sa targetHandleType(), targetId() */ uint Channel::targetHandle() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::targetHandle() used channel not ready"; } return mPriv->targetHandle; } /** * Return the persistent unique ID of the remote party with which this channel communicates. * * If targetHandleType() is #HandleTypeContact, this will be the ID of the remote contact, and * similarly the unique ID of the room when targetHandleType() is #HandleTypeRoom. * * This is not necessarily the best identifier to display to the user, though. In particular, for * contacts, their alias should be displayed instead. It can be used for matching channels and UI * elements for them across reconnects, though, at which point the old channels and contacts are * invalidated. * * This method requires Channel::FeatureCore to be ready. * * \return The target identifier. * \sa targetHandle(), targetContact() */ QString Channel::targetId() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::targetId() used, but the channel is not ready"; } return mPriv->targetId; } /** * Return the contact with which this channel communicates for its lifetime, if applicable. * * This method requires Channel::FeatureCore to be ready. * * \return A pointer to the Contact object, or a null ContactPtr if targetHandleType() is not * #HandleTypeContact. * \sa targetHandle(), targetId() */ ContactPtr Channel::targetContact() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::targetContact() used, but the channel is not ready"; } else if (targetHandleType() != HandleTypeContact) { warning() << "Channel::targetContact() used with targetHandleType() != Contact"; } return mPriv->targetContact; } /** * Return whether this channel was created in response to a * local request. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if the channel was created in response to a local request, * \c false otherwise. */ bool Channel::isRequested() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::isRequested() used channel not ready"; } return mPriv->requested; } /** * Return the contact who initiated this channel. * * This method requires Channel::FeatureCore to be ready. * * \return A pointer to the Contact object representing the contact who initiated the channel, * or a null ContactPtr if it can't be retrieved. */ ContactPtr Channel::initiatorContact() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::initiatorContact() used channel not ready"; } return mPriv->initiatorContact; } /** * Start an asynchronous request that this channel be closed. * * The returned PendingOperation object will signal the success or failure * of this request; under normal circumstances, it can be expected to * succeed. * * \return A PendingOperation which will emit PendingOperation::finished * when the call has finished. * \sa requestLeave() */ PendingOperation *Channel::requestClose() { // Closing a channel does not make sense if it is already closed, // just silently Return. if (!isValid()) { return new PendingSuccess(ChannelPtr(this)); } return new PendingVoid(mPriv->baseInterface->Close(), ChannelPtr(this)); } Channel::PendingLeave::PendingLeave(const ChannelPtr &chan, const QString &message, ChannelGroupChangeReason reason) : PendingOperation(chan) { Q_ASSERT(chan->mPriv->group != NULL); QDBusPendingCall call = chan->mPriv->group->RemoveMembersWithReason( UIntList() << chan->mPriv->groupSelfHandle, message, reason); connect(chan.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), this, SLOT(onChanInvalidated(Tp::DBusProxy*))); connect(new PendingVoid(call, chan), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onRemoveFinished(Tp::PendingOperation*))); } void Channel::PendingLeave::onChanInvalidated(Tp::DBusProxy *proxy) { if (isFinished()) { return; } debug() << "Finishing PendingLeave successfully as the channel was invalidated"; setFinished(); } void Channel::PendingLeave::onRemoveFinished(Tp::PendingOperation *op) { if (isFinished()) { return; } ChannelPtr chan = ChannelPtr::staticCast(_object()); if (op->isValid()) { debug() << "We left the channel" << chan->objectPath(); ContactPtr c = chan->groupSelfContact(); if (chan->groupContacts().contains(c) || chan->groupLocalPendingContacts().contains(c) || chan->groupRemotePendingContacts().contains(c)) { debug() << "Waiting for self remove to be picked up"; connect(chan.data(), SIGNAL(groupMembersChanged(Tp::Contacts,Tp::Contacts,Tp::Contacts,Tp::Contacts, Tp::Channel::GroupMemberChangeDetails)), this, SLOT(onMembersChanged(Tp::Contacts,Tp::Contacts,Tp::Contacts,Tp::Contacts))); } else { setFinished(); } return; } debug() << "Leave RemoveMembersWithReason failed with " << op->errorName() << op->errorMessage() << "- falling back to Close"; // If the channel has been closed or otherwise invalidated already in this mainloop iteration, // the requestClose() operation will early-succeed connect(chan->requestClose(), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onCloseFinished(Tp::PendingOperation*))); } void Channel::PendingLeave::onMembersChanged(const Tp::Contacts &, const Tp::Contacts &, const Tp::Contacts &, const Tp::Contacts &removed) { if (isFinished()) { return; } ChannelPtr chan = ChannelPtr::staticCast(_object()); ContactPtr c = chan->groupSelfContact(); if (removed.contains(c)) { debug() << "Leave event picked up for" << chan->objectPath(); setFinished(); } } void Channel::PendingLeave::onCloseFinished(Tp::PendingOperation *op) { if (isFinished()) { return; } ChannelPtr chan = ChannelPtr::staticCast(_object()); if (op->isError()) { warning() << "Closing the channel" << chan->objectPath() << "as a fallback for leaving it failed with" << op->errorName() << op->errorMessage() << "- so didn't leave"; setFinishedWithError(op->errorName(), op->errorMessage()); } else { debug() << "We left (by closing) the channel" << chan->objectPath(); setFinished(); } } /** * Start an asynchronous request to leave this channel as gracefully as possible. * * If leaving any more gracefully is not possible, this will revert to the same as requestClose(). * In particular, this will be the case for channels with no group interface * (#TP_QT4_IFACE_CHANNEL_INTERFACE_GROUP not in the list returned by interfaces()). * * The returned PendingOperation object will signal the success or failure * of this request; under normal circumstances, it can be expected to * succeed. * * A message and a reason may be provided along with the request, which will be sent to the server * if supported, which is indicated by #ChannelGroupFlagMessageDepart and/or * #ChannelGroupFlagMessageReject. * * Attempting to leave again when we have already left, either by our request or forcibly, will be a * no-op, with the returned PendingOperation immediately finishing successfully. * * \param message The message, which can be blank if desired. * \param reason A reason for leaving. * \return A PendingOperation which will emit PendingOperation::finished * when the call has finished. */ PendingOperation *Channel::requestLeave(const QString &message, ChannelGroupChangeReason reason) { // Leaving a channel does not make sense if it is already closed, // just silently Return. if (!isValid()) { return new PendingSuccess(ChannelPtr(this)); } if (!isReady(Channel::FeatureCore)) { return new PendingFailure(TP_QT4_ERROR_NOT_AVAILABLE, QLatin1String("Channel::FeatureCore must be ready to leave a channel"), ChannelPtr(this)); } if (!interfaces().contains(TP_QT4_IFACE_CHANNEL_INTERFACE_GROUP)) { return requestClose(); } ContactPtr self = groupSelfContact(); if (!groupContacts().contains(self) && !groupLocalPendingContacts().contains(self) && !groupRemotePendingContacts().contains(self)) { debug() << "Channel::requestLeave() called for " << objectPath() << "which we aren't a member of"; return new PendingSuccess(ChannelPtr(this)); } return new PendingLeave(ChannelPtr(this), message, reason); } /** * \name Group interface * * Cached access to state of the group interface on the associated remote * object, if the interface is present. * * Some methods can be used when targetHandleType() == #HandleTypeContact, such * as groupFlags(), groupCanAddContacts(), groupCanRemoveContacts(), * groupSelfContact() and groupContacts(). * * As the group interface state can change freely during the lifetime of the * channel due to events like new contacts joining the group, the cached state * is automatically kept in sync with the remote object's state by hooking * to the change notification signals present in the D-Bus interface. * * As the cached value changes, change notification signals are emitted. * * Signals such as groupMembersChanged(), groupSelfContactChanged(), etc., are emitted to * indicate that properties have changed. * * Check the individual signals' descriptions for details. */ //@{ /** * Return a set of flags indicating the capabilities and behaviour of the * group on this channel. * * Change notification is via the groupFlagsChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return The bitfield combination of flags as #ChannelGroupFlags. * \sa groupFlagsChanged() */ ChannelGroupFlags Channel::groupFlags() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupFlags() used channel not ready"; } return (ChannelGroupFlags) mPriv->groupFlags; } /** * Return whether contacts can be added or invited to this channel. * * Change notification is via the groupCanAddContactsChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if contacts can be added or invited to the channel, * \c false otherwise. * \sa groupFlags(), groupAddContacts() */ bool Channel::groupCanAddContacts() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanAddContacts() used channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagCanAdd; } /** * Return whether a message is expected when adding/inviting contacts, who * are not already members, to this channel. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if a message is expected, \c false otherwise. * \sa groupFlags(), groupAddContacts() */ bool Channel::groupCanAddContactsWithMessage() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanAddContactsWithMessage() used when channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagMessageAdd; } /** * Return whether a message is expected when accepting contacts' requests to * join this channel. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if a message is expected, \c false otherwise. * \sa groupFlags(), groupAddContacts() */ bool Channel::groupCanAcceptContactsWithMessage() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanAcceptContactsWithMessage() used when channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagMessageAccept; } /** * Add contacts to this channel. * * Contacts on the local pending list (those waiting for permission to join * the channel) can always be added. If groupCanAcceptContactsWithMessage() * returns \c true, an optional message is expected when doing this; if not, * the message parameter is likely to be ignored (so the user should not be * asked for a message, and the message parameter should be left empty). * * Other contacts can only be added if groupCanAddContacts() returns \c true. * If groupCanAddContactsWithMessage() returns \c true, an optional message is * expected when doing this, and if not, the message parameter is likely to be * ignored. * * This method requires Channel::FeatureCore to be ready. * * \param contacts Contacts to be added. * \param message A string message, which can be blank if desired. * \return A PendingOperation which will emit PendingOperation::finished * when the call has finished. * \sa groupCanAddContacts(), groupCanAddContactsWithMessage(), groupCanAcceptContactsWithMessage() */ PendingOperation *Channel::groupAddContacts(const QList<ContactPtr> &contacts, const QString &message) { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupAddContacts() used channel not ready"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE), QLatin1String("Channel not ready"), ChannelPtr(this)); } else if (contacts.isEmpty()) { warning() << "Channel::groupAddContacts() used with empty contacts param"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT), QLatin1String("contacts cannot be an empty list"), ChannelPtr(this)); } foreach (const ContactPtr &contact, contacts) { if (!contact) { warning() << "Channel::groupAddContacts() used but contacts param contains " "invalid contact"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT), QLatin1String("Unable to add invalid contacts"), ChannelPtr(this)); } } if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupAddContacts() used with no group interface"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED), QLatin1String("Channel does not support group interface"), ChannelPtr(this)); } UIntList handles; foreach (const ContactPtr &contact, contacts) { handles << contact->handle()[0]; } return new PendingVoid(mPriv->group->AddMembers(handles, message), ChannelPtr(this)); } /** * Return whether contacts in groupRemotePendingContacts() can be removed from * this channel (i.e. whether an invitation can be rescinded). * * Change notification is via the groupCanRescindContactsChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if contacts can be removed, \c false otherwise. * \sa groupFlags(), groupRemoveContacts() */ bool Channel::groupCanRescindContacts() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanRescindContacts() used channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagCanRescind; } /** * Return whether a message is expected when removing contacts who are in * groupRemotePendingContacts() from this channel (i.e. rescinding an * invitation). * * This method requires Channel::FeatureCore to be ready. * * \return \c true if a message is expected, \c false otherwise. * \sa groupFlags(), groupRemoveContacts() */ bool Channel::groupCanRescindContactsWithMessage() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanRescindContactsWithMessage() used when channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagMessageRescind; } /** * Return if contacts in groupContacts() can be removed from this channel. * * Note that contacts in local pending lists, and the groupSelfContact(), can * always be removed from the channel. * * Change notification is via the groupCanRemoveContactsChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if contacts can be removed, \c false otherwise. * \sa groupFlags(), groupRemoveContacts() */ bool Channel::groupCanRemoveContacts() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanRemoveContacts() used channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagCanRemove; } /** * Return whether a message is expected when removing contacts who are in * groupContacts() from this channel. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if a message is expected, \c false otherwise. * \sa groupFlags(), groupRemoveContacts() */ bool Channel::groupCanRemoveContactsWithMessage() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanRemoveContactsWithMessage() used when channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagMessageRemove; } /** * Return whether a message is expected when removing contacts who are in * groupLocalPendingContacts() from this channel (i.e. rejecting a request to * join). * * This method requires Channel::FeatureCore to be ready. * * \return \c true if a message is expected, \c false otherwise. * \sa groupFlags(), groupRemoveContacts() */ bool Channel::groupCanRejectContactsWithMessage() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanRejectContactsWithMessage() used when channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagMessageReject; } /** * Return whether a message is expected when removing the groupSelfContact() * from this channel (i.e. departing from the channel). * * \return \c true if a message is expected, \c false otherwise. * \sa groupFlags(), groupRemoveContacts() */ bool Channel::groupCanDepartWithMessage() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupCanDepartWithMessage() used when channel not ready"; } return mPriv->groupFlags & ChannelGroupFlagMessageDepart; } /** * Remove contacts from this channel. * * Contacts on the local pending list (those waiting for permission to join * the channel) can always be removed. If groupCanRejectContactsWithMessage() * returns \c true, an optional message is expected when doing this; if not, * the message parameter is likely to be ignored (so the user should not be * asked for a message, and the message parameter should be left empty). * * The groupSelfContact() can also always be removed, as a way to leave the * group with an optional departure message and/or departure reason indication. * If groupCanDepartWithMessage() returns \c true, an optional message is * expected when doing this, and if not, the message parameter is likely to * be ignored. * * Contacts in the group can only be removed (e.g. kicked) if * groupCanRemoveContacts() returns \c true. If * groupCanRemoveContactsWithMessage() returns \c true, an optional message is * expected when doing this, and if not, the message parameter is likely to be * ignored. * * Contacts in the remote pending list (those who have been invited to the * channel) can only be removed (have their invitations rescinded) if * groupCanRescindContacts() returns \c true. If * groupCanRescindContactsWithMessage() returns \c true, an optional message is * expected when doing this, and if not, the message parameter is likely to be * ignored. * * This method requires Channel::FeatureCore to be ready. * * \param contacts Contacts to be removed. * \param message A string message, which can be blank if desired. * \param reason Reason of the change, as specified in * #ChannelGroupChangeReason * \return A PendingOperation which will emit PendingOperation::finished * when the call has finished. * \sa groupCanRemoveContacts(), groupCanRemoveContactsWithMessage(), * groupCanRejectContactsWithMessage(), groupCanRescindContacts(), * groupCanRescindContacts(), groupCanRescindContactsWithMessage(), * groupCanDepartWithMessage() */ PendingOperation *Channel::groupRemoveContacts(const QList<ContactPtr> &contacts, const QString &message, ChannelGroupChangeReason reason) { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupRemoveContacts() used channel not ready"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_AVAILABLE), QLatin1String("Channel not ready"), ChannelPtr(this)); } if (contacts.isEmpty()) { warning() << "Channel::groupRemoveContacts() used with empty contacts param"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT), QLatin1String("contacts param cannot be an empty list"), ChannelPtr(this)); } foreach (const ContactPtr &contact, contacts) { if (!contact) { warning() << "Channel::groupRemoveContacts() used but contacts param contains " "invalid contact:"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT), QLatin1String("Unable to remove invalid contacts"), ChannelPtr(this)); } } if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupRemoveContacts() used with no group interface"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED), QLatin1String("Channel does not support group interface"), ChannelPtr(this)); } UIntList handles; foreach (const ContactPtr &contact, contacts) { handles << contact->handle()[0]; } return new PendingVoid( mPriv->group->RemoveMembersWithReason(handles, message, reason), ChannelPtr(this)); } /** * Return the current contacts of the group. * * Change notification is via the groupMembersChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return A set of pointers to the Contact objects. * \sa groupLocalPendingContacts(), groupRemotePendingContacts() */ Contacts Channel::groupContacts() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupMembers() used channel not ready"; } return mPriv->groupContacts.values().toSet(); } /** * Return the contacts currently waiting for local approval to join the * group. * * Change notification is via the groupMembersChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return A set of pointers to the Contact objects. * \sa groupContacts(), groupRemotePendingContacts() */ Contacts Channel::groupLocalPendingContacts() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupLocalPendingContacts() used channel not ready"; } else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupLocalPendingContacts() used with no group interface"; } return mPriv->groupLocalPendingContacts.values().toSet(); } /** * Return the contacts currently waiting for remote approval to join the * group. * * Change notification is via the groupMembersChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return A set of pointers to the Contact objects. * \sa groupContacts(), groupLocalPendingContacts() */ Contacts Channel::groupRemotePendingContacts() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupRemotePendingContacts() used channel not ready"; } else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupRemotePendingContacts() used with no " "group interface"; } return mPriv->groupRemotePendingContacts.values().toSet(); } /** * Return information of a local pending contact change. If * no information is available, an object for which * GroupMemberChangeDetails::isValid() returns <code>false</code> is returned. * * This method requires Channel::FeatureCore to be ready. * * \param contact A Contact object that is on the local pending contacts list. * \return The change info as a GroupMemberChangeDetails object. */ Channel::GroupMemberChangeDetails Channel::groupLocalPendingContactChangeInfo( const ContactPtr &contact) const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupLocalPendingContactChangeInfo() used channel not ready"; } else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupLocalPendingContactChangeInfo() used with no group interface"; } else if (!contact) { warning() << "Channel::groupLocalPendingContactChangeInfo() used with null contact param"; return GroupMemberChangeDetails(); } uint handle = contact->handle()[0]; return mPriv->groupLocalPendingContactsChangeInfo.value(handle); } /** * Return information on the removal of the local user from the group. If * the user hasn't been removed from the group, an object for which * GroupMemberChangeDetails::isValid() returns <code>false</code> is returned. * * This method should be called only after you've left the channel. * This is useful for getting the remove information after missing the * corresponding groupMembersChanged() signal, as the local user being * removed usually causes the channel to be closed. * * The returned information is not guaranteed to be correct if * groupIsSelfHandleTracked() returns false and a self handle change has * occurred on the remote object. * * This method requires Channel::FeatureCore to be ready. * * \return The remove info as a GroupMemberChangeDetails object. */ Channel::GroupMemberChangeDetails Channel::groupSelfContactRemoveInfo() const { // Oftentimes, the channel will be closed as a result from being left - so checking a channel's // self remove info when it has been closed and hence invalidated is valid if (isValid() && !isReady(Channel::FeatureCore)) { warning() << "Channel::groupSelfContactRemoveInfo() used before Channel::FeatureCore is ready"; } else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupSelfContactRemoveInfo() used with " "no group interface"; } return mPriv->groupSelfContactRemoveInfo; } /** * Return whether globally valid handles can be looked up using the * channel-specific handle on this channel using this object. * * Handle owner lookup is only available if: * <ul> * <li>The object is ready * <li>The list returned by interfaces() contains #TP_QT4_IFACE_CHANNEL_INTERFACE_GROUP</li> * <li>The set of flags returned by groupFlags() contains * #GroupFlagProperties and #GroupFlagChannelSpecificHandles</li> * </ul> * * If this function returns \c false, the return value of * groupHandleOwners() is undefined and groupHandleOwnersChanged() will * never be emitted. * * The value returned by this function will stay fixed for the entire time * the object is ready, so no change notification is provided. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if handle owner lookup functionality is available, \c false otherwise. */ bool Channel::groupAreHandleOwnersAvailable() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupAreHandleOwnersAvailable() used channel not ready"; } else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupAreHandleOwnersAvailable() used with " "no group interface"; } return mPriv->groupAreHandleOwnersAvailable; } /** * Return a mapping of handles specific to this channel to globally valid * handles. * * The mapping includes at least all of the channel-specific handles in this * channel's members, local-pending and remote-pending sets as keys. Any * handle not in the keys of this mapping is not channel-specific in this * channel. Handles which are channel-specific, but for which the owner is * unknown, appear in this mapping with 0 as owner. * * Change notification is via the groupHandleOwnersChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return A mapping from group-specific handles to globally valid handles. */ HandleOwnerMap Channel::groupHandleOwners() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupHandleOwners() used channel not ready"; } else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupAreHandleOwnersAvailable() used with no " "group interface"; } else if (!groupAreHandleOwnersAvailable()) { warning() << "Channel::groupAreHandleOwnersAvailable() used, but handle " "owners not available"; } return mPriv->groupHandleOwners; } /** * Return whether the value returned by groupSelfContact() is guaranteed to * accurately represent the local user even after nickname changes, etc. * * This should always be \c true for new services implementing the group interface. * * Older services not providing group properties don't necessarily * emit the SelfHandleChanged signal either, so self contact changes can't be * reliably tracked. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if changes to the self contact are tracked, \c false otherwise. */ bool Channel::groupIsSelfContactTracked() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupIsSelfHandleTracked() used channel not ready"; } else if (!interfaces().contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_INTERFACE_GROUP))) { warning() << "Channel::groupIsSelfHandleTracked() used with " "no group interface"; } return mPriv->groupIsSelfHandleTracked; } /** * Return a Contact object representing the user in the group if at all possible, otherwise a * Contact object representing the user globally. * * Change notification is via the groupSelfContactChanged() signal. * * This method requires Channel::FeatureCore to be ready. * * \return A pointer to the Contact object. */ ContactPtr Channel::groupSelfContact() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupSelfContact() used channel not ready"; } return mPriv->groupSelfContact; } /** * Return whether the local user is in the "local pending" state. This * indicates that the local user needs to take action to accept an invitation, * an incoming call, etc. * * This method requires Channel::FeatureCore to be ready. * * \return \c true if local user is in the channel's local-pending set, \c false otherwise. */ bool Channel::groupSelfHandleIsLocalPending() const { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupSelfHandleIsLocalPending() used when " "channel not ready"; return false; } return mPriv->groupLocalPendingContacts.contains(mPriv->groupSelfHandle); } /** * Attempt to add the local user to this channel. In some channel types, * such as Text and StreamedMedia, this is used to accept an invitation or an * incoming call. * * This method requires Channel::FeatureCore to be ready. * * \return A PendingOperation which will emit PendingOperation::finished * when the call has finished. */ PendingOperation *Channel::groupAddSelfHandle() { if (!isReady(Channel::FeatureCore)) { warning() << "Channel::groupAddSelfHandle() used when channel not " "ready"; return new PendingFailure(QLatin1String(TELEPATHY_ERROR_INVALID_ARGUMENT), QLatin1String("Channel object not ready"), ChannelPtr(this)); } UIntList handles; if (mPriv->groupSelfHandle == 0) { handles << mPriv->connection->selfHandle(); } else { handles << mPriv->groupSelfHandle; } return new PendingVoid( mPriv->group->AddMembers(handles, QLatin1String("")), ChannelPtr(this)); } //@} /** * Return whether this channel implements the conference interface * (#TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE is in the list returned by interfaces()). * * This method requires Channel::FeatureCore to be ready. * * \return \c true if the conference interface is supported, \c false otherwise. */ bool Channel::isConference() const { return hasInterface(TP_QT4_IFACE_CHANNEL_INTERFACE_CONFERENCE); } /** * Return a list of contacts invited to this conference when it was created. * * This method requires Channel::FeatureConferenceInitialInviteeContacts to be ready. * * \return A set of pointers to the Contact objects. */ Contacts Channel::conferenceInitialInviteeContacts() const { return mPriv->conferenceInitialInviteeContacts; } /** * Return the individual channels that are part of this conference. * * Change notification is via the conferenceChannelMerged() and * conferenceChannelRemoved() signals. * * Note that the returned channels are not guaranteed to be ready. Calling * Channel::becomeReady() may be needed. * * This method requires Channel::FeatureCore to be ready. * * \return A list of pointers to Channel objects containing all channels in the conference. * \sa conferenceInitialChannels(), conferenceOriginalChannels() */ QList<ChannelPtr> Channel::conferenceChannels() const { return mPriv->conferenceChannels.values(); } /** * Return the initial value of conferenceChannels(). * * Note that the returned channels are not guaranteed to be ready. Calling * Channel::becomeReady() may be needed. * * This method requires Channel::FeatureCore to be ready. * * \return A list of pointers to Channel objects containing all channels that were initially * part of the conference. * \sa conferenceChannels(), conferenceOriginalChannels() */ QList<ChannelPtr> Channel::conferenceInitialChannels() const { return mPriv->conferenceInitialChannels.values(); } /** * Return a map between channel specific handles and the corresponding channels of this conference. * * This method is only relevant on GSM conference calls where it is possible to have the same phone * number in a conference twice; for instance, it could be the number of a corporate switchboard. * This is represented using channel-specific handles; whether or not a channel uses * channel-specific handles is reported in groupFlags(). The groupHandleOwners() specifies the * mapping from opaque channel-specific handles to actual numbers; this property specifies the * original 1-1 channel corresponding to each channel-specific handle in the conference. * * In protocols where this situation cannot arise, such as XMPP, this method will return an empty * hash. * * Example, consider this situation: * 1. Place a call (with path /call/to/simon) to the contact +441234567890 (which is assigned the * handle h, say), and ask to be put through to Simon McVittie; * 2. Put that call on hold; * 3. Place another call (with path /call/to/jonny) to +441234567890, and ask to be put through to * Jonny Lamb; * 4. Request a new conference channel with initial channels: ['/call/to/simon', '/call/to/jonny']. * * The new channel will have the following properties, for some handles s and j: * * { * groupFlags(): ChannelGroupFlagChannelSpecificHandles | (other flags), * groupMembers(): [self handle, s, j], * groupHandleOwners(): { s: h, j: h }, * conferenceInitialChannels(): ['/call/to/simon', '/call/to/jonny'], * conferenceChannels(): ['/call/to/simon', '/call/to/jonny'], * conferenceOriginalChannels(): { s: '/call/to/simon', j: '/call/to/jonny' }, * # ... * } * * Note that the returned channels are not guaranteed to be ready. Calling * Channel::becomeReady() may be needed. * * This method requires Channel::FeatureCore to be ready. * * \return A map of channel specific handles to pointers to Channel objects. * \sa conferenceChannels(), conferenceInitialChannels() */ QHash<uint, ChannelPtr> Channel::conferenceOriginalChannels() const { return mPriv->conferenceOriginalChannels; } /** * Return whether this channel supports conference merging using conferenceMergeChannel(). * * This method requires Channel::FeatureCore to be ready. * * \return \c true if the interface is supported, \c false otherwise. * \sa conferenceMergeChannel() */ bool Channel::supportsConferenceMerging() const { return interfaces().contains(QLatin1String( TP_FUTURE_INTERFACE_CHANNEL_INTERFACE_MERGEABLE_CONFERENCE)); } /** * Request that the given channel be incorporated into this channel. * * This method requires Channel::FeatureCore to be ready. * * \return A PendingOperation which will emit PendingOperation::finished * when the call has finished. * \sa supportsConferenceMerging() */ PendingOperation *Channel::conferenceMergeChannel(const ChannelPtr &channel) { if (!supportsConferenceMerging()) { return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED), QLatin1String("Channel does not support MergeableConference interface"), ChannelPtr(this)); } return new PendingVoid(mPriv->mergeableConferenceInterface()->Merge( QDBusObjectPath(channel->objectPath())), ChannelPtr(this)); } /** * Return whether this channel supports splitting using conferenceSplitChannel(). * * This method requires Channel::FeatureCore to be ready. * * \return \c true if the interface is supported, \c false otherwise. * \sa conferenceSplitChannel() */ bool Channel::supportsConferenceSplitting() const { return interfaces().contains(QLatin1String( TP_FUTURE_INTERFACE_CHANNEL_INTERFACE_SPLITTABLE)); } /** * Request that this channel is removed from any conference of which it is * a part. * * This method requires Channel::FeatureCore to be ready. * * \return A PendingOperation which will emit PendingOperation::finished * when the call has finished. * \sa supportsConferenceSplitting() */ PendingOperation *Channel::conferenceSplitChannel() { if (!supportsConferenceSplitting()) { return new PendingFailure(QLatin1String(TELEPATHY_ERROR_NOT_IMPLEMENTED), QLatin1String("Channel does not support Splittable interface"), ChannelPtr(this)); } return new PendingVoid(mPriv->splittableInterface()->Split(), ChannelPtr(this)); } /** * Return the Client::ChannelInterface interface proxy object for this channel. * This method is protected since the convenience methods provided by this * class should generally be used instead of calling D-Bus methods * directly. * * \return A pointer to the existing Client::ChannelInterface object for this * Channel object. */ Client::ChannelInterface *Channel::baseInterface() const { return mPriv->baseInterface; } void Channel::gotMainProperties(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<QVariantMap> reply = *watcher; QVariantMap props; if (!reply.isError()) { debug() << "Got reply to Properties::GetAll(Channel)"; props = reply.value(); } else { warning().nospace() << "Properties::GetAll(Channel) failed with " << reply.error().name() << ": " << reply.error().message(); } mPriv->extractMainProps(props); mPriv->continueIntrospection(); } void Channel::gotChannelType(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<QString> reply = *watcher; if (reply.isError()) { warning().nospace() << "Channel::GetChannelType() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead"; invalidate(reply.error()); return; } debug() << "Got reply to fallback Channel::GetChannelType()"; mPriv->channelType = reply.value(); mPriv->continueIntrospection(); } void Channel::gotHandle(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<uint, uint> reply = *watcher; if (reply.isError()) { warning().nospace() << "Channel::GetHandle() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead"; invalidate(reply.error()); return; } debug() << "Got reply to fallback Channel::GetHandle()"; mPriv->targetHandleType = reply.argumentAt<0>(); mPriv->targetHandle = reply.argumentAt<1>(); mPriv->continueIntrospection(); } void Channel::gotInterfaces(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<QStringList> reply = *watcher; if (reply.isError()) { warning().nospace() << "Channel::GetInterfaces() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead"; invalidate(reply.error()); return; } debug() << "Got reply to fallback Channel::GetInterfaces()"; setInterfaces(reply.value()); mPriv->readinessHelper->setInterfaces(interfaces()); mPriv->nowHaveInterfaces(); mPriv->fakeGroupInterfaceIfNeeded(); mPriv->continueIntrospection(); } void Channel::onClosed() { debug() << "Got Channel::Closed"; QString error; QString message; if (mPriv->groupSelfContactRemoveInfo.isValid() && mPriv->groupSelfContactRemoveInfo.hasReason()) { error = mPriv->groupMemberChangeDetailsTelepathyError( mPriv->groupSelfContactRemoveInfo); message = mPriv->groupSelfContactRemoveInfo.message(); } else { error = TP_QT4_ERROR_CANCELLED; message = QLatin1String("channel closed"); } invalidate(error, message); } void Channel::onConnectionReady(PendingOperation *op) { if (op->isError()) { invalidate(op->errorName(), op->errorMessage()); return; } // FIXME: should connect to selfHandleChanged and act accordingly, but that is a PITA for // keeping the Contacts built and even if we don't do it, the new code is better than the // old one anyway because earlier on we just wouldn't have had a self contact. // // besides, the only thing which breaks without connecting in the world likely is if you're // using idle and decide to change your nick, which I don't think we necessarily even have API // to do from tp-qt4 anyway (or did I make idle change the nick when setting your alias? can't // remember) // // Simply put, I just don't care ATM. // Will be overwritten by the group self handle, if we can discover any. Q_ASSERT(!mPriv->groupSelfHandle); mPriv->groupSelfHandle = mPriv->connection->selfHandle(); mPriv->introspectMainProperties(); } void Channel::onConnectionInvalidated() { debug() << "Owning connection died leaving an orphan Channel, " "changing to closed"; invalidate(QLatin1String(TP_QT4_ERROR_ORPHANED), QLatin1String("Connection given as the owner of this channel was invalidated")); } void Channel::gotGroupProperties(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<QVariantMap> reply = *watcher; QVariantMap props; if (!reply.isError()) { debug() << "Got reply to Properties::GetAll(Channel.Interface.Group)"; props = reply.value(); } else { warning().nospace() << "Properties::GetAll(Channel.Interface.Group) " "failed with " << reply.error().name() << ": " << reply.error().message(); } mPriv->extract0176GroupProps(props); // Add extraction (and possible fallbacks) in similar functions, called from here mPriv->continueIntrospection(); } void Channel::gotGroupFlags(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<uint> reply = *watcher; if (reply.isError()) { warning().nospace() << "Channel.Interface.Group::GetGroupFlags() failed with " << reply.error().name() << ": " << reply.error().message(); } else { debug() << "Got reply to fallback Channel.Interface.Group::GetGroupFlags()"; mPriv->setGroupFlags(reply.value()); if (mPriv->groupFlags & ChannelGroupFlagProperties) { warning() << " Reply included ChannelGroupFlagProperties, even " "though properties specified in 0.17.7 didn't work! - unsetting"; mPriv->groupFlags &= ~ChannelGroupFlagProperties; } } mPriv->continueIntrospection(); } void Channel::gotAllMembers(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<UIntList, UIntList, UIntList> reply = *watcher; if (reply.isError()) { warning().nospace() << "Channel.Interface.Group::GetAllMembers() failed with " << reply.error().name() << ": " << reply.error().message(); } else { debug() << "Got reply to fallback Channel.Interface.Group::GetAllMembers()"; mPriv->groupInitialMembers = reply.argumentAt<0>(); mPriv->groupInitialRP = reply.argumentAt<2>(); foreach (uint handle, reply.argumentAt<1>()) { LocalPendingInfo info = {handle, 0, ChannelGroupChangeReasonNone, QLatin1String("")}; mPriv->groupInitialLP.push_back(info); } } mPriv->continueIntrospection(); } void Channel::gotLocalPendingMembersWithInfo(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<LocalPendingInfoList> reply = *watcher; if (reply.isError()) { warning().nospace() << "Channel.Interface.Group::GetLocalPendingMembersWithInfo() " "failed with " << reply.error().name() << ": " << reply.error().message(); warning() << " Falling back to what GetAllMembers returned with no extended info"; } else { debug() << "Got reply to fallback " "Channel.Interface.Group::GetLocalPendingMembersWithInfo()"; // Overrides the previous vague list provided by gotAllMembers mPriv->groupInitialLP = reply.value(); } mPriv->continueIntrospection(); } void Channel::gotSelfHandle(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<uint> reply = *watcher; if (reply.isError()) { warning().nospace() << "Channel.Interface.Group::GetSelfHandle() failed with " << reply.error().name() << ": " << reply.error().message(); } else { debug() << "Got reply to fallback Channel.Interface.Group::GetSelfHandle()"; // Don't overwrite the self handle we got from the connection with 0 if (reply.value()) { mPriv->groupSelfHandle = reply.value(); } } mPriv->nowHaveInitialMembers(); mPriv->continueIntrospection(); } void Channel::gotContacts(PendingOperation *op) { PendingContacts *pending = qobject_cast<PendingContacts *>(op); mPriv->buildingContacts = false; QList<ContactPtr> contacts; if (pending->isValid()) { contacts = pending->contacts(); if (!pending->invalidHandles().isEmpty()) { warning() << "Unable to construct Contact objects for handles:" << pending->invalidHandles(); if (mPriv->groupSelfHandle && pending->invalidHandles().contains(mPriv->groupSelfHandle)) { warning() << "Unable to retrieve self contact"; mPriv->groupSelfContact.reset(); emit groupSelfContactChanged(); } } } else { warning().nospace() << "Getting contacts failed with " << pending->errorName() << ":" << pending->errorMessage(); } mPriv->updateContacts(contacts); } void Channel::onGroupFlagsChanged(uint added, uint removed) { debug().nospace() << "Got Channel.Interface.Group::GroupFlagsChanged(" << hex << added << ", " << removed << ")"; added &= ~(mPriv->groupFlags); removed &= mPriv->groupFlags; debug().nospace() << "Arguments after filtering (" << hex << added << ", " << removed << ")"; uint groupFlags = mPriv->groupFlags; groupFlags |= added; groupFlags &= ~removed; // just emit groupFlagsChanged and related signals if the flags really // changed and we are ready if (mPriv->setGroupFlags(groupFlags) && isReady(Channel::FeatureCore)) { debug() << "Emitting groupFlagsChanged with" << mPriv->groupFlags << "value" << added << "added" << removed << "removed"; emit groupFlagsChanged((ChannelGroupFlags) mPriv->groupFlags, (ChannelGroupFlags) added, (ChannelGroupFlags) removed); if (added & ChannelGroupFlagCanAdd || removed & ChannelGroupFlagCanAdd) { debug() << "Emitting groupCanAddContactsChanged"; emit groupCanAddContactsChanged(groupCanAddContacts()); } if (added & ChannelGroupFlagCanRemove || removed & ChannelGroupFlagCanRemove) { debug() << "Emitting groupCanRemoveContactsChanged"; emit groupCanRemoveContactsChanged(groupCanRemoveContacts()); } if (added & ChannelGroupFlagCanRescind || removed & ChannelGroupFlagCanRescind) { debug() << "Emitting groupCanRescindContactsChanged"; emit groupCanRescindContactsChanged(groupCanRescindContacts()); } } } void Channel::onMembersChanged(const QString &message, const UIntList &added, const UIntList &removed, const UIntList &localPending, const UIntList &remotePending, uint actor, uint reason) { // Ignore the signal if we're using the MCD signal to not duplicate events if (mPriv->usingMembersChangedDetailed) { return; } debug() << "Got Channel.Interface.Group::MembersChanged with" << added.size() << "added," << removed.size() << "removed," << localPending.size() << "moved to LP," << remotePending.size() << "moved to RP," << actor << "being the actor," << reason << "the reason and" << message << "the message"; debug() << " synthesizing a corresponding MembersChangedDetailed signal"; QVariantMap details; if (!message.isEmpty()) { details.insert(QLatin1String("message"), message); } if (actor != 0) { details.insert(QLatin1String("actor"), actor); } details.insert(QLatin1String("change-reason"), reason); mPriv->doMembersChangedDetailed(added, removed, localPending, remotePending, details); } void Channel::onMembersChangedDetailed( const UIntList &added, const UIntList &removed, const UIntList &localPending, const UIntList &remotePending, const QVariantMap &details) { // Ignore the signal if we aren't (yet) using MCD to not duplicate events if (!mPriv->usingMembersChangedDetailed) { return; } debug() << "Got Channel.Interface.Group::MembersChangedDetailed with" << added.size() << "added," << removed.size() << "removed," << localPending.size() << "moved to LP," << remotePending.size() << "moved to RP and with" << details.size() << "details"; mPriv->doMembersChangedDetailed(added, removed, localPending, remotePending, details); } void Channel::Private::doMembersChangedDetailed( const UIntList &added, const UIntList &removed, const UIntList &localPending, const UIntList &remotePending, const QVariantMap &details) { if (!groupHaveMembers) { debug() << "Still waiting for initial group members, " "so ignoring delta signal..."; return; } if (added.isEmpty() && removed.isEmpty() && localPending.isEmpty() && remotePending.isEmpty()) { debug() << "Nothing really changed, so skipping membersChanged"; return; } // let's store groupSelfContactRemoveInfo here as we may not have time // to build the contacts in case self contact is removed, // as Closed will be emitted right after if (removed.contains(groupSelfHandle)) { if (qdbus_cast<uint>(details.value(QLatin1String("change-reason"))) == ChannelGroupChangeReasonRenamed) { if (removed.size() != 1 || (added.size() + localPending.size() + remotePending.size()) != 1) { // spec-incompliant CM, ignoring members changed warning() << "Received MembersChangedDetailed with reason " "Renamed and removed.size != 1 or added.size + " "localPending.size + remotePending.size != 1. Ignoring"; return; } uint newHandle = 0; if (!added.isEmpty()) { newHandle = added.first(); } else if (!localPending.isEmpty()) { newHandle = localPending.first(); } else if (!remotePending.isEmpty()) { newHandle = remotePending.first(); } parent->onSelfHandleChanged(newHandle); return; } // let's try to get the actor contact from contact manager if available groupSelfContactRemoveInfo = GroupMemberChangeDetails( connection->contactManager()->lookupContactByHandle( qdbus_cast<uint>(details.value(QLatin1String("actor")))), details); } HandleIdentifierMap contactIds = qdbus_cast<HandleIdentifierMap>( details.value(GroupMembersChangedInfo::keyContactIds)); connection->lowlevel()->injectContactIds(contactIds); groupMembersChangedQueue.enqueue( new Private::GroupMembersChangedInfo( added, removed, localPending, remotePending, details)); if (!buildingContacts) { // if we are building contacts, we should wait it to finish so we don't // present the user with wrong information processMembersChanged(); } } void Channel::onHandleOwnersChanged(const HandleOwnerMap &added, const UIntList &removed) { debug() << "Got Channel.Interface.Group::HandleOwnersChanged with" << added.size() << "added," << removed.size() << "removed"; if (!mPriv->groupAreHandleOwnersAvailable) { debug() << "Still waiting for initial handle owners, so ignoring " "delta signal..."; return; } UIntList emitAdded; UIntList emitRemoved; for (HandleOwnerMap::const_iterator i = added.begin(); i != added.end(); ++i) { uint handle = i.key(); uint global = i.value(); if (!mPriv->groupHandleOwners.contains(handle) || mPriv->groupHandleOwners[handle] != global) { debug() << " +++/changed" << handle << "->" << global; mPriv->groupHandleOwners[handle] = global; emitAdded.append(handle); } } foreach (uint handle, removed) { if (mPriv->groupHandleOwners.contains(handle)) { debug() << " ---" << handle; mPriv->groupHandleOwners.remove(handle); emitRemoved.append(handle); } } // just emit groupHandleOwnersChanged if it really changed and // we are ready if ((emitAdded.size() || emitRemoved.size()) && isReady(Channel::FeatureCore)) { debug() << "Emitting groupHandleOwnersChanged with" << emitAdded.size() << "added" << emitRemoved.size() << "removed"; emit groupHandleOwnersChanged(mPriv->groupHandleOwners, emitAdded, emitRemoved); } } void Channel::onSelfHandleChanged(uint selfHandle) { debug().nospace() << "Got Channel.Interface.Group::SelfHandleChanged"; if (selfHandle != mPriv->groupSelfHandle) { mPriv->groupSelfHandle = selfHandle; debug() << " Emitting groupSelfHandleChanged with new self handle" << selfHandle; // FIXME: fix self contact building with no group mPriv->pendingRetrieveGroupSelfContact = true; } } void Channel::gotConferenceProperties(QDBusPendingCallWatcher *watcher) { QDBusPendingReply<QVariantMap> reply = *watcher; QVariantMap props; mPriv->introspectingConference = false; if (!reply.isError()) { debug() << "Got reply to Properties::GetAll(Channel.Interface.Conference)"; props = reply.value(); ConnectionPtr conn = connection(); ChannelFactoryConstPtr chanFactory = conn->channelFactory(); ObjectPathList channels = qdbus_cast<ObjectPathList>(props[QLatin1String("Channels")]); foreach (const QDBusObjectPath &channelPath, channels) { if (mPriv->conferenceChannels.contains(channelPath.path())) { continue; } PendingReady *readyOp = chanFactory->proxy(conn, channelPath.path(), QVariantMap()); ChannelPtr channel(ChannelPtr::qObjectCast(readyOp->proxy())); Q_ASSERT(!channel.isNull()); mPriv->conferenceChannels.insert(channelPath.path(), channel); } ObjectPathList initialChannels = qdbus_cast<ObjectPathList>(props[QLatin1String("InitialChannels")]); foreach (const QDBusObjectPath &channelPath, initialChannels) { if (mPriv->conferenceInitialChannels.contains(channelPath.path())) { continue; } PendingReady *readyOp = chanFactory->proxy(conn, channelPath.path(), QVariantMap()); ChannelPtr channel(ChannelPtr::qObjectCast(readyOp->proxy())); Q_ASSERT(!channel.isNull()); mPriv->conferenceInitialChannels.insert(channelPath.path(), channel); } mPriv->conferenceInitialInviteeHandles = qdbus_cast<UIntList>(props[QLatin1String("InitialInviteeHandles")]); QStringList conferenceInitialInviteeIds = qdbus_cast<QStringList>(props[QLatin1String("InitialInviteeIDs")]); if (mPriv->conferenceInitialInviteeHandles.size() == conferenceInitialInviteeIds.size()) { HandleIdentifierMap contactIds; int i = 0; foreach (uint handle, mPriv->conferenceInitialInviteeHandles) { contactIds.insert(handle, conferenceInitialInviteeIds.at(i++)); } mPriv->connection->lowlevel()->injectContactIds(contactIds); } mPriv->conferenceInvitationMessage = qdbus_cast<QString>(props[QLatin1String("InvitationMessage")]); ChannelOriginatorMap originalChannels = qdbus_cast<ChannelOriginatorMap>( props[QLatin1String("OriginalChannels")]); for (ChannelOriginatorMap::const_iterator i = originalChannels.constBegin(); i != originalChannels.constEnd(); ++i) { PendingReady *readyOp = chanFactory->proxy(conn, i.value().path(), QVariantMap()); ChannelPtr channel(ChannelPtr::qObjectCast(readyOp->proxy())); Q_ASSERT(!channel.isNull()); mPriv->conferenceOriginalChannels.insert(i.key(), channel); } } else { warning().nospace() << "Properties::GetAll(Channel.Interface.Conference) " "failed with " << reply.error().name() << ": " << reply.error().message(); } mPriv->continueIntrospection(); } void Channel::gotConferenceInitialInviteeContacts(PendingOperation *op) { PendingContacts *pending = qobject_cast<PendingContacts *>(op); if (pending->isValid()) { mPriv->conferenceInitialInviteeContacts = pending->contacts().toSet(); } else { warning().nospace() << "Getting conference initial invitee contacts " "failed with " << pending->errorName() << ":" << pending->errorMessage(); } mPriv->readinessHelper->setIntrospectCompleted( FeatureConferenceInitialInviteeContacts, true); } void Channel::onConferenceChannelMerged(const QDBusObjectPath &channelPath, uint channelSpecificHandle, const QVariantMap &properties) { if (mPriv->conferenceChannels.contains(channelPath.path())) { return; } ConnectionPtr conn = connection(); ChannelFactoryConstPtr chanFactory = conn->channelFactory(); PendingReady *readyOp = chanFactory->proxy(conn, channelPath.path(), properties); ChannelPtr channel(ChannelPtr::qObjectCast(readyOp->proxy())); Q_ASSERT(!channel.isNull()); mPriv->conferenceChannels.insert(channelPath.path(), channel); emit conferenceChannelMerged(channel); if (channelSpecificHandle != 0) { mPriv->conferenceOriginalChannels.insert(channelSpecificHandle, channel); } } void Channel::onConferenceChannelMerged(const QDBusObjectPath &channelPath) { onConferenceChannelMerged(channelPath, 0, QVariantMap()); } void Channel::onConferenceChannelRemoved(const QDBusObjectPath &channelPath, const QVariantMap &details) { if (!mPriv->conferenceChannels.contains(channelPath.path())) { return; } HandleIdentifierMap contactIds = qdbus_cast<HandleIdentifierMap>( details.value(Private::GroupMembersChangedInfo::keyContactIds)); mPriv->connection->lowlevel()->injectContactIds(contactIds); mPriv->conferenceChannelRemovedQueue.enqueue( new Private::ConferenceChannelRemovedInfo(channelPath, details)); mPriv->processConferenceChannelRemoved(); } void Channel::onConferenceChannelRemoved(const QDBusObjectPath &channelPath) { onConferenceChannelRemoved(channelPath, QVariantMap()); } void Channel::gotConferenceChannelRemovedActorContact(PendingOperation *op) { ContactPtr actorContact; if (op) { PendingContacts *pc = qobject_cast<PendingContacts *>(op); if (pc->isValid()) { Q_ASSERT(pc->contacts().size() == 1); actorContact = pc->contacts().first(); } else { warning().nospace() << "Getting conference channel removed actor " "failed with " << pc->errorName() << ":" << pc->errorMessage(); } } Private::ConferenceChannelRemovedInfo *info = mPriv->conferenceChannelRemovedQueue.dequeue(); ChannelPtr channel = mPriv->conferenceChannels[info->channelPath.path()]; mPriv->conferenceChannels.remove(info->channelPath.path()); emit conferenceChannelRemoved(channel, GroupMemberChangeDetails(actorContact, info->details)); for (QHash<uint, ChannelPtr>::iterator i = mPriv->conferenceOriginalChannels.begin(); i != mPriv->conferenceOriginalChannels.end();) { if (i.value() == channel) { i = mPriv->conferenceOriginalChannels.erase(i); } else { ++i; } } delete info; mPriv->buildingConferenceChannelRemovedActorContact = false; mPriv->processConferenceChannelRemoved(); } /** * \fn void Channel::groupFlagsChanged(uint flags, uint added, uint removed) * * Emitted when the value of groupFlags() changes. * * \param flags The value which would now be returned by groupFlags(). * \param added Flags added compared to the previous value. * \param removed Flags removed compared to the previous value. */ /** * \fn void Channel::groupCanAddContactsChanged(bool canAddContacts) * * Emitted when the value of groupCanAddContacts() changes. * * \param canAddContacts Whether a contact can be added to this channel. * \sa groupCanAddContacts() */ /** * \fn void Channel::groupCanRemoveContactsChanged(bool canRemoveContacts) * * Emitted when the value of groupCanRemoveContacts() changes. * * \param canRemoveContacts Whether a contact can be removed from this channel. * \sa groupCanRemoveContacts() */ /** * \fn void Channel::groupCanRescindContactsChanged(bool canRescindContacts) * * Emitted when the value of groupCanRescindContacts() changes. * * \param canRescindContacts Whether contact invitations can be rescinded. * \sa groupCanRescindContacts() */ /** * \fn void Channel::groupMembersChanged( * const Tp::Contacts &groupMembersAdded, * const Tp::Contacts &groupLocalPendingMembersAdded, * const Tp::Contacts &groupRemotePendingMembersAdded, * const Tp::Contacts &groupMembersRemoved, * const Channel::GroupMemberChangeDetails &details) * * Emitted when the value returned by groupContacts(), groupLocalPendingContacts() or * groupRemotePendingContacts() changes. * * \param groupMembersAdded The contacts that were added to this channel. * \param groupLocalPendingMembersAdded The local pending contacts that were * added to this channel. * \param groupRemotePendingMembersAdded The remote pending contacts that were * added to this channel. * \param groupMembersRemoved The contacts removed from this channel. * \param details Additional details such as the contact requesting or causing * the change. */ /** * \fn void Channel::groupHandleOwnersChanged(const HandleOwnerMap &owners, * const Tp::UIntList &added, const Tp::UIntList &removed) * * Emitted when the value returned by groupHandleOwners() changes. * * \param owners The value which would now be returned by * groupHandleOwners(). * \param added Handles which have been added to the mapping as keys, or * existing handle keys for which the mapped-to value has changed. * \param removed Handles which have been removed from the mapping. */ /** * \fn void Channel::groupSelfContactChanged() * * Emitted when the value returned by groupSelfContact() changes. */ /** * \fn void Channel::conferenceChannelMerged(const Tp::ChannelPtr &channel) * * Emitted when a new channel is added to the value of conferenceChannels(). * * \param channel The channel that was added to conferenceChannels(). */ /** * \fn void Channel::conferenceChannelRemoved(const Tp::ChannelPtr &channel, * const Tp::Channel::GroupMemberChangeDetails &details) * * Emitted when a new channel is removed from the value of conferenceChannels(). * * \param channel The channel that was removed from conferenceChannels(). * \param details The change details. */ } // Tp
Telekinesis/Telepathy-qt4-0.8.0
TelepathyQt4/channel.cpp
C++
lgpl-2.1
130,256
package com.nutz.granola; public class Reference { public static final String MOD_ID = "granola"; public static final String MOD_NAME = "The Granola Mod"; public static final String VERSION = "alpha 0.3"; public static final String CLIENT_PROXY_CLASS = "com.nutz.granola.proxy.ClientProxy"; public static final String SERVER_PROXY_CLASS = "com.nutz.granola.proxy.CommonProxy"; }
Nutzchannel/granola
src/main/java/com/nutz/granola/Reference.java
Java
lgpl-2.1
385
/* * examples/sparsesolverat.C * * Copyright (C) The LinBox Group * ========LICENCE======== * This file is part of the library LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ /**\file examples/sparsesolverat.C @example examples/sparsesolverat.C @author Jean-Guillaume.Dumas@univ-grenoble-alpes.fr * \brief Direct sparse solver over the rationals * \ingroup examples */ #include <iostream> #include "givaro/modular.h" #include "linbox/matrix/sparse-matrix.h" #include "linbox/solutions/solve.h" #include "linbox/util/matrix-stream.h" #include "linbox/solutions/methods.h" using namespace LinBox; template<typename DVector, typename EDom> int rhs(DVector& B, const EDom& DD, bool createB, std::ifstream& invect) { if (createB) { std::cerr << "Creating a random {-1,1} vector " << std::endl; for(auto it=B.begin(); it != B.end(); ++it) if (drand48() <0.5) *it = -1; else *it = 1; } else { for(auto&& it:B) invect >> it; invect.close(); } std::clog << "B is ["; for(auto it:B) DD.write(std::clog, it) << ' '; std::clog << ']' << std::endl; return 0; } int main (int argc, char **argv) { // set 2 to see Q L U P factorization; // see fill-in with 2 and __LINBOX_ALL__ or __LINBOX_FILLIN__ defined commentator().setMaxDetailLevel (1); commentator().setMaxDepth (-1); commentator().setReportStream (std::clog); // commentator().setDefaultReportFile("/dev/stdout"); // to see activities if (argc < 2 || argc > 4) { std::cerr << "Usage: solve <matrix-file-in-supported-format> [<dense-vector-file>] [0/1 <integer solve>]" << std::endl; return 0; } std::ifstream input (argv[1]); if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; } std::ifstream invect; bool createB = false; if (argc == 2) { createB = true; } bool integralsolve=false; if (argc >= 3) { invect.open (argv[2], std::ifstream::in); if (!invect) { createB = true; integralsolve = atoi(argv[2]); } else { createB = false; } } if (argc >= 4) integralsolve = atoi(argv[3]); typedef Givaro::QField<Givaro::Rational> Rats; Rats QQ; typedef DenseVector<Rats> RVector; if (integralsolve) { std::clog << "Integral solving" << std::endl; typedef Givaro::ZRing<Givaro::Integer> Ints; Ints ZZ; typedef DenseVector<Ints> ZVector; MatrixStream<Rats> ms( QQ, input ); size_t nrow, ncol; ms.getDimensions(nrow,ncol); SparseMatrix<Ints> A(ZZ,nrow,ncol); ZVector X(ZZ, A.coldim()),B(ZZ, A.rowdim()); // Read rational matrix and rhs, then compute denominator LCM { SparseMatrix<Rats> RA ( ms ); std::clog << "A is " << RA.rowdim() << " by " << RA.coldim() << std::endl; Givaro::Integer ABlcm(1); for(auto iterow = RA.rowBegin() ; iterow != RA.rowEnd(); ++iterow) { for(auto iter = iterow->begin(); iter != iterow->end(); ++iter) { lcm(ABlcm, ABlcm, iter->second.deno()); } } std::clog << "A denominator lcm: " << ABlcm << std::endl; RVector RB(QQ, RA.rowdim()); rhs(RB, QQ, createB, invect); for(auto iter = RB.begin(); iter != RB.end(); ++iter) { lcm(ABlcm, ABlcm, iter->deno()); } std::clog << "A & B denominator lcm: " << ABlcm << std::endl; // A x = b is equivalent to (l.A) x = (l.b) auto iterow = RA.rowBegin(); auto iterit = A.rowBegin(); for(; iterow != RA.rowEnd(); ++iterow, ++iterit) { for(auto iter = iterow->begin(); iter != iterow->end(); ++iter) { iterit->emplace_back( iter->first, (iter->second.nume() * ABlcm) / iter->second.deno() ); } } auto iter = RB.begin(); auto itez = B.begin(); for( ; iter != RB.end(); ++iter, ++itez) { *itez = (iter->nume() * ABlcm) / iter->deno(); } } Givaro::ZRing<Integer>::Element d; Timer chrono; std::clog << "Integral Sparse Elimination" << std::endl; chrono.start(); solveInPlace (X, d, A, B, Method::SparseElimination()); chrono.stop(); std::cout << "(SparseElimination) Solution is ["; for(auto it:X) ZZ.write(std::cout, it) << ' '; std::cout << "] / "; ZZ.write(std::cout, d)<< std::endl; std::clog << "CPU time (seconds): " << chrono.usertime() << std::endl; } else { MatrixStream<Rats> ms( QQ, input ); SparseMatrix<Rats> A ( ms ); std::clog << "A is " << A.rowdim() << " by " << A.coldim() << std::endl; RVector X(QQ, A.coldim()),B(QQ, A.rowdim()); // Sparse Elimination rhs(B, QQ, createB, invect); Timer chrono; std::clog << "Direct Rational Sparse Elimination" << std::endl; chrono.start(); // @fixme Can't pass a Randiter anymore, we need an API through Method to set seed or such // typename Rats::RandIter generator(QQ,0,BaseTimer::seed() ); // solveInPlace (X, A, B, Method::SparseElimination(), generator); solveInPlace (X, A, B, Method::SparseElimination()); chrono.stop(); std::clog << "(SparseElimination) Solution is ["; for(auto it:X) QQ.write(std::cout, it) << ' '; std::clog << ']' << std::endl; std::clog << "CPU time (seconds): " << chrono.usertime() << std::endl; } return 0; } // Local Variables: // mode: C++ // tab-width: 4 // indent-tabs-mode: nil // c-basic-offset: 4 // End: // vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
linbox-team/linbox
examples/sparsesolverat.C
C++
lgpl-2.1
6,601
/* * Latch integration for Meteor framework * Copyright (C) 2015 Bruno Orcha García <gimcoo@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ Session.setDefault('Meteor._latch.pairing', false); Template._latchAccountLinks.helpers({ isPairing: function() { return Session.get('Meteor._latch.pairing'); }, isPaired: Latch.isPaired }); Template._latchAccountLinks.events({ "click #latch-pair-link" : function (evt, tmpl) { Accounts._loginButtonsSession.resetMessages(); Tracker.flush(); var token = prompt("Open your Latch app and select 'Add a new service'.\nWrite down the token code shown."); if (!token) return; Session.set('Meteor._latch.pairing', true); Latch.pair(token, function(err, res) { Session.set('Meteor._latch.pairing', false); if (err) { Accounts._loginButtonsSession.errorMessage(err.reason); } else { Accounts._loginButtonsSession.infoMessage("Account protected with Latch!"); } }); }, "click #latch-unpair-link" : function (evt, tmpl) { Accounts._loginButtonsSession.resetMessages(); Tracker.flush(); if (!confirm("You're going to disable Latch protection for your account. Are your sure?")) return; Latch.unpair(function(err, res) { if (err) { Accounts._loginButtonsSession.errorMessage(err.reason); } else { Accounts._loginButtonsSession.infoMessage("Account protection disabled."); } }); } }); injectTemplate("_latchAccountLinks", "_loginButtonsLoggedInDropdownActions")
gimco/meteor-accounts-ui-latch
accounts_ui_latch.js
JavaScript
lgpl-2.1
2,278
//===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass implements a simple loop unroller. It works best when loops have // been canonicalized by the -indvars pass, allowing it to determine the trip // counts of loops easily. //===----------------------------------------------------------------------===// #include "llvm/ADT/SetVector.h" #include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/CodeMetrics.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/LoopUnrollAnalyzer.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/InstVisitor.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Metadata.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/LoopUtils.h" #include "llvm/Transforms/Utils/UnrollLoop.h" #include <climits> #include <utility> using namespace llvm; #define DEBUG_TYPE "loop-unroll" static cl::opt<unsigned> UnrollThreshold("unroll-threshold", cl::Hidden, cl::desc("The baseline cost threshold for loop unrolling")); static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold( "unroll-percent-dynamic-cost-saved-threshold", cl::init(50), cl::Hidden, cl::desc("The percentage of estimated dynamic cost which must be saved by " "unrolling to allow unrolling up to the max threshold.")); static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount( "unroll-dynamic-cost-savings-discount", cl::init(100), cl::Hidden, cl::desc("This is the amount discounted from the total unroll cost when " "the unrolled form has a high dynamic cost savings (triggered by " "the '-unroll-perecent-dynamic-cost-saved-threshold' flag).")); static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden, cl::desc("Don't allow loop unrolling to simulate more than this number of" "iterations when checking full unroll profitability")); static cl::opt<unsigned> UnrollCount( "unroll-count", cl::Hidden, cl::desc("Use this unroll count for all loops including those with " "unroll_count pragma values, for testing purposes")); static cl::opt<unsigned> UnrollMaxCount( "unroll-max-count", cl::Hidden, cl::desc("Set the max unroll count for partial and runtime unrolling, for" "testing purposes")); static cl::opt<unsigned> UnrollFullMaxCount( "unroll-full-max-count", cl::Hidden, cl::desc( "Set the max unroll count for full unrolling, for testing purposes")); static cl::opt<bool> UnrollAllowPartial("unroll-allow-partial", cl::Hidden, cl::desc("Allows loops to be partially unrolled until " "-unroll-threshold loop size is reached.")); static cl::opt<bool> UnrollAllowRemainder( "unroll-allow-remainder", cl::Hidden, cl::desc("Allow generation of a loop remainder (extra iterations) " "when unrolling a loop.")); static cl::opt<bool> UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden, cl::desc("Unroll loops with run-time trip counts")); static cl::opt<unsigned> PragmaUnrollThreshold( "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, cl::desc("Unrolled size limit for loops with an unroll(full) or " "unroll_count pragma.")); /// A magic value for use with the Threshold parameter to indicate /// that the loop unroll should be performed regardless of how much /// code expansion would result. static const unsigned NoThreshold = UINT_MAX; /// Default unroll count for loops with run-time trip count if /// -unroll-count is not set static const unsigned DefaultUnrollRuntimeCount = 8; /// Gather the various unrolling parameters based on the defaults, compiler /// flags, TTI overrides and user specified parameters. static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences( Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold, Optional<unsigned> UserCount, Optional<bool> UserAllowPartial, Optional<bool> UserRuntime) { TargetTransformInfo::UnrollingPreferences UP; // Set up the defaults UP.Threshold = 150; UP.PercentDynamicCostSavedThreshold = 50; UP.DynamicCostSavingsDiscount = 100; UP.OptSizeThreshold = 0; UP.PartialThreshold = UP.Threshold; UP.PartialOptSizeThreshold = 0; UP.Count = 0; UP.MaxCount = UINT_MAX; UP.FullUnrollMaxCount = UINT_MAX; UP.Partial = false; UP.Runtime = false; UP.AllowRemainder = true; UP.AllowExpensiveTripCount = false; UP.Force = false; // Override with any target specific settings TTI.getUnrollingPreferences(L, UP); // Apply size attributes if (L->getHeader()->getParent()->optForSize()) { UP.Threshold = UP.OptSizeThreshold; UP.PartialThreshold = UP.PartialOptSizeThreshold; } // Apply any user values specified by cl::opt if (UnrollThreshold.getNumOccurrences() > 0) { UP.Threshold = UnrollThreshold; UP.PartialThreshold = UnrollThreshold; } if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0) UP.PercentDynamicCostSavedThreshold = UnrollPercentDynamicCostSavedThreshold; if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0) UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount; if (UnrollMaxCount.getNumOccurrences() > 0) UP.MaxCount = UnrollMaxCount; if (UnrollFullMaxCount.getNumOccurrences() > 0) UP.FullUnrollMaxCount = UnrollFullMaxCount; if (UnrollAllowPartial.getNumOccurrences() > 0) UP.Partial = UnrollAllowPartial; if (UnrollAllowRemainder.getNumOccurrences() > 0) UP.AllowRemainder = UnrollAllowRemainder; if (UnrollRuntime.getNumOccurrences() > 0) UP.Runtime = UnrollRuntime; // Apply user values provided by argument if (UserThreshold.hasValue()) { UP.Threshold = *UserThreshold; UP.PartialThreshold = *UserThreshold; } if (UserCount.hasValue()) UP.Count = *UserCount; if (UserAllowPartial.hasValue()) UP.Partial = *UserAllowPartial; if (UserRuntime.hasValue()) UP.Runtime = *UserRuntime; return UP; } namespace { /// A struct to densely store the state of an instruction after unrolling at /// each iteration. /// /// This is designed to work like a tuple of <Instruction *, int> for the /// purposes of hashing and lookup, but to be able to associate two boolean /// states with each key. struct UnrolledInstState { Instruction *I; int Iteration : 30; unsigned IsFree : 1; unsigned IsCounted : 1; }; /// Hashing and equality testing for a set of the instruction states. struct UnrolledInstStateKeyInfo { typedef DenseMapInfo<Instruction *> PtrInfo; typedef DenseMapInfo<std::pair<Instruction *, int>> PairInfo; static inline UnrolledInstState getEmptyKey() { return {PtrInfo::getEmptyKey(), 0, 0, 0}; } static inline UnrolledInstState getTombstoneKey() { return {PtrInfo::getTombstoneKey(), 0, 0, 0}; } static inline unsigned getHashValue(const UnrolledInstState &S) { return PairInfo::getHashValue({S.I, S.Iteration}); } static inline bool isEqual(const UnrolledInstState &LHS, const UnrolledInstState &RHS) { return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration}); } }; } namespace { struct EstimatedUnrollCost { /// \brief The estimated cost after unrolling. int UnrolledCost; /// \brief The estimated dynamic cost of executing the instructions in the /// rolled form. int RolledDynamicCost; }; } /// \brief Figure out if the loop is worth full unrolling. /// /// Complete loop unrolling can make some loads constant, and we need to know /// if that would expose any further optimization opportunities. This routine /// estimates this optimization. It computes cost of unrolled loop /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By /// dynamic cost we mean that we won't count costs of blocks that are known not /// to be executed (i.e. if we have a branch in the loop and we know that at the /// given iteration its condition would be resolved to true, we won't add up the /// cost of the 'false'-block). /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If /// the analysis failed (no benefits expected from the unrolling, or the loop is /// too big to analyze), the returned value is None. static Optional<EstimatedUnrollCost> analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, const TargetTransformInfo &TTI, int MaxUnrolledLoopSize) { // We want to be able to scale offsets by the trip count and add more offsets // to them without checking for overflows, and we already don't want to // analyze *massive* trip counts, so we force the max to be reasonably small. assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) && "The unroll iterations max is too large!"); // Only analyze inner loops. We can't properly estimate cost of nested loops // and we won't visit inner loops again anyway. if (!L->empty()) return None; // Don't simulate loops with a big or unknown tripcount if (!UnrollMaxIterationsCountToAnalyze || !TripCount || TripCount > UnrollMaxIterationsCountToAnalyze) return None; SmallSetVector<BasicBlock *, 16> BBWorklist; SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist; DenseMap<Value *, Constant *> SimplifiedValues; SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues; // The estimated cost of the unrolled form of the loop. We try to estimate // this by simplifying as much as we can while computing the estimate. int UnrolledCost = 0; // We also track the estimated dynamic (that is, actually executed) cost in // the rolled form. This helps identify cases when the savings from unrolling // aren't just exposing dead control flows, but actual reduced dynamic // instructions due to the simplifications which we expect to occur after // unrolling. int RolledDynamicCost = 0; // We track the simplification of each instruction in each iteration. We use // this to recursively merge costs into the unrolled cost on-demand so that // we don't count the cost of any dead code. This is essentially a map from // <instruction, int> to <bool, bool>, but stored as a densely packed struct. DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap; // A small worklist used to accumulate cost of instructions from each // observable and reached root in the loop. SmallVector<Instruction *, 16> CostWorklist; // PHI-used worklist used between iterations while accumulating cost. SmallVector<Instruction *, 4> PHIUsedList; // Helper function to accumulate cost for instructions in the loop. auto AddCostRecursively = [&](Instruction &RootI, int Iteration) { assert(Iteration >= 0 && "Cannot have a negative iteration!"); assert(CostWorklist.empty() && "Must start with an empty cost list"); assert(PHIUsedList.empty() && "Must start with an empty phi used list"); CostWorklist.push_back(&RootI); for (;; --Iteration) { do { Instruction *I = CostWorklist.pop_back_val(); // InstCostMap only uses I and Iteration as a key, the other two values // don't matter here. auto CostIter = InstCostMap.find({I, Iteration, 0, 0}); if (CostIter == InstCostMap.end()) // If an input to a PHI node comes from a dead path through the loop // we may have no cost data for it here. What that actually means is // that it is free. continue; auto &Cost = *CostIter; if (Cost.IsCounted) // Already counted this instruction. continue; // Mark that we are counting the cost of this instruction now. Cost.IsCounted = true; // If this is a PHI node in the loop header, just add it to the PHI set. if (auto *PhiI = dyn_cast<PHINode>(I)) if (PhiI->getParent() == L->getHeader()) { assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they " "inherently simplify during unrolling."); if (Iteration == 0) continue; // Push the incoming value from the backedge into the PHI used list // if it is an in-loop instruction. We'll use this to populate the // cost worklist for the next iteration (as we count backwards). if (auto *OpI = dyn_cast<Instruction>( PhiI->getIncomingValueForBlock(L->getLoopLatch()))) if (L->contains(OpI)) PHIUsedList.push_back(OpI); continue; } // First accumulate the cost of this instruction. if (!Cost.IsFree) { UnrolledCost += TTI.getUserCost(I); DEBUG(dbgs() << "Adding cost of instruction (iteration " << Iteration << "): "); DEBUG(I->dump()); } // We must count the cost of every operand which is not free, // recursively. If we reach a loop PHI node, simply add it to the set // to be considered on the next iteration (backwards!). for (Value *Op : I->operands()) { // Check whether this operand is free due to being a constant or // outside the loop. auto *OpI = dyn_cast<Instruction>(Op); if (!OpI || !L->contains(OpI)) continue; // Otherwise accumulate its cost. CostWorklist.push_back(OpI); } } while (!CostWorklist.empty()); if (PHIUsedList.empty()) // We've exhausted the search. break; assert(Iteration > 0 && "Cannot track PHI-used values past the first iteration!"); CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end()); PHIUsedList.clear(); } }; // Ensure that we don't violate the loop structure invariants relied on by // this analysis. assert(L->isLoopSimplifyForm() && "Must put loop into normal form first."); assert(L->isLCSSAForm(DT) && "Must have loops in LCSSA form to track live-out values."); DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n"); // Simulate execution of each iteration of the loop counting instructions, // which would be simplified. // Since the same load will take different values on different iterations, // we literally have to go through all loop's iterations. for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) { DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n"); // Prepare for the iteration by collecting any simplified entry or backedge // inputs. for (Instruction &I : *L->getHeader()) { auto *PHI = dyn_cast<PHINode>(&I); if (!PHI) break; // The loop header PHI nodes must have exactly two input: one from the // loop preheader and one from the loop latch. assert( PHI->getNumIncomingValues() == 2 && "Must have an incoming value only for the preheader and the latch."); Value *V = PHI->getIncomingValueForBlock( Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch()); Constant *C = dyn_cast<Constant>(V); if (Iteration != 0 && !C) C = SimplifiedValues.lookup(V); if (C) SimplifiedInputValues.push_back({PHI, C}); } // Now clear and re-populate the map for the next iteration. SimplifiedValues.clear(); while (!SimplifiedInputValues.empty()) SimplifiedValues.insert(SimplifiedInputValues.pop_back_val()); UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L); BBWorklist.clear(); BBWorklist.insert(L->getHeader()); // Note that we *must not* cache the size, this loop grows the worklist. for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { BasicBlock *BB = BBWorklist[Idx]; // Visit all instructions in the given basic block and try to simplify // it. We don't change the actual IR, just count optimization // opportunities. for (Instruction &I : *BB) { // Track this instruction's expected baseline cost when executing the // rolled loop form. RolledDynamicCost += TTI.getUserCost(&I); // Visit the instruction to analyze its loop cost after unrolling, // and if the visitor returns true, mark the instruction as free after // unrolling and continue. bool IsFree = Analyzer.visit(I); bool Inserted = InstCostMap.insert({&I, (int)Iteration, (unsigned)IsFree, /*IsCounted*/ false}).second; (void)Inserted; assert(Inserted && "Cannot have a state for an unvisited instruction!"); if (IsFree) continue; // If the instruction might have a side-effect recursively account for // the cost of it and all the instructions leading up to it. if (I.mayHaveSideEffects()) AddCostRecursively(I, Iteration); // Can't properly model a cost of a call. // FIXME: With a proper cost model we should be able to do it. if(isa<CallInst>(&I)) return None; // If unrolled body turns out to be too big, bail out. if (UnrolledCost > MaxUnrolledLoopSize) { DEBUG(dbgs() << " Exceeded threshold.. exiting.\n" << " UnrolledCost: " << UnrolledCost << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize << "\n"); return None; } } TerminatorInst *TI = BB->getTerminator(); // Add in the live successors by first checking whether we have terminator // that may be simplified based on the values simplified by this call. BasicBlock *KnownSucc = nullptr; if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { if (BI->isConditional()) { if (Constant *SimpleCond = SimplifiedValues.lookup(BI->getCondition())) { // Just take the first successor if condition is undef if (isa<UndefValue>(SimpleCond)) KnownSucc = BI->getSuccessor(0); else if (ConstantInt *SimpleCondVal = dyn_cast<ConstantInt>(SimpleCond)) KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0); } } } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { if (Constant *SimpleCond = SimplifiedValues.lookup(SI->getCondition())) { // Just take the first successor if condition is undef if (isa<UndefValue>(SimpleCond)) KnownSucc = SI->getSuccessor(0); else if (ConstantInt *SimpleCondVal = dyn_cast<ConstantInt>(SimpleCond)) KnownSucc = SI->findCaseValue(SimpleCondVal).getCaseSuccessor(); } } if (KnownSucc) { if (L->contains(KnownSucc)) BBWorklist.insert(KnownSucc); else ExitWorklist.insert({BB, KnownSucc}); continue; } // Add BB's successors to the worklist. for (BasicBlock *Succ : successors(BB)) if (L->contains(Succ)) BBWorklist.insert(Succ); else ExitWorklist.insert({BB, Succ}); AddCostRecursively(*TI, Iteration); } // If we found no optimization opportunities on the first iteration, we // won't find them on later ones too. if (UnrolledCost == RolledDynamicCost) { DEBUG(dbgs() << " No opportunities found.. exiting.\n" << " UnrolledCost: " << UnrolledCost << "\n"); return None; } } while (!ExitWorklist.empty()) { BasicBlock *ExitingBB, *ExitBB; std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val(); for (Instruction &I : *ExitBB) { auto *PN = dyn_cast<PHINode>(&I); if (!PN) break; Value *Op = PN->getIncomingValueForBlock(ExitingBB); if (auto *OpI = dyn_cast<Instruction>(Op)) if (L->contains(OpI)) AddCostRecursively(*OpI, TripCount - 1); } } DEBUG(dbgs() << "Analysis finished:\n" << "UnrolledCost: " << UnrolledCost << ", " << "RolledDynamicCost: " << RolledDynamicCost << "\n"); return {{UnrolledCost, RolledDynamicCost}}; } /// ApproximateLoopSize - Approximate the size of the loop. static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, bool &NotDuplicatable, bool &Convergent, const TargetTransformInfo &TTI, AssumptionCache *AC) { SmallPtrSet<const Value *, 32> EphValues; CodeMetrics::collectEphemeralValues(L, AC, EphValues); CodeMetrics Metrics; for (BasicBlock *BB : L->blocks()) Metrics.analyzeBasicBlock(BB, TTI, EphValues); NumCalls = Metrics.NumInlineCandidates; NotDuplicatable = Metrics.notDuplicatable; Convergent = Metrics.convergent; unsigned LoopSize = Metrics.NumInsts; // Don't allow an estimate of size zero. This would allows unrolling of loops // with huge iteration counts, which is a compile time problem even if it's // not a problem for code quality. Also, the code using this size may assume // that each loop has at least three instructions (likely a conditional // branch, a comparison feeding that branch, and some kind of loop increment // feeding that comparison instruction). LoopSize = std::max(LoopSize, 3u); return LoopSize; } // Returns the loop hint metadata node with the given name (for example, // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is // returned. static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { if (MDNode *LoopID = L->getLoopID()) return GetUnrollMetadata(LoopID, Name); return nullptr; } // Returns true if the loop has an unroll(full) pragma. static bool HasUnrollFullPragma(const Loop *L) { return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); } // Returns true if the loop has an unroll(enable) pragma. This metadata is used // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives. static bool HasUnrollEnablePragma(const Loop *L) { return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable"); } // Returns true if the loop has an unroll(disable) pragma. static bool HasUnrollDisablePragma(const Loop *L) { return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); } // Returns true if the loop has an runtime unroll(disable) pragma. static bool HasRuntimeUnrollDisablePragma(const Loop *L) { return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable"); } // If loop has an unroll_count pragma return the (necessarily // positive) value from the pragma. Otherwise return 0. static unsigned UnrollCountPragmaValue(const Loop *L) { MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); if (MD) { assert(MD->getNumOperands() == 2 && "Unroll count hint metadata should have two operands."); unsigned Count = mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); assert(Count >= 1 && "Unroll count must be positive."); return Count; } return 0; } // Remove existing unroll metadata and add unroll disable metadata to // indicate the loop has already been unrolled. This prevents a loop // from being unrolled more than is directed by a pragma if the loop // unrolling pass is run more than once (which it generally is). static void SetLoopAlreadyUnrolled(Loop *L) { MDNode *LoopID = L->getLoopID(); // First remove any existing loop unrolling metadata. SmallVector<Metadata *, 4> MDs; // Reserve first location for self reference to the LoopID metadata node. MDs.push_back(nullptr); if (LoopID) { for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { bool IsUnrollMetadata = false; MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); if (MD) { const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); } if (!IsUnrollMetadata) MDs.push_back(LoopID->getOperand(i)); } } // Add unroll(disable) metadata to disable future unrolling. LLVMContext &Context = L->getHeader()->getContext(); SmallVector<Metadata *, 1> DisableOperands; DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); MDNode *DisableNode = MDNode::get(Context, DisableOperands); MDs.push_back(DisableNode); MDNode *NewLoopID = MDNode::get(Context, MDs); // Set operand 0 to refer to the loop id itself. NewLoopID->replaceOperandWith(0, NewLoopID); L->setLoopID(NewLoopID); } static bool canUnrollCompletely(Loop *L, unsigned Threshold, unsigned PercentDynamicCostSavedThreshold, unsigned DynamicCostSavingsDiscount, uint64_t UnrolledCost, uint64_t RolledDynamicCost) { if (Threshold == NoThreshold) { DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n"); return true; } if (UnrolledCost <= Threshold) { DEBUG(dbgs() << " Can fully unroll, because unrolled cost: " << UnrolledCost << "<" << Threshold << "\n"); return true; } assert(UnrolledCost && "UnrolledCost can't be 0 at this point."); assert(RolledDynamicCost >= UnrolledCost && "Cannot have a higher unrolled cost than a rolled cost!"); // Compute the percentage of the dynamic cost in the rolled form that is // saved when unrolled. If unrolling dramatically reduces the estimated // dynamic cost of the loop, we use a higher threshold to allow more // unrolling. unsigned PercentDynamicCostSaved = (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost; if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold && (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <= (int64_t)Threshold) { DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the " "expected dynamic cost by " << PercentDynamicCostSaved << "% (threshold: " << PercentDynamicCostSavedThreshold << "%)\n" << " and the unrolled cost (" << UnrolledCost << ") is less than the max threshold (" << DynamicCostSavingsDiscount << ").\n"); return true; } DEBUG(dbgs() << " Too large to fully unroll:\n"); DEBUG(dbgs() << " Threshold: " << Threshold << "\n"); DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n"); DEBUG(dbgs() << " Percent cost saved threshold: " << PercentDynamicCostSavedThreshold << "%\n"); DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n"); DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n"); DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved << "\n"); return false; } // Returns true if unroll count was set explicitly. // Calculates unroll count and writes it to UP.Count. static bool computeUnrollCount(Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE, unsigned TripCount, unsigned TripMultiple, unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP) { // BEInsns represents number of instructions optimized when "back edge" // becomes "fall through" in unrolled loop. // For now we count a conditional branch on a backedge and a comparison // feeding it. unsigned BEInsns = 2; // Check for explicit Count. // 1st priority is unroll count set by "unroll-count" option. bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0; if (UserUnrollCount) { UP.Count = UnrollCount; UP.AllowExpensiveTripCount = true; UP.Force = true; if (UP.AllowRemainder && (LoopSize - BEInsns) * UP.Count + BEInsns < UP.Threshold) return true; } // 2nd priority is unroll count set by pragma. unsigned PragmaCount = UnrollCountPragmaValue(L); if (PragmaCount > 0) { UP.Count = PragmaCount; UP.Runtime = true; UP.AllowExpensiveTripCount = true; UP.Force = true; if (UP.AllowRemainder && (LoopSize - BEInsns) * UP.Count + BEInsns < PragmaUnrollThreshold) return true; } bool PragmaFullUnroll = HasUnrollFullPragma(L); if (PragmaFullUnroll && TripCount != 0) { UP.Count = TripCount; if ((LoopSize - BEInsns) * UP.Count + BEInsns < PragmaUnrollThreshold) return false; } bool PragmaEnableUnroll = HasUnrollEnablePragma(L); bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll || PragmaEnableUnroll || UserUnrollCount; uint64_t UnrolledSize; DebugLoc LoopLoc = L->getStartLoc(); Function *F = L->getHeader()->getParent(); LLVMContext &Ctx = F->getContext(); if (ExplicitUnroll && TripCount != 0) { // If the loop has an unrolling pragma, we want to be more aggressive with // unrolling limits. Set thresholds to at least the PragmaThreshold value // which is larger than the default limits. UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold); UP.PartialThreshold = std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold); } // 3rd priority is full unroll count. // Full unroll make sense only when TripCount could be staticaly calculated. // Also we need to check if we exceed FullUnrollMaxCount. if (TripCount && TripCount <= UP.FullUnrollMaxCount) { // When computing the unrolled size, note that BEInsns are not replicated // like the rest of the loop body. UnrolledSize = (uint64_t)(LoopSize - BEInsns) * TripCount + BEInsns; if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount, UnrolledSize, UnrolledSize)) { UP.Count = TripCount; return ExplicitUnroll; } else { // The loop isn't that small, but we still can fully unroll it if that // helps to remove a significant number of instructions. // To check that, run additional analysis on the loop. if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost( L, TripCount, DT, *SE, TTI, UP.Threshold + UP.DynamicCostSavingsDiscount)) if (canUnrollCompletely(L, UP.Threshold, UP.PercentDynamicCostSavedThreshold, UP.DynamicCostSavingsDiscount, Cost->UnrolledCost, Cost->RolledDynamicCost)) { UP.Count = TripCount; return ExplicitUnroll; } } } // 4rd priority is partial unrolling. // Try partial unroll only when TripCount could be staticaly calculated. if (TripCount) { if (UP.Count == 0) UP.Count = TripCount; UP.Partial |= ExplicitUnroll; if (!UP.Partial) { DEBUG(dbgs() << " will not try to unroll partially because " << "-unroll-allow-partial not given\n"); UP.Count = 0; return false; } if (UP.PartialThreshold != NoThreshold) { // Reduce unroll count to be modulo of TripCount for partial unrolling. UnrolledSize = (uint64_t)(LoopSize - BEInsns) * UP.Count + BEInsns; if (UnrolledSize > UP.PartialThreshold) UP.Count = (std::max(UP.PartialThreshold, 3u) - BEInsns) / (LoopSize - BEInsns); if (UP.Count > UP.MaxCount) UP.Count = UP.MaxCount; while (UP.Count != 0 && TripCount % UP.Count != 0) UP.Count--; if (UP.AllowRemainder && UP.Count <= 1) { // If there is no Count that is modulo of TripCount, set Count to // largest power-of-two factor that satisfies the threshold limit. // As we'll create fixup loop, do the type of unrolling only if // remainder loop is allowed. UP.Count = DefaultUnrollRuntimeCount; UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns; while (UP.Count != 0 && UnrolledSize > UP.PartialThreshold) { UP.Count >>= 1; UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns; } } if (UP.Count < 2) { if (PragmaEnableUnroll) emitOptimizationRemarkMissed( Ctx, DEBUG_TYPE, *F, LoopLoc, "Unable to unroll loop as directed by unroll(enable) pragma " "because unrolled size is too large."); UP.Count = 0; } } else { UP.Count = TripCount; } if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount && UP.Count != TripCount) emitOptimizationRemarkMissed( Ctx, DEBUG_TYPE, *F, LoopLoc, "Unable to fully unroll loop as directed by unroll pragma because " "unrolled size is too large."); return ExplicitUnroll; } assert(TripCount == 0 && "All cases when TripCount is constant should be covered here."); if (PragmaFullUnroll) emitOptimizationRemarkMissed( Ctx, DEBUG_TYPE, *F, LoopLoc, "Unable to fully unroll loop as directed by unroll(full) pragma " "because loop has a runtime trip count."); // 5th priority is runtime unrolling. // Don't unroll a runtime trip count loop when it is disabled. if (HasRuntimeUnrollDisablePragma(L)) { UP.Count = 0; return false; } // Reduce count based on the type of unrolling and the threshold values. UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount; if (!UP.Runtime) { DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " << "-unroll-runtime not given\n"); UP.Count = 0; return false; } if (UP.Count == 0) UP.Count = DefaultUnrollRuntimeCount; UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns; // Reduce unroll count to be the largest power-of-two factor of // the original count which satisfies the threshold limit. while (UP.Count != 0 && UnrolledSize > UP.PartialThreshold) { UP.Count >>= 1; UnrolledSize = (LoopSize - BEInsns) * UP.Count + BEInsns; } #ifndef NDEBUG unsigned OrigCount = UP.Count; #endif if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) { while (UP.Count != 0 && TripMultiple % UP.Count != 0) UP.Count >>= 1; DEBUG(dbgs() << "Remainder loop is restricted (that could architecture " "specific or because the loop contains a convergent " "instruction), so unroll count must divide the trip " "multiple, " << TripMultiple << ". Reducing unroll count from " << OrigCount << " to " << UP.Count << ".\n"); if (PragmaCount > 0 && !UP.AllowRemainder) emitOptimizationRemarkMissed( Ctx, DEBUG_TYPE, *F, LoopLoc, Twine("Unable to unroll loop the number of times directed by " "unroll_count pragma because remainder loop is restricted " "(that could architecture specific or because the loop " "contains a convergent instruction) and so must have an unroll " "count that divides the loop trip multiple of ") + Twine(TripMultiple) + ". Unrolling instead " + Twine(UP.Count) + " time(s)."); } if (UP.Count > UP.MaxCount) UP.Count = UP.MaxCount; DEBUG(dbgs() << " partially unrolling with count: " << UP.Count << "\n"); if (UP.Count < 2) UP.Count = 0; return ExplicitUnroll; } static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE, const TargetTransformInfo &TTI, AssumptionCache &AC, bool PreserveLCSSA, Optional<unsigned> ProvidedCount, Optional<unsigned> ProvidedThreshold, Optional<bool> ProvidedAllowPartial, Optional<bool> ProvidedRuntime) { DEBUG(dbgs() << "Loop Unroll: F[" << L->getHeader()->getParent()->getName() << "] Loop %" << L->getHeader()->getName() << "\n"); if (HasUnrollDisablePragma(L)) { return false; } unsigned NumInlineCandidates; bool NotDuplicatable; bool Convergent; unsigned LoopSize = ApproximateLoopSize( L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC); DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); if (NotDuplicatable) { DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" << " instructions.\n"); return false; } if (NumInlineCandidates != 0) { DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); return false; } // Find trip count and trip multiple if count is not available unsigned TripCount = 0; unsigned TripMultiple = 1; // If there are multiple exiting blocks but one of them is the latch, use the // latch for the trip count estimation. Otherwise insist on a single exiting // block for the trip count estimation. BasicBlock *ExitingBlock = L->getLoopLatch(); if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) ExitingBlock = L->getExitingBlock(); if (ExitingBlock) { TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); } TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences( L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial, ProvidedRuntime); // If the loop contains a convergent operation, the prelude we'd add // to do the first few instructions before we hit the unrolled loop // is unsafe -- it adds a control-flow dependency to the convergent // operation. Therefore restrict remainder loop (try unrollig without). // // TODO: This is quite conservative. In practice, convergent_op() // is likely to be called unconditionally in the loop. In this // case, the program would be ill-formed (on most architectures) // unless n were the same on all threads in a thread group. // Assuming n is the same on all threads, any kind of unrolling is // safe. But currently llvm's notion of convergence isn't powerful // enough to express this. if (Convergent) UP.AllowRemainder = false; bool IsCountSetExplicitly = computeUnrollCount(L, TTI, DT, LI, SE, TripCount, TripMultiple, LoopSize, UP); if (!UP.Count) return false; // Unroll factor (Count) must be less or equal to TripCount. if (TripCount && UP.Count > TripCount) UP.Count = TripCount; // Unroll the loop. if (!UnrollLoop(L, UP.Count, TripCount, UP.Force, UP.Runtime, UP.AllowExpensiveTripCount, TripMultiple, LI, SE, &DT, &AC, PreserveLCSSA)) return false; // If loop has an unroll count pragma or unrolled by explicitly set count // mark loop as unrolled to prevent unrolling beyond that requested. if (IsCountSetExplicitly) SetLoopAlreadyUnrolled(L); return true; } namespace { class LoopUnroll : public LoopPass { public: static char ID; // Pass ID, replacement for typeid LoopUnroll(Optional<unsigned> Threshold = None, Optional<unsigned> Count = None, Optional<bool> AllowPartial = None, Optional<bool> Runtime = None) : LoopPass(ID), ProvidedCount(std::move(Count)), ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial), ProvidedRuntime(Runtime) { initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); } Optional<unsigned> ProvidedCount; Optional<unsigned> ProvidedThreshold; Optional<bool> ProvidedAllowPartial; Optional<bool> ProvidedRuntime; bool runOnLoop(Loop *L, LPPassManager &) override { if (skipLoop(L)) return false; Function &F = *L->getHeader()->getParent(); auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); const TargetTransformInfo &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, PreserveLCSSA, ProvidedCount, ProvidedThreshold, ProvidedAllowPartial, ProvidedRuntime); } /// This transformation requires natural loop information & requires that /// loop preheaders be inserted into the CFG... /// void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<AssumptionCacheTracker>(); AU.addRequired<TargetTransformInfoWrapperPass>(); // FIXME: Loop passes are required to preserve domtree, and for now we just // recreate dom info if anything gets unrolled. getLoopAnalysisUsage(AU); } }; } char LoopUnroll::ID = 0; INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) INITIALIZE_PASS_DEPENDENCY(LoopPass) INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, int Runtime) { // TODO: It would make more sense for this function to take the optionals // directly, but that's dangerous since it would silently break out of tree // callers. return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold), Count == -1 ? None : Optional<unsigned>(Count), AllowPartial == -1 ? None : Optional<bool>(AllowPartial), Runtime == -1 ? None : Optional<bool>(Runtime)); } Pass *llvm::createSimpleLoopUnrollPass() { return llvm::createLoopUnrollPass(-1, -1, 0, 0); }
sawenzel/root
interpreter/llvm/src/lib/Transforms/Scalar/LoopUnrollPass.cpp
C++
lgpl-2.1
43,203
############################################################################ ## ## Copyright (C) 2016 The Qt Company Ltd. ## Contact: https://www.qt.io/licensing/ ## ## This file is part of the examples of PySide2. ## ## $QT_BEGIN_LICENSE:BSD$ ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance with the commercial license agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and The Qt Company. For licensing terms ## and conditions see https://www.qt.io/terms-conditions. For further ## information use the contact form at https://www.qt.io/contact-us. ## ## BSD License Usage ## Alternatively, you may use this file under the terms of the BSD license ## as follows: ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in ## the documentation and/or other materials provided with the ## distribution. ## * Neither the name of The Qt Company Ltd nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## ## $QT_END_LICENSE$ ## ############################################################################ //! [0] def __init__(self, parent): QSpinBox.__init__(self, parent) //! [0] //! [1] def valueFromText(self, text): regExp = QRegExp(tr("(\\d+)(\\s*[xx]\\s*\\d+)?")) if regExp.exactMatch(text): return regExp.cap(1).toInt() else: return 0 //! [1] //! [2] def textFromValue(self, value): return self.tr("%1 x %1").arg(value) //! [2]
qtproject/pyside-pyside
doc/codesnippets/examples/widgets/icons/iconsizespinbox.cpp
C++
lgpl-2.1
2,818
package islam.adhanalarm.widget; import islam.adhanalarm.Schedule; import islam.adhanalarm.util.LocaleManager; import uz.efir.muazzin.Muazzin; import uz.efir.muazzin.R; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.text.format.DateFormat; import android.widget.RemoteViews; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; public class NextNotificationWidgetProvider extends AppWidgetProvider { private static final int[] times = new int[] { R.string.fajr, R.string.sunrise, R.string.dhuhr, R.string.asr, R.string.maghrib, R.string.ishaa, R.string.next_fajr }; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { setNextTime(context, appWidgetManager, appWidgetIds); super.onUpdate(context, appWidgetManager, appWidgetIds); } public static void setNextTime(Context context) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, NextNotificationWidgetProvider.class)); setNextTime(context, appWidgetManager, appWidgetIds); } private static void setNextTime(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { LocaleManager lm = LocaleManager.getInstance(context, false); SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", lm.getLocale(context)); if (DateFormat.is24HourFormat(context)) { timeFormat = new SimpleDateFormat("k:mm", lm.getLocale(context)); } final int nextTimeIndex = Schedule.today(context).nextTimeIndex(); final GregorianCalendar nextTime = Schedule.today(context).getTimes()[nextTimeIndex]; for (int i = 0; i < appWidgetIds.length; i++) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_next_notification); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, Muazzin.class), 0); views.setOnClickPendingIntent(R.id.widget_next_notification, pendingIntent); views.setTextViewText(R.id.time_name, context.getString(times[nextTimeIndex])); views.setTextViewText(R.id.next_notification, timeFormat.format(nextTime.getTime())); appWidgetManager.updateAppWidget(appWidgetIds[i], views); } } }
ozbek/al-muazzin
app/src/main/java/islam/adhanalarm/widget/NextNotificationWidgetProvider.java
Java
lgpl-2.1
2,682
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "Material.h" #include "SubProblem.h" #include "MaterialData.h" // system includes #include <iostream> template<> InputParameters validParams<Material>() { InputParameters params = validParams<MooseObject>(); params += validParams<BlockRestrictable>(); params += validParams<BoundaryRestrictable>(); params.addParam<bool>("use_displaced_mesh", false, "Whether or not this object should use the displaced mesh for computation. Note that in the case this is true but no displacements are provided in the Mesh block the undisplaced mesh will still be used."); // Outputs params += validParams<OutputInterface>(); params.set<std::vector<OutputName> >("outputs") = std::vector<OutputName>(1, "none"); params.addParam<std::vector<std::string> >("output_properties", "List of material properties, from this material, to output (outputs must also be defined to an output type)"); params.addParamNamesToGroup("outputs output_properties", "Outputs"); params.addParamNamesToGroup("use_displaced_mesh", "Advanced"); params.registerBase("Material"); return params; } Material::Material(const std::string & name, InputParameters parameters) : MooseObject(name, parameters), BlockRestrictable(name, parameters), BoundaryRestrictable(name, parameters), SetupInterface(parameters), Coupleable(parameters, false), MooseVariableDependencyInterface(), ScalarCoupleable(parameters), FunctionInterface(parameters), UserObjectInterface(parameters), TransientInterface(parameters, name, "materials"), MaterialPropertyInterface(name, parameters), PostprocessorInterface(parameters), DependencyResolverInterface(), Restartable(name, parameters, "Materials"), ZeroInterface(parameters), MeshChangedInterface(parameters), // The false flag disables the automatic call buildOutputVariableHideList; // for Material objects the hide lists are handled by MaterialOutputAction OutputInterface(name, parameters, false), _subproblem(*parameters.get<SubProblem *>("_subproblem")), _fe_problem(*parameters.get<FEProblem *>("_fe_problem")), _tid(parameters.get<THREAD_ID>("_tid")), _assembly(_subproblem.assembly(_tid)), _bnd(parameters.get<bool>("_bnd")), _neighbor(getParam<bool>("_neighbor")), _material_data(*parameters.get<MaterialData *>("_material_data")), _qp(std::numeric_limits<unsigned int>::max()), _qrule(_bnd ? _assembly.qRuleFace() : _assembly.qRule()), _JxW(_bnd ? _assembly.JxWFace() : _assembly.JxW()), _coord(_assembly.coordTransformation()), _q_point(_bnd ? _assembly.qPointsFace() : _assembly.qPoints()), _normals(_assembly.normals()), _current_elem(_neighbor ? _assembly.neighbor() : _assembly.elem()), _current_side(_neighbor ? _assembly.neighborSide() : _assembly.side()), _mesh(_subproblem.mesh()), _coord_sys(_assembly.coordSystem()), _has_stateful_property(false) { // Fill in the MooseVariable dependencies const std::vector<MooseVariable *> & coupled_vars = getCoupledMooseVars(); for (unsigned int i=0; i<coupled_vars.size(); i++) addMooseVariableDependency(coupled_vars[i]); } Material::~Material() { } void Material::computeProperties() { for (_qp = 0; _qp < _qrule->n_points(); ++_qp) computeQpProperties(); } void Material::initStatefulProperties(unsigned int n_points) { if (_has_stateful_property) for (_qp = 0; _qp < n_points; ++_qp) initQpStatefulProperties(); } void Material::initQpStatefulProperties() { mooseDoOnce(mooseWarning(std::string("Material \"") + _name + "\" declares one or more stateful properties but initQpStatefulProperties() was not overridden in the derived class.")); } void Material::computeQpProperties() { } void Material::timeStepSetup() {} QpData * Material::createData() { return NULL; } void Material::checkStatefulSanity() const { for (std::map<std::string, int>::const_iterator it = _props_to_flags.begin(); it != _props_to_flags.end(); ++it) { if (static_cast<int>(it->second) % 2 == 0) // Only Stateful properties declared! mooseError("Material '" << _name << "' has stateful properties declared but not associated \"current\" properties." << it->second); } } void Material::registerPropName(std::string prop_name, bool is_get, Material::Prop_State state) { if (!is_get) { _props_to_flags[prop_name] |= static_cast<int>(state); if (static_cast<int>(state) % 2 == 0) _has_stateful_property = true; } // Store material properties for block ids for (std::set<SubdomainID>::const_iterator it = blockIDs().begin(); it != blockIDs().end(); ++it) { // Only save this prop as a "supplied" prop is it was registered as a result of a call to declareProperty not getMaterialProperty if (!is_get) _supplied_props.insert(prop_name); _fe_problem.storeMatPropName(*it, prop_name); _subproblem.storeMatPropName(*it, prop_name); } // Store material properties for the boundary ids for (std::set<BoundaryID>::const_iterator it = boundaryIDs().begin(); it != boundaryIDs().end(); ++it) { /// \todo{see ticket #2192} // Only save this prop as a "supplied" prop is it was registered as a result of a call to declareProperty not getMaterialProperty if (!is_get) _supplied_props.insert(prop_name); _fe_problem.storeMatPropName(*it, prop_name); _subproblem.storeMatPropName(*it, prop_name); } } std::set<OutputName> Material::getOutputs() { return std::set<OutputName>(getParam<std::vector<OutputName> >("outputs").begin(), getParam<std::vector<OutputName> >("outputs").end()); }
cpritam/moose
framework/src/materials/Material.C
C++
lgpl-2.1
6,500
package com.loovjo.bloovtech.tileentity; import net.minecraft.tileentity.TileEntity; public class TileEntityInfuser extends TileEntity { }
loovjo/Bloovtech
src/main/java/com/loovjo/bloovtech/tileentity/TileEntityInfuser.java
Java
lgpl-2.1
142
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* Daf-collage is made up of two Moodle modules which help in the process of German language learning. It facilitates the content organization like vocabulary or the main grammar features and gives the chance to create exercises in order to consolidate knowledge. Copyright (C) 2011 Coordination: Ruth Burbat Source code: Francisco Javier Rodríguez López (seiyadesagitario@gmail.com) Simeón Ruiz Romero (simeonruiz@gmail.com) Serafina Molina Soto(finamolinasoto@gmail.com) Original idea: Ruth Burbat Content design: Ruth Burbat AInmaculada Almahano Güeto Andrea Bies Julia Möller Runge Blanca Rodríguez Gómez Antonio Salmerón Matilla María José Varela Salinas Karin Vilar Sánchez This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ require_once("../../config.php"); require_once("lib.php"); require_once("ejercicios_clase_general.php"); require_once("ejercicios_form_creacion.php"); require_once("YoutubeVideoHelper.php"); $id_curso = optional_param('id_curso', 0, PARAM_INT); $id_ejercicio = optional_param('id_ejercicio', 0, PARAM_INT); $tipo_origen = optional_param('tipo_origen', 0, PARAM_INT); $tipo_respuesta = optional_param('tr', 0, PARAM_INT); $tipo_creacion = optional_param('tipocreacion', 0, PARAM_INT); ECHO "MODIFICANDO"; $mform = new mod_ejercicios_mostrar_ejercicio_asociacion_simple($id_curso, $id_ejercicio, $tipo_origen, $tipo_respuesta, $tipocreacion); $mform->mostrar_ejercicio_asociacion_simple($id_curso, $id_ejercicio, 0, $tipo_origen, $tipo_respuesta, $tipocreacion); $numeropreguntas = optional_param('num_preg', 0, PARAM_INT); echo "El numero de pregunas es" . $numeropreguntas; $ejercicio_general = new Ejercicios_general(); $miejercicio=$ejercicio_general->obtener_uno($id_ejercicio); $miejercicio->set_numpregunta($numeropreguntas); $fuentes = optional_param('fuentes',PARAM_TEXT); $miejercicio->set_fuentes($fuentes); $miejercicio->alterar(); begin_sql(); if ($tipo_origen == 1) { //la pregunta es un texto if ($tipo_respuesta == 1) {//Es un texto //obtengo los id de las preguntas del ejercicio $id_preguntas = array(); $mis_preguntas = new Ejercicios_texto_texto_preg(); $id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio); //borro las respuestas for ($s = 0; $s < sizeof($id_preguntas); $s++) { delete_records('ejercicios_texto_texto_resp', 'id_pregunta', $id_preguntas[$s]->get('id')); } } else { if ($tipo_respuesta == 2) { //la respuesta es un audio echo "actualizando audio"; //obtengo los id de las preguntas del ejercicio $id_preguntas = array(); $mis_preguntas = new Ejercicios_texto_texto_preg(); $id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio); //borro las respuestas for ($s = 0; $s < sizeof($id_preguntas); $s++) { delete_records('ejercicios_audios_asociados', 'id_ejercicio', $id_ejercicio); } } else { if ($tipo_respuesta == 3) {//video echo "actualizando video"; //obtengo los id de las preguntas del ejercicio $id_preguntas = array(); $mis_preguntas = new Ejercicios_texto_texto_preg(); $id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio); //borro las respuestas for ($s = 0; $s < sizeof($id_preguntas); $s++) { delete_records('ejercicios_videos_asociados', 'id_ejercicio', $id_ejercicio); } } else { if ($tipo_respuesta == 4) { echo "actualizando imagen"; //obtengo los id de las preguntas del ejercicio $id_preguntas = array(); $mis_preguntas = new Ejercicios_texto_texto_preg(); $id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio); //borro las respuestas for ($s = 0; $s < sizeof($id_preguntas); $s++) { delete_records('ejercicios_imagenes_asociadas', 'id_ejercicio', $id_ejercicio); } } } } } //borro las preguntas delete_records('ejercicios_texto_texto_preg', 'id_ejercicio', $id_ejercicio); } else { if ($tipo_origen == 2) { //Pregunta es un Audio //borro las preguntas $id_preguntas = array(); $mis_preguntas = new Ejercicios_texto_texto_preg(); $id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio); //borro las respuestas for ($s = 0; $s < sizeof($id_preguntas); $s++) { delete_records('ejercicios_audios_asociados', 'id_ejercicio', $id_ejercicio); } if ($tipo_respuesta == 1) { //La respuesta es un texto //borro las respuestas delete_records('ejercicios_texto_texto_preg', 'id_ejercicio', $id_ejercicio); } } else { if ($tipo_origen == 3) {//video echo "actualizando video"; //obtengo los id de las preguntas del ejercicio $id_preguntas = array(); $mis_preguntas = new Ejercicios_texto_texto_preg(); $id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio); //borro las respuestas for ($s = 0; $s < sizeof($id_preguntas); $s++) { delete_records('ejercicios_videos_asociados', 'id_ejercicio', $id_ejercicio); } if ($tipo_respuesta == 1) { //La respuesta es un texto //borro las respuestas delete_records('ejercicios_texto_texto_preg', 'id_ejercicio', $id_ejercicio); } } else if ($tipo_origen==4) //La pregunta es una imagen { if ($tipo_respuesta == 1) { //La respuesta es un texto echo "actualizando imagen"; //obtengo los id de las preguntas del ejercicio $id_preguntas = array(); $mis_preguntas = new Ejercicios_texto_texto_preg(); $id_preguntas = $mis_preguntas->obtener_todas_preguntas_ejercicicio($id_ejercicio); //borro las respuestas for ($s = 0; $s < sizeof($id_preguntas); $s++) { delete_records('ejercicios_imagenes_asociadas', 'id_ejercicio', $id_ejercicio); } delete_records('ejercicios_texto_texto_preg', 'id_ejercicio', $id_ejercicio); echo 'Borradas imagenes'; } } } } //Guardo las nuevas for ($i = 0; $i < $numeropreguntas; $i++) { //Obtengo el numero de respuestas a cada pregunta $j = $i + 1; if ($tipo_origen == 1) { //Si la pregunta es un texto $preg = required_param('pregunta' . $j, PARAM_TEXT); $ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg); $id_pregunta = $ejercicio_texto_preg->insertar(); if ($tipo_respuesta == 1) { //Si la respuesta es un texto $resp = required_param('respuesta' . $j, PARAM_TEXT); $correcta = 0; $ejercicio_texto_resp = new Ejercicios_texto_texto_resp(NULL, $id_pregunta, $resp, $correcta); $ejercicio_texto_resp->insertar(); } else { if ($tipo_respuesta == 2) { //es un audio $ejercicio_texto_audio = new Ejercicios_audios_asociados($NULL, $id_ejercicio, $id_pregunta, 'audio_' . $id_ejercicio . "_" . $j . ".mp3"); $ejercicio_texto_audio->insertar(); } else { if ($tipo_respuesta == 3) { //ES UN VIDEO $resp = YoutubeVideoHelper::getVideoId(required_param('archivovideo' . $j, PARAM_TEXT)); echo "archivo video" . $resp; $ejercicio_texto_video = new Ejercicios_videos_asociados(NULL, $id_ejercicio, $id_pregunta, $resp); $ejercicio_texto_video->insertar(); } else { if ($tipo_respuesta == 4) { //eS UNA IMAGEN $ejercicio_texto_img = new Ejercicios_imagenes_asociadas($NULL, $id_ejercicio, $id_pregunta, 'foto_' . $id_ejercicio . "_" . $j . ".jpg"); $ejercicio_texto_img->insertar(); } } } } } else { if ($tipo_origen == 2) { //la pregunta es un audio // echo "entra"; $preg = required_param('pregunta' . $j, PARAM_TEXT); $ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg); $id_pregunta = $ejercicio_texto_preg->insertar(); if ($tipo_respuesta == 1) { //la respuesta es un texto // echo "entra 2"; $ejercicio_texto_audio = new Ejercicios_audios_asociados($NULL, $id_ejercicio, $id_pregunta, 'audio_' . $id_ejercicio . "_" . $j . ".mp3"); $ejercicio_texto_audio->insertar(); } } else { if ($tipo_origen == 3) { //ES UN VIDEO if (YoutubeVideoHelper::getVideoId(required_param('archivovideo' . $j, PARAM_TEXT)) != null){ $preg = required_param('pregunta' . $j, PARAM_TEXT); $ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg); $id_pregunta = $ejercicio_texto_preg->insertar(); $resp = YoutubeVideoHelper::getVideoId(required_param('archivovideo' . $j, PARAM_TEXT)); echo "archivo video" . $resp; $ejercicio_texto_video = new Ejercicios_videos_asociados(NULL, $id_ejercicio, $id_pregunta, $resp); $ejercicio_texto_video->insertar(); echo "insertado"; } } else if ($tipo_origen == 4) { // ES UNA IMAGEN if ($tipo_respuesta == 1) { //La respuesta es un texto $preg = required_param('pregunta' . $j, PARAM_TEXT); $ejercicio_texto_preg = new Ejercicios_texto_texto_preg(NULL, $id_ejercicio, $preg); $id_pregunta = $ejercicio_texto_preg->insertar(); $ejercicio_texto_img = new Ejercicios_imagenes_asociadas($NULL, $id_ejercicio, $id_pregunta, 'foto_' . $id_ejercicio . "_" . $j . ".jpg"); $ejercicio_texto_img->insertar(); } } } } } commit_sql(); redirect('./view.php?id=' . $id_curso . '&opcion=9'); ?>
seiya64/dafcollage
ejercicios/ejercicios_modificar_asociacion_simple.php
PHP
lgpl-2.1
11,528
<?php /** * Limb Web Application Framework * * @link http://limb-project.com * * @copyright Copyright &copy; 2004-2009 BIT * @license LGPL http://www.gnu.org/copyleft/lesser.html * @version $Id$ * @package web_app */ lmb_require('limb/web_app/src/controller/lmbController.class.php'); lmb_require('limb/view/src/wact/lmbWactHighlightHandler.class.php'); require_once('limb/view/lib/XML/HTMLSax3.php'); abstract class lmbWactTemplateSourceController extends lmbController { protected $template_for_hackers = 'template_source/error.html'; protected $history = array(); protected $highlight_page_url = 'wact_template_source'; function doDisplay() { require_once('limb/wact/src/compiler/templatecompiler.inc.php'); require_once('limb/view/src/lmbWactView.class.php'); $this->setTemplate('template_source/display.html'); if(($t = $this->request->get('t')) && is_array($t) && sizeof($t) > 0) { $this->history = $t; $template_path = end($this->history); } else { $this->setTemplate($this->template_for_hackers); return; } if(substr($template_path, -5, 5) != '.html') $template_path = $this->template_for_hackers; $wact_locator = $this->toolkit->getWactLocator(); if(!$source_file_path = $wact_locator->locateSourceTemplate($template_path)) { $this->setTemplate($this->template_for_hackers); return; } $template_contents = file_get_contents($source_file_path); if(sizeof($this->history) > 1) { $tmp_history = $this->history; $from_template_path = $tmp_history[sizeof($tmp_history) - 2]; $tmp_history = array_splice($tmp_history, 0, sizeof($tmp_history) - 1); $history_query = 't[]=' . implode('&t[]=', $tmp_history); $this->view->set('history_query', $this->highlight_page_url . '?' .$history_query); $this->view->set('from_template_path', $from_template_path); } $this->view->set('template_path', $template_path); $this->view->set('this_template_path', $this->view->getTemplate()); $this->view->set('template_content', $this->_processTemplateContent($template_contents)); } function _processTemplateContent($template_contents) { $compiler = $this->view->getWactTemplate()->createCompiler(); $tag_dictionary = $compiler->getTagDictionary(); $parser = new XML_HTMLSax3(); $handler = new lmbWactHighlightHandler($tag_dictionary, $this->highlight_page_url); $handler->setTemplatePathHistory($this->history); $parser->set_object($handler); $parser->set_element_handler('openHandler','closeHandler'); $parser->set_data_handler('dataHandler'); $parser->set_escape_handler('escapeHandler'); $parser->parse($template_contents); $html = $handler->getHtml(); return $html; } }
knevcher/limb
web_app/src/controller/lmbWactTemplateSourceController.class.php
PHP
lgpl-2.1
2,939
""" ECE 4564 Final Project Team: Immortal Title: HomeGuard - Home Visitors Detection and Alert System Filename: publisher.py Members: Arun Rai, Mohammad Islam, and Yihan Pang Date: 11/26/2014 --------------------------------------------------------------------- Description: 1. Receive host user information, and send it to the subscriber. 2. Receive visitors' message and send it to the subscriber. 3. Receive sensor reading, and send trigger signal to camera to the subscriber. Network protocols: TCP/IP and AMQP --------------------------------------------------------------------- """ #!/usr/bin/python import sys import threading from infoSetup import infoSetup from getSensorData import getSensorData from setVisitorMessage import setVisitorMessage import time import signal import socket import json """ Default host IP address and port number """ HOST = "127.0.0.1" PORT = 9000 class HostInformation: def __init__(self): self.senderNumber = ''; self.receiverNumber = '' self.receiverEmail = 'sangpang20@gmail.com'; self.loop = True; self.s = ''; self.emailOnly = True; self.smsOnly = False; self.both = False; self.Message = {}; self.msgSignal = False; """ Set receiver's phone number """ def setPhoneNumber(self, number): self.receiverNumber = number; self.smsOnly = True; self.emailOnly = False; self.both = False; """ Set receiver's email id """ def setEmail(self, email): self.receiverEmail = email; self.emailOnly = True; self.smsOnly = False; self.both = False; """ Set both email and phone nubmer """ def setBoth(self, email, phone): self.receiverEmail = email; self.receiverNumber = phone; self.both = True; self.emailOnly = False; self.smsOnly = False; def getReceiverNumber(self): return self.receiverNumber; def getReceiverEmail(self): return self.receiverEmail; def getSenderEmail(self): return self.senderEmail; def getSenderEmailPass(self): return self.senderPassword; def messageInEmail(self): return self.emailOnly; def messageInSms(self): return self.smsOnly; def messageInBoth(self): return self.both; def setLoopState(self, signal=None, frame=None): print 'Gracefully closing the socket .................' self.loop = False; self.s.close(); """ Here, the message is of type dictionary """ def setMessage(self, message): self.Message = message; def getMessage(self): return self.Message; def setMessageSignal(self, sig): self.msgSignal = sig; def getMessageSignal(self): return self.msgSignal; def getLoopState(self): return self.loop; """ The function is called before the program exits for gracefully closing the socket when user enters Ctrl + c. """ def closeSocket(self, s): self.s = s; def main(): setHostInfo = HostInformation() """ Sensor thread: sensor reading is performed""" sensorThread = threading.Thread(target = getSensorData, args = [setHostInfo,]); """ start the thread """ sensorThread.start() """ Setup signal handlers to shutdown this app when SIGINT or SIGTERM is sent to this app """ signal_num = signal.SIGINT try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) """ main thread """ while setHostInfo.getLoopState(): try: setHostInfo.closeSocket(s); signal.signal(signal_num, setHostInfo.setLoopState) signal_num = signal.SIGTERM signal.signal(signal_num, setHostInfo.setLoopState) except ValueError as error1: print "Warning: Greceful shutdown may not be possible: Unsupported" print "Signal: " + signal_num conn, addr = s.accept() message = conn.recv(1024) if len(message) > 3: if message[0] == '$' and message[1] == '$' and message[2] == '$': setVisitorMessage(setHostInfo, message) else: infoSetup(setHostInfo, message) except socket.error, se: print 'connection failed/socket closed. \n', se if s: s.close(); sensorThread.join() if __name__ == '__main__': main();
raiarun/HomeGuard
publisher.py
Python
lgpl-2.1
4,016
<?php /*"****************************************************************************************************** * (c) 2016 by Kajona, www.kajona.de * * Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt * ********************************************************************************************************/ /** * @deprecated */ class class_pdf_tcpdf extends Kajona\Pdf\System\PdfTcpdf { }
kajona/kajonacms
module_pdf/legacy/class_pdf_tcpdf.php
PHP
lgpl-2.1
516
#!/usr/bin/env python # # Generated Thu Jul 22 14:11:34 2010 by generateDS.py. # import sys import getopt from xml.dom import minidom from xml.dom import Node # # If you have installed IPython you can uncomment and use the following. # IPython is available from http://ipython.scipy.org/. # ## from IPython.Shell import IPShellEmbed ## args = '' ## ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', ## exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: # ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit') # # Support/utility functions. # def showIndent(outfile, level): for idx in range(level): outfile.write(' ') def quote_xml(inStr): s1 = inStr s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('"', '&quot;') return s1 def quote_python(inStr): s1 = inStr if s1.find("'") == -1: if s1.find('\n') == -1: return "'%s'" % s1 else: return "'''%s'''" % s1 else: if s1.find('"') != -1: s1 = s1.replace('"', '\\"') if s1.find('\n') == -1: return '"%s"' % s1 else: return '"""%s"""' % s1 class MixedContainer: # Constants for category: CategoryNone = 0 CategoryText = 1 CategorySimple = 2 CategoryComplex = 3 # Constants for content_type: TypeNone = 0 TypeText = 1 TypeString = 2 TypeInteger = 3 TypeFloat = 4 TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value def getCategory(self): return self.category def getContenttype(self, content_type): return self.content_type def getValue(self): return self.value def getName(self): return self.name def export(self, outfile, level, name): if self.category == MixedContainer.CategoryText: outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex self.value.export(outfile, level, name) def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeInteger or \ self.content_type == MixedContainer.TypeBoolean: outfile.write('<%s>%d</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeFloat or \ self.content_type == MixedContainer.TypeDecimal: outfile.write('<%s>%f</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g</%s>' % (self.name, self.value, self.name)) def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s",\n' % \ (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') # # Data representation classes. # class GenerateModel: subclass = None def __init__(self, Module=None, PythonExport=None): if Module is None: self.Module = [] else: self.Module = Module if PythonExport is None: self.PythonExport = [] else: self.PythonExport = PythonExport def factory(*args_, **kwargs_): if GenerateModel.subclass: return GenerateModel.subclass(*args_, **kwargs_) else: return GenerateModel(*args_, **kwargs_) factory = staticmethod(factory) def getModule(self): return self.Module def setModule(self, Module): self.Module = Module def addModule(self, value): self.Module.append(value) def insertModule(self, index, value): self.Module[index] = value def getPythonexport(self): return self.PythonExport def setPythonexport(self, PythonExport): self.PythonExport = PythonExport def addPythonexport(self, value): self.PythonExport.append(value) def insertPythonexport(self, index, value): self.PythonExport[index] = value def export(self, outfile, level, name_='GenerateModel'): showIndent(outfile, level) outfile.write('<%s>\n' % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='GenerateModel'): pass def exportChildren(self, outfile, level, name_='GenerateModel'): for Module_ in self.getModule(): Module_.export(outfile, level) for PythonExport_ in self.getPythonexport(): PythonExport_.export(outfile, level) def exportLiteral(self, outfile, level, name_='GenerateModel'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Module=[\n') level += 1 for Module in self.Module: showIndent(outfile, level) outfile.write('Module(\n') Module.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('PythonExport=[\n') level += 1 for PythonExport in self.PythonExport: showIndent(outfile, level) outfile.write('PythonExport(\n') PythonExport.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Module': obj_ = Module.factory() obj_.build(child_) self.Module.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'PythonExport': obj_ = PythonExport.factory() obj_.build(child_) self.PythonExport.append(obj_) # end class GenerateModel class PythonExport: subclass = None def __init__(self, FatherNamespace='', RichCompare=0, Name='', Reference=0, FatherInclude='', Father='', Namespace='', Twin='', Constructor=0, TwinPointer='', Include='', NumberProtocol=0, Delete=0, Documentation=None, Methode=None, Attribute=None, Sequence=None, CustomAttributes='', ClassDeclarations='', Initialization=0): self.FatherNamespace = FatherNamespace self.RichCompare = RichCompare self.Name = Name self.Reference = Reference self.FatherInclude = FatherInclude self.Father = Father self.Namespace = Namespace self.Twin = Twin self.Constructor = Constructor self.TwinPointer = TwinPointer self.Include = Include self.NumberProtocol = NumberProtocol self.Delete = Delete self.Documentation = Documentation self.Initialization = Initialization if Methode is None: self.Methode = [] else: self.Methode = Methode if Attribute is None: self.Attribute = [] else: self.Attribute = Attribute self.Sequence = Sequence self.CustomAttributes = CustomAttributes self.ClassDeclarations = ClassDeclarations def factory(*args_, **kwargs_): if PythonExport.subclass: return PythonExport.subclass(*args_, **kwargs_) else: return PythonExport(*args_, **kwargs_) factory = staticmethod(factory) def getInitialization(self): return self.Initialization def setInitialization(self, Initialization): self.Initialization = Initialization def getDocumentation(self): return self.Documentation def setDocumentation(self, Documentation): self.Documentation = Documentation def getMethode(self): return self.Methode def setMethode(self, Methode): self.Methode = Methode def addMethode(self, value): self.Methode.append(value) def insertMethode(self, index, value): self.Methode[index] = value def getAttribute(self): return self.Attribute def setAttribute(self, Attribute): self.Attribute = Attribute def addAttribute(self, value): self.Attribute.append(value) def insertAttribute(self, index, value): self.Attribute[index] = value def getSequence(self): return self.Sequence def setSequence(self, Sequence): self.Sequence = Sequence def getCustomattributes(self): return self.CustomAttributes def setCustomattributes(self, CustomAttributes): self.CustomAttributes = CustomAttributes def getClassdeclarations(self): return self.ClassDeclarations def setClassdeclarations(self, ClassDeclarations): self.ClassDeclarations = ClassDeclarations def getFathernamespace(self): return self.FatherNamespace def setFathernamespace(self, FatherNamespace): self.FatherNamespace = FatherNamespace def getRichcompare(self): return self.RichCompare def setRichcompare(self, RichCompare): self.RichCompare = RichCompare def getName(self): return self.Name def setName(self, Name): self.Name = Name def getReference(self): return self.Reference def setReference(self, Reference): self.Reference = Reference def getFatherinclude(self): return self.FatherInclude def setFatherinclude(self, FatherInclude): self.FatherInclude = FatherInclude def getFather(self): return self.Father def setFather(self, Father): self.Father = Father def getNamespace(self): return self.Namespace def setNamespace(self, Namespace): self.Namespace = Namespace def getTwin(self): return self.Twin def setTwin(self, Twin): self.Twin = Twin def getConstructor(self): return self.Constructor def setConstructor(self, Constructor): self.Constructor = Constructor def getTwinpointer(self): return self.TwinPointer def setTwinpointer(self, TwinPointer): self.TwinPointer = TwinPointer def getInclude(self): return self.Include def setInclude(self, Include): self.Include = Include def getNumberprotocol(self): return self.NumberProtocol def setNumberprotocol(self, NumberProtocol): self.NumberProtocol = NumberProtocol def getDelete(self): return self.Delete def setDelete(self, Delete): self.Delete = Delete def export(self, outfile, level, name_='PythonExport'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='PythonExport') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='PythonExport'): outfile.write(' FatherNamespace="%s"' % (self.getFathernamespace(), )) if self.getRichcompare() is not None: outfile.write(' RichCompare="%s"' % (self.getRichcompare(), )) outfile.write(' Name="%s"' % (self.getName(), )) if self.getReference() is not None: outfile.write(' Reference="%s"' % (self.getReference(), )) outfile.write(' FatherInclude="%s"' % (self.getFatherinclude(), )) outfile.write(' Father="%s"' % (self.getFather(), )) outfile.write(' Namespace="%s"' % (self.getNamespace(), )) outfile.write(' Twin="%s"' % (self.getTwin(), )) if self.getConstructor() is not None: outfile.write(' Constructor="%s"' % (self.getConstructor(), )) if self.getInitialization() is not None: outfile.write(' Initialization="%s"' % (self.getInitialization(), )) outfile.write(' TwinPointer="%s"' % (self.getTwinpointer(), )) outfile.write(' Include="%s"' % (self.getInclude(), )) if self.getNumberprotocol() is not None: outfile.write(' NumberProtocol="%s"' % (self.getNumberprotocol(), )) if self.getDelete() is not None: outfile.write(' Delete="%s"' % (self.getDelete(), )) def exportChildren(self, outfile, level, name_='PythonExport'): if self.Documentation: self.Documentation.export(outfile, level) for Methode_ in self.getMethode(): Methode_.export(outfile, level) for Attribute_ in self.getAttribute(): Attribute_.export(outfile, level) if self.Sequence: self.Sequence.export(outfile, level) showIndent(outfile, level) outfile.write('<CustomAttributes>%s</CustomAttributes>\n' % quote_xml(self.getCustomattributes())) showIndent(outfile, level) outfile.write('<ClassDeclarations>%s</ClassDeclarations>\n' % quote_xml(self.getClassdeclarations())) def exportLiteral(self, outfile, level, name_='PythonExport'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('FatherNamespace = "%s",\n' % (self.getFathernamespace(),)) showIndent(outfile, level) outfile.write('RichCompare = "%s",\n' % (self.getRichcompare(),)) showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) showIndent(outfile, level) outfile.write('Reference = "%s",\n' % (self.getReference(),)) showIndent(outfile, level) outfile.write('FatherInclude = "%s",\n' % (self.getFatherinclude(),)) showIndent(outfile, level) outfile.write('Father = "%s",\n' % (self.getFather(),)) showIndent(outfile, level) outfile.write('Namespace = "%s",\n' % (self.getNamespace(),)) showIndent(outfile, level) outfile.write('Twin = "%s",\n' % (self.getTwin(),)) showIndent(outfile, level) outfile.write('Constructor = "%s",\n' % (self.getConstructor(),)) showIndent(outfile, level) outfile.write('Initialization = "%s",\n' % (self.getInitialization(),)) outfile.write('TwinPointer = "%s",\n' % (self.getTwinpointer(),)) showIndent(outfile, level) outfile.write('Include = "%s",\n' % (self.getInclude(),)) showIndent(outfile, level) outfile.write('NumberProtocol = "%s",\n' % (self.getNumberprotocol(),)) showIndent(outfile, level) outfile.write('Delete = "%s",\n' % (self.getDelete(),)) def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) outfile.write('Documentation=Documentation(\n') self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('Methode=[\n') level += 1 for Methode in self.Methode: showIndent(outfile, level) outfile.write('Methode(\n') Methode.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('Attribute=[\n') level += 1 for Attribute in self.Attribute: showIndent(outfile, level) outfile.write('Attribute(\n') Attribute.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.Sequence: showIndent(outfile, level) outfile.write('Sequence=Sequence(\n') self.Sequence.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('CustomAttributes=%s,\n' % quote_python(self.getCustomattributes())) showIndent(outfile, level) outfile.write('ClassDeclarations=%s,\n' % quote_python(self.getClassdeclarations())) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('FatherNamespace'): self.FatherNamespace = attrs.get('FatherNamespace').value if attrs.get('RichCompare'): if attrs.get('RichCompare').value in ('true', '1'): self.RichCompare = 1 elif attrs.get('RichCompare').value in ('false', '0'): self.RichCompare = 0 else: raise ValueError('Bad boolean attribute (RichCompare)') if attrs.get('Name'): self.Name = attrs.get('Name').value if attrs.get('Reference'): if attrs.get('Reference').value in ('true', '1'): self.Reference = 1 elif attrs.get('Reference').value in ('false', '0'): self.Reference = 0 else: raise ValueError('Bad boolean attribute (Reference)') if attrs.get('FatherInclude'): self.FatherInclude = attrs.get('FatherInclude').value if attrs.get('Father'): self.Father = attrs.get('Father').value if attrs.get('Namespace'): self.Namespace = attrs.get('Namespace').value if attrs.get('Twin'): self.Twin = attrs.get('Twin').value if attrs.get('Constructor'): if attrs.get('Constructor').value in ('true', '1'): self.Constructor = 1 elif attrs.get('Constructor').value in ('false', '0'): self.Constructor = 0 else: raise ValueError('Bad boolean attribute (Constructor)') if attrs.get('Initialization'): if attrs.get('Initialization').value in ('true', '1'): self.Initialization = 1 elif attrs.get('Initialization').value in ('false', '0'): self.Initialization = 0 else: raise ValueError('Bad boolean attribute (Initialization)') if attrs.get('TwinPointer'): self.TwinPointer = attrs.get('TwinPointer').value if attrs.get('Include'): self.Include = attrs.get('Include').value if attrs.get('NumberProtocol'): if attrs.get('NumberProtocol').value in ('true', '1'): self.NumberProtocol = 1 elif attrs.get('NumberProtocol').value in ('false', '0'): self.NumberProtocol = 0 else: raise ValueError('Bad boolean attribute (NumberProtocol)') if attrs.get('Delete'): if attrs.get('Delete').value in ('true', '1'): self.Delete = 1 elif attrs.get('Delete').value in ('false', '0'): self.Delete = 0 else: raise ValueError('Bad boolean attribute (Delete)') def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Documentation': obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Methode': obj_ = Methode.factory() obj_.build(child_) self.Methode.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Attribute': obj_ = Attribute.factory() obj_.build(child_) self.Attribute.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Sequence': obj_ = Sequence.factory() obj_.build(child_) self.setSequence(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'CustomAttributes': CustomAttributes_ = '' for text__content_ in child_.childNodes: CustomAttributes_ += text__content_.nodeValue self.CustomAttributes = CustomAttributes_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'ClassDeclarations': ClassDeclarations_ = '' for text__content_ in child_.childNodes: ClassDeclarations_ += text__content_.nodeValue self.ClassDeclarations = ClassDeclarations_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Initialization': obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) # end class PythonExport class Methode: subclass = None def __init__(self, Const=0, Name='', Keyword=0, Documentation=None, Parameter=None): self.Const = Const self.Name = Name self.Keyword = Keyword self.Documentation = Documentation if Parameter is None: self.Parameter = [] else: self.Parameter = Parameter def factory(*args_, **kwargs_): if Methode.subclass: return Methode.subclass(*args_, **kwargs_) else: return Methode(*args_, **kwargs_) factory = staticmethod(factory) def getDocumentation(self): return self.Documentation def setDocumentation(self, Documentation): self.Documentation = Documentation def getParameter(self): return self.Parameter def setParameter(self, Parameter): self.Parameter = Parameter def addParameter(self, value): self.Parameter.append(value) def insertParameter(self, index, value): self.Parameter[index] = value def getConst(self): return self.Const def setConst(self, Const): self.Const = Const def getName(self): return self.Name def setName(self, Name): self.Name = Name def getKeyword(self): return self.Keyword def setKeyword(self, Keyword): self.Keyword = Keyword def export(self, outfile, level, name_='Methode'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='Methode') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Methode'): if self.getConst() is not None: outfile.write(' Const="%s"' % (self.getConst(), )) outfile.write(' Name="%s"' % (self.getName(), )) if self.getKeyword() is not None: outfile.write(' Keyword="%s"' % (self.getKeyword(), )) def exportChildren(self, outfile, level, name_='Methode'): if self.Documentation: self.Documentation.export(outfile, level) for Parameter_ in self.getParameter(): Parameter_.export(outfile, level) def exportLiteral(self, outfile, level, name_='Methode'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Const = "%s",\n' % (self.getConst(),)) showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) showIndent(outfile, level) outfile.write('Keyword = "%s",\n' % (self.getKeyword(),)) def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) outfile.write('Documentation=Documentation(\n') self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('Parameter=[\n') level += 1 for Parameter in self.Parameter: showIndent(outfile, level) outfile.write('Parameter(\n') Parameter.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('Const'): if attrs.get('Const').value in ('true', '1'): self.Const = 1 elif attrs.get('Const').value in ('false', '0'): self.Const = 0 else: raise ValueError('Bad boolean attribute (Const)') if attrs.get('Name'): self.Name = attrs.get('Name').value if attrs.get('Keyword'): if attrs.get('Keyword').value in ('true', '1'): self.Keyword = 1 elif attrs.get('Keyword').value in ('false', '0'): self.Keyword = 0 else: raise ValueError('Bad boolean attribute (Keyword)') def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Documentation': obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Parameter': obj_ = Parameter.factory() obj_.build(child_) self.Parameter.append(obj_) # end class Methode class Attribute: subclass = None def __init__(self, ReadOnly=0, Name='', Documentation=None, Parameter=None): self.ReadOnly = ReadOnly self.Name = Name self.Documentation = Documentation self.Parameter = Parameter def factory(*args_, **kwargs_): if Attribute.subclass: return Attribute.subclass(*args_, **kwargs_) else: return Attribute(*args_, **kwargs_) factory = staticmethod(factory) def getDocumentation(self): return self.Documentation def setDocumentation(self, Documentation): self.Documentation = Documentation def getParameter(self): return self.Parameter def setParameter(self, Parameter): self.Parameter = Parameter def getReadonly(self): return self.ReadOnly def setReadonly(self, ReadOnly): self.ReadOnly = ReadOnly def getName(self): return self.Name def setName(self, Name): self.Name = Name def export(self, outfile, level, name_='Attribute'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='Attribute') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Attribute'): outfile.write(' ReadOnly="%s"' % (self.getReadonly(), )) outfile.write(' Name="%s"' % (self.getName(), )) def exportChildren(self, outfile, level, name_='Attribute'): if self.Documentation: self.Documentation.export(outfile, level) if self.Parameter: self.Parameter.export(outfile, level) def exportLiteral(self, outfile, level, name_='Attribute'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('ReadOnly = "%s",\n' % (self.getReadonly(),)) showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) outfile.write('Documentation=Documentation(\n') self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') if self.Parameter: showIndent(outfile, level) outfile.write('Parameter=Parameter(\n') self.Parameter.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('ReadOnly'): if attrs.get('ReadOnly').value in ('true', '1'): self.ReadOnly = 1 elif attrs.get('ReadOnly').value in ('false', '0'): self.ReadOnly = 0 else: raise ValueError('Bad boolean attribute (ReadOnly)') if attrs.get('Name'): self.Name = attrs.get('Name').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Documentation': obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Parameter': obj_ = Parameter.factory() obj_.build(child_) self.setParameter(obj_) # end class Attribute class Sequence: subclass = None def __init__(self, sq_slice=0, sq_item=0, sq_concat=0, sq_inplace_repeat=0, sq_ass_slice=0, sq_contains=0, sq_ass_item=0, sq_repeat=0, sq_length=0, sq_inplace_concat=0, valueOf_=''): self.sq_slice = sq_slice self.sq_item = sq_item self.sq_concat = sq_concat self.sq_inplace_repeat = sq_inplace_repeat self.sq_ass_slice = sq_ass_slice self.sq_contains = sq_contains self.sq_ass_item = sq_ass_item self.sq_repeat = sq_repeat self.sq_length = sq_length self.sq_inplace_concat = sq_inplace_concat self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if Sequence.subclass: return Sequence.subclass(*args_, **kwargs_) else: return Sequence(*args_, **kwargs_) factory = staticmethod(factory) def getSq_slice(self): return self.sq_slice def setSq_slice(self, sq_slice): self.sq_slice = sq_slice def getSq_item(self): return self.sq_item def setSq_item(self, sq_item): self.sq_item = sq_item def getSq_concat(self): return self.sq_concat def setSq_concat(self, sq_concat): self.sq_concat = sq_concat def getSq_inplace_repeat(self): return self.sq_inplace_repeat def setSq_inplace_repeat(self, sq_inplace_repeat): self.sq_inplace_repeat = sq_inplace_repeat def getSq_ass_slice(self): return self.sq_ass_slice def setSq_ass_slice(self, sq_ass_slice): self.sq_ass_slice = sq_ass_slice def getSq_contains(self): return self.sq_contains def setSq_contains(self, sq_contains): self.sq_contains = sq_contains def getSq_ass_item(self): return self.sq_ass_item def setSq_ass_item(self, sq_ass_item): self.sq_ass_item = sq_ass_item def getSq_repeat(self): return self.sq_repeat def setSq_repeat(self, sq_repeat): self.sq_repeat = sq_repeat def getSq_length(self): return self.sq_length def setSq_length(self, sq_length): self.sq_length = sq_length def getSq_inplace_concat(self): return self.sq_inplace_concat def setSq_inplace_concat(self, sq_inplace_concat): self.sq_inplace_concat = sq_inplace_concat def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, name_='Sequence'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='Sequence') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Sequence'): outfile.write(' sq_slice="%s"' % (self.getSq_slice(), )) outfile.write(' sq_item="%s"' % (self.getSq_item(), )) outfile.write(' sq_concat="%s"' % (self.getSq_concat(), )) outfile.write(' sq_inplace_repeat="%s"' % (self.getSq_inplace_repeat(), )) outfile.write(' sq_ass_slice="%s"' % (self.getSq_ass_slice(), )) outfile.write(' sq_contains="%s"' % (self.getSq_contains(), )) outfile.write(' sq_ass_item="%s"' % (self.getSq_ass_item(), )) outfile.write(' sq_repeat="%s"' % (self.getSq_repeat(), )) outfile.write(' sq_length="%s"' % (self.getSq_length(), )) outfile.write(' sq_inplace_concat="%s"' % (self.getSq_inplace_concat(), )) def exportChildren(self, outfile, level, name_='Sequence'): outfile.write(self.valueOf_) def exportLiteral(self, outfile, level, name_='Sequence'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('sq_slice = "%s",\n' % (self.getSq_slice(),)) showIndent(outfile, level) outfile.write('sq_item = "%s",\n' % (self.getSq_item(),)) showIndent(outfile, level) outfile.write('sq_concat = "%s",\n' % (self.getSq_concat(),)) showIndent(outfile, level) outfile.write('sq_inplace_repeat = "%s",\n' % (self.getSq_inplace_repeat(),)) showIndent(outfile, level) outfile.write('sq_ass_slice = "%s",\n' % (self.getSq_ass_slice(),)) showIndent(outfile, level) outfile.write('sq_contains = "%s",\n' % (self.getSq_contains(),)) showIndent(outfile, level) outfile.write('sq_ass_item = "%s",\n' % (self.getSq_ass_item(),)) showIndent(outfile, level) outfile.write('sq_repeat = "%s",\n' % (self.getSq_repeat(),)) showIndent(outfile, level) outfile.write('sq_length = "%s",\n' % (self.getSq_length(),)) showIndent(outfile, level) outfile.write('sq_inplace_concat = "%s",\n' % (self.getSq_inplace_concat(),)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('sq_slice'): if attrs.get('sq_slice').value in ('true', '1'): self.sq_slice = 1 elif attrs.get('sq_slice').value in ('false', '0'): self.sq_slice = 0 else: raise ValueError('Bad boolean attribute (sq_slice)') if attrs.get('sq_item'): if attrs.get('sq_item').value in ('true', '1'): self.sq_item = 1 elif attrs.get('sq_item').value in ('false', '0'): self.sq_item = 0 else: raise ValueError('Bad boolean attribute (sq_item)') if attrs.get('sq_concat'): if attrs.get('sq_concat').value in ('true', '1'): self.sq_concat = 1 elif attrs.get('sq_concat').value in ('false', '0'): self.sq_concat = 0 else: raise ValueError('Bad boolean attribute (sq_concat)') if attrs.get('sq_inplace_repeat'): if attrs.get('sq_inplace_repeat').value in ('true', '1'): self.sq_inplace_repeat = 1 elif attrs.get('sq_inplace_repeat').value in ('false', '0'): self.sq_inplace_repeat = 0 else: raise ValueError('Bad boolean attribute (sq_inplace_repeat)') if attrs.get('sq_ass_slice'): if attrs.get('sq_ass_slice').value in ('true', '1'): self.sq_ass_slice = 1 elif attrs.get('sq_ass_slice').value in ('false', '0'): self.sq_ass_slice = 0 else: raise ValueError('Bad boolean attribute (sq_ass_slice)') if attrs.get('sq_contains'): if attrs.get('sq_contains').value in ('true', '1'): self.sq_contains = 1 elif attrs.get('sq_contains').value in ('false', '0'): self.sq_contains = 0 else: raise ValueError('Bad boolean attribute (sq_contains)') if attrs.get('sq_ass_item'): if attrs.get('sq_ass_item').value in ('true', '1'): self.sq_ass_item = 1 elif attrs.get('sq_ass_item').value in ('false', '0'): self.sq_ass_item = 0 else: raise ValueError('Bad boolean attribute (sq_ass_item)') if attrs.get('sq_repeat'): if attrs.get('sq_repeat').value in ('true', '1'): self.sq_repeat = 1 elif attrs.get('sq_repeat').value in ('false', '0'): self.sq_repeat = 0 else: raise ValueError('Bad boolean attribute (sq_repeat)') if attrs.get('sq_length'): if attrs.get('sq_length').value in ('true', '1'): self.sq_length = 1 elif attrs.get('sq_length').value in ('false', '0'): self.sq_length = 0 else: raise ValueError('Bad boolean attribute (sq_length)') if attrs.get('sq_inplace_concat'): if attrs.get('sq_inplace_concat').value in ('true', '1'): self.sq_inplace_concat = 1 elif attrs.get('sq_inplace_concat').value in ('false', '0'): self.sq_inplace_concat = 0 else: raise ValueError('Bad boolean attribute (sq_inplace_concat)') def buildChildren(self, child_, nodeName_): self.valueOf_ = '' for child in child_.childNodes: if child.nodeType == Node.TEXT_NODE: self.valueOf_ += child.nodeValue # end class Sequence class Module: subclass = None def __init__(self, Name='', Documentation=None, Dependencies=None, Content=None): self.Name = Name self.Documentation = Documentation self.Dependencies = Dependencies self.Content = Content def factory(*args_, **kwargs_): if Module.subclass: return Module.subclass(*args_, **kwargs_) else: return Module(*args_, **kwargs_) factory = staticmethod(factory) def getDocumentation(self): return self.Documentation def setDocumentation(self, Documentation): self.Documentation = Documentation def getDependencies(self): return self.Dependencies def setDependencies(self, Dependencies): self.Dependencies = Dependencies def getContent(self): return self.Content def setContent(self, Content): self.Content = Content def getName(self): return self.Name def setName(self, Name): self.Name = Name def export(self, outfile, level, name_='Module'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='Module') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Module'): outfile.write(' Name="%s"' % (self.getName(), )) def exportChildren(self, outfile, level, name_='Module'): if self.Documentation: self.Documentation.export(outfile, level) if self.Dependencies: self.Dependencies.export(outfile, level) if self.Content: self.Content.export(outfile, level) def exportLiteral(self, outfile, level, name_='Module'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) outfile.write('Documentation=Documentation(\n') self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') if self.Dependencies: showIndent(outfile, level) outfile.write('Dependencies=Dependencies(\n') self.Dependencies.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') if self.Content: showIndent(outfile, level) outfile.write('Content=Content(\n') self.Content.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('Name'): self.Name = attrs.get('Name').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Documentation': obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Dependencies': obj_ = Dependencies.factory() obj_.build(child_) self.setDependencies(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Content': obj_ = Content.factory() obj_.build(child_) self.setContent(obj_) # end class Module class Dependencies: subclass = None def __init__(self, Module=None): if Module is None: self.Module = [] else: self.Module = Module def factory(*args_, **kwargs_): if Dependencies.subclass: return Dependencies.subclass(*args_, **kwargs_) else: return Dependencies(*args_, **kwargs_) factory = staticmethod(factory) def getModule(self): return self.Module def setModule(self, Module): self.Module = Module def addModule(self, value): self.Module.append(value) def insertModule(self, index, value): self.Module[index] = value def export(self, outfile, level, name_='Dependencies'): showIndent(outfile, level) outfile.write('<%s>\n' % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Dependencies'): pass def exportChildren(self, outfile, level, name_='Dependencies'): for Module_ in self.getModule(): Module_.export(outfile, level) def exportLiteral(self, outfile, level, name_='Dependencies'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Module=[\n') level += 1 for Module in self.Module: showIndent(outfile, level) outfile.write('Module(\n') Module.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Module': obj_ = Module.factory() obj_.build(child_) self.Module.append(obj_) # end class Dependencies class Content: subclass = None def __init__(self, Property=None, Feature=None, DocObject=None, GuiCommand=None, PreferencesPage=None): if Property is None: self.Property = [] else: self.Property = Property if Feature is None: self.Feature = [] else: self.Feature = Feature if DocObject is None: self.DocObject = [] else: self.DocObject = DocObject if GuiCommand is None: self.GuiCommand = [] else: self.GuiCommand = GuiCommand if PreferencesPage is None: self.PreferencesPage = [] else: self.PreferencesPage = PreferencesPage def factory(*args_, **kwargs_): if Content.subclass: return Content.subclass(*args_, **kwargs_) else: return Content(*args_, **kwargs_) factory = staticmethod(factory) def getProperty(self): return self.Property def setProperty(self, Property): self.Property = Property def addProperty(self, value): self.Property.append(value) def insertProperty(self, index, value): self.Property[index] = value def getFeature(self): return self.Feature def setFeature(self, Feature): self.Feature = Feature def addFeature(self, value): self.Feature.append(value) def insertFeature(self, index, value): self.Feature[index] = value def getDocobject(self): return self.DocObject def setDocobject(self, DocObject): self.DocObject = DocObject def addDocobject(self, value): self.DocObject.append(value) def insertDocobject(self, index, value): self.DocObject[index] = value def getGuicommand(self): return self.GuiCommand def setGuicommand(self, GuiCommand): self.GuiCommand = GuiCommand def addGuicommand(self, value): self.GuiCommand.append(value) def insertGuicommand(self, index, value): self.GuiCommand[index] = value def getPreferencespage(self): return self.PreferencesPage def setPreferencespage(self, PreferencesPage): self.PreferencesPage = PreferencesPage def addPreferencespage(self, value): self.PreferencesPage.append(value) def insertPreferencespage(self, index, value): self.PreferencesPage[index] = value def export(self, outfile, level, name_='Content'): showIndent(outfile, level) outfile.write('<%s>\n' % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Content'): pass def exportChildren(self, outfile, level, name_='Content'): for Property_ in self.getProperty(): Property_.export(outfile, level) for Feature_ in self.getFeature(): Feature_.export(outfile, level) for DocObject_ in self.getDocobject(): DocObject_.export(outfile, level) for GuiCommand_ in self.getGuicommand(): showIndent(outfile, level) outfile.write('<GuiCommand>%s</GuiCommand>\n' % quote_xml(GuiCommand_)) for PreferencesPage_ in self.getPreferencespage(): showIndent(outfile, level) outfile.write('<PreferencesPage>%s</PreferencesPage>\n' % quote_xml(PreferencesPage_)) def exportLiteral(self, outfile, level, name_='Content'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Property=[\n') level += 1 for Property in self.Property: showIndent(outfile, level) outfile.write('Property(\n') Property.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('Feature=[\n') level += 1 for Feature in self.Feature: showIndent(outfile, level) outfile.write('Feature(\n') Feature.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('DocObject=[\n') level += 1 for DocObject in self.DocObject: showIndent(outfile, level) outfile.write('DocObject(\n') DocObject.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('GuiCommand=[\n') level += 1 for GuiCommand in self.GuiCommand: showIndent(outfile, level) outfile.write('%s,\n' % quote_python(GuiCommand)) level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('PreferencesPage=[\n') level += 1 for PreferencesPage in self.PreferencesPage: showIndent(outfile, level) outfile.write('%s,\n' % quote_python(PreferencesPage)) level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Property': obj_ = Property.factory() obj_.build(child_) self.Property.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Feature': obj_ = Feature.factory() obj_.build(child_) self.Feature.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'DocObject': obj_ = DocObject.factory() obj_.build(child_) self.DocObject.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'GuiCommand': GuiCommand_ = '' for text__content_ in child_.childNodes: GuiCommand_ += text__content_.nodeValue self.GuiCommand.append(GuiCommand_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'PreferencesPage': PreferencesPage_ = '' for text__content_ in child_.childNodes: PreferencesPage_ += text__content_.nodeValue self.PreferencesPage.append(PreferencesPage_) # end class Content class Feature: subclass = None def __init__(self, Name='', Documentation=None, Property=None, ViewProvider=None): self.Name = Name self.Documentation = Documentation if Property is None: self.Property = [] else: self.Property = Property self.ViewProvider = ViewProvider def factory(*args_, **kwargs_): if Feature.subclass: return Feature.subclass(*args_, **kwargs_) else: return Feature(*args_, **kwargs_) factory = staticmethod(factory) def getDocumentation(self): return self.Documentation def setDocumentation(self, Documentation): self.Documentation = Documentation def getProperty(self): return self.Property def setProperty(self, Property): self.Property = Property def addProperty(self, value): self.Property.append(value) def insertProperty(self, index, value): self.Property[index] = value def getViewprovider(self): return self.ViewProvider def setViewprovider(self, ViewProvider): self.ViewProvider = ViewProvider def getName(self): return self.Name def setName(self, Name): self.Name = Name def export(self, outfile, level, name_='Feature'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='Feature') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Feature'): outfile.write(' Name="%s"' % (self.getName(), )) def exportChildren(self, outfile, level, name_='Feature'): if self.Documentation: self.Documentation.export(outfile, level) for Property_ in self.getProperty(): Property_.export(outfile, level) if self.ViewProvider: self.ViewProvider.export(outfile, level) def exportLiteral(self, outfile, level, name_='Feature'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) outfile.write('Documentation=Documentation(\n') self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('Property=[\n') level += 1 for Property in self.Property: showIndent(outfile, level) outfile.write('Property(\n') Property.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.ViewProvider: showIndent(outfile, level) outfile.write('ViewProvider=ViewProvider(\n') self.ViewProvider.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('Name'): self.Name = attrs.get('Name').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Documentation': obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Property': obj_ = Property.factory() obj_.build(child_) self.Property.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'ViewProvider': obj_ = ViewProvider.factory() obj_.build(child_) self.setViewprovider(obj_) # end class Feature class DocObject: subclass = None def __init__(self, Name='', Documentation=None, Property=None): self.Name = Name self.Documentation = Documentation if Property is None: self.Property = [] else: self.Property = Property def factory(*args_, **kwargs_): if DocObject.subclass: return DocObject.subclass(*args_, **kwargs_) else: return DocObject(*args_, **kwargs_) factory = staticmethod(factory) def getDocumentation(self): return self.Documentation def setDocumentation(self, Documentation): self.Documentation = Documentation def getProperty(self): return self.Property def setProperty(self, Property): self.Property = Property def addProperty(self, value): self.Property.append(value) def insertProperty(self, index, value): self.Property[index] = value def getName(self): return self.Name def setName(self, Name): self.Name = Name def export(self, outfile, level, name_='DocObject'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='DocObject') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='DocObject'): outfile.write(' Name="%s"' % (self.getName(), )) def exportChildren(self, outfile, level, name_='DocObject'): if self.Documentation: self.Documentation.export(outfile, level) for Property_ in self.getProperty(): Property_.export(outfile, level) def exportLiteral(self, outfile, level, name_='DocObject'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) outfile.write('Documentation=Documentation(\n') self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('Property=[\n') level += 1 for Property in self.Property: showIndent(outfile, level) outfile.write('Property(\n') Property.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('Name'): self.Name = attrs.get('Name').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Documentation': obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Property': obj_ = Property.factory() obj_.build(child_) self.Property.append(obj_) # end class DocObject class Property: subclass = None def __init__(self, Type='', Name='', StartValue='', Documentation=None): self.Type = Type self.Name = Name self.StartValue = StartValue self.Documentation = Documentation def factory(*args_, **kwargs_): if Property.subclass: return Property.subclass(*args_, **kwargs_) else: return Property(*args_, **kwargs_) factory = staticmethod(factory) def getDocumentation(self): return self.Documentation def setDocumentation(self, Documentation): self.Documentation = Documentation def getType(self): return self.Type def setType(self, Type): self.Type = Type def getName(self): return self.Name def setName(self, Name): self.Name = Name def getStartvalue(self): return self.StartValue def setStartvalue(self, StartValue): self.StartValue = StartValue def export(self, outfile, level, name_='Property'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='Property') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Property'): outfile.write(' Type="%s"' % (self.getType(), )) outfile.write(' Name="%s"' % (self.getName(), )) if self.getStartvalue() is not None: outfile.write(' StartValue="%s"' % (self.getStartvalue(), )) def exportChildren(self, outfile, level, name_='Property'): if self.Documentation: self.Documentation.export(outfile, level) def exportLiteral(self, outfile, level, name_='Property'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Type = "%s",\n' % (self.getType(),)) showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) showIndent(outfile, level) outfile.write('StartValue = "%s",\n' % (self.getStartvalue(),)) def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) outfile.write('Documentation=Documentation(\n') self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('Type'): self.Type = attrs.get('Type').value if attrs.get('Name'): self.Name = attrs.get('Name').value if attrs.get('StartValue'): self.StartValue = attrs.get('StartValue').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Documentation': obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) # end class Property class Documentation: subclass = None def __init__(self, Author=None, DeveloperDocu='', UserDocu=''): self.Author = Author self.DeveloperDocu = DeveloperDocu self.UserDocu = UserDocu def factory(*args_, **kwargs_): if Documentation.subclass: return Documentation.subclass(*args_, **kwargs_) else: return Documentation(*args_, **kwargs_) factory = staticmethod(factory) def getAuthor(self): return self.Author def setAuthor(self, Author): self.Author = Author def getDeveloperdocu(self): return self.DeveloperDocu def setDeveloperdocu(self, DeveloperDocu): self.DeveloperDocu = DeveloperDocu def getUserdocu(self): return self.UserDocu def setUserdocu(self, UserDocu): self.UserDocu = UserDocu def export(self, outfile, level, name_='Documentation'): showIndent(outfile, level) outfile.write('<%s>\n' % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Documentation'): pass def exportChildren(self, outfile, level, name_='Documentation'): if self.Author: self.Author.export(outfile, level) showIndent(outfile, level) outfile.write('<DeveloperDocu>%s</DeveloperDocu>\n' % quote_xml(self.getDeveloperdocu())) showIndent(outfile, level) outfile.write('<UserDocu>%s</UserDocu>\n' % quote_xml(self.getUserdocu())) def exportLiteral(self, outfile, level, name_='Documentation'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): if self.Author: showIndent(outfile, level) outfile.write('Author=Author(\n') self.Author.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('DeveloperDocu=%s,\n' % quote_python(self.getDeveloperdocu())) showIndent(outfile, level) outfile.write('UserDocu=%s,\n' % quote_python(self.getUserdocu())) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Author': obj_ = Author.factory() obj_.build(child_) self.setAuthor(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'DeveloperDocu': DeveloperDocu_ = '' for text__content_ in child_.childNodes: DeveloperDocu_ += text__content_.nodeValue self.DeveloperDocu = DeveloperDocu_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'UserDocu': UserDocu_ = '' for text__content_ in child_.childNodes: UserDocu_ += text__content_.nodeValue self.UserDocu = UserDocu_ # end class Documentation class Author: subclass = None def __init__(self, Name='', Licence='', EMail='', valueOf_=''): self.Name = Name self.Licence = Licence self.EMail = EMail self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if Author.subclass: return Author.subclass(*args_, **kwargs_) else: return Author(*args_, **kwargs_) factory = staticmethod(factory) def getName(self): return self.Name def setName(self, Name): self.Name = Name def getLicence(self): return self.Licence def setLicence(self, Licence): self.Licence = Licence def getEmail(self): return self.EMail def setEmail(self, EMail): self.EMail = EMail def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, name_='Author'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='Author') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Author'): outfile.write(' Name="%s"' % (self.getName(), )) if self.getLicence() is not None: outfile.write(' Licence="%s"' % (self.getLicence(), )) outfile.write(' EMail="%s"' % (self.getEmail(), )) def exportChildren(self, outfile, level, name_='Author'): outfile.write(self.valueOf_) def exportLiteral(self, outfile, level, name_='Author'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) showIndent(outfile, level) outfile.write('Licence = "%s",\n' % (self.getLicence(),)) showIndent(outfile, level) outfile.write('EMail = "%s",\n' % (self.getEmail(),)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('Name'): self.Name = attrs.get('Name').value if attrs.get('Licence'): self.Licence = attrs.get('Licence').value if attrs.get('EMail'): self.EMail = attrs.get('EMail').value def buildChildren(self, child_, nodeName_): self.valueOf_ = '' for child in child_.childNodes: if child.nodeType == Node.TEXT_NODE: self.valueOf_ += child.nodeValue # end class Author class ViewProvider: subclass = None def __init__(self, Property=None): if Property is None: self.Property = [] else: self.Property = Property def factory(*args_, **kwargs_): if ViewProvider.subclass: return ViewProvider.subclass(*args_, **kwargs_) else: return ViewProvider(*args_, **kwargs_) factory = staticmethod(factory) def getProperty(self): return self.Property def setProperty(self, Property): self.Property = Property def addProperty(self, value): self.Property.append(value) def insertProperty(self, index, value): self.Property[index] = value def export(self, outfile, level, name_='ViewProvider'): showIndent(outfile, level) outfile.write('<%s>\n' % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='ViewProvider'): pass def exportChildren(self, outfile, level, name_='ViewProvider'): for Property_ in self.getProperty(): Property_.export(outfile, level) def exportLiteral(self, outfile, level, name_='ViewProvider'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Property=[\n') level += 1 for Property in self.Property: showIndent(outfile, level) outfile.write('Property(\n') Property.exportLiteral(outfile, level) showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'Property': obj_ = Property.factory() obj_.build(child_) self.Property.append(obj_) # end class ViewProvider class Parameter: subclass = None def __init__(self, Type='', Name='', valueOf_=''): self.Type = Type self.Name = Name self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if Parameter.subclass: return Parameter.subclass(*args_, **kwargs_) else: return Parameter(*args_, **kwargs_) factory = staticmethod(factory) def getType(self): return self.Type def setType(self, Type): self.Type = Type def getName(self): return self.Name def setName(self, Name): self.Name = Name def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, name_='Parameter'): showIndent(outfile, level) outfile.write('<%s' % (name_, )) self.exportAttributes(outfile, level, name_='Parameter') outfile.write('>\n') self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) outfile.write('</%s>\n' % name_) def exportAttributes(self, outfile, level, name_='Parameter'): outfile.write(' Type="%s"' % (self.getType(), )) outfile.write(' Name="%s"' % (self.getName(), )) def exportChildren(self, outfile, level, name_='Parameter'): outfile.write(self.valueOf_) def exportLiteral(self, outfile, level, name_='Parameter'): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Type = "%s",\n' % (self.getType(),)) showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('Type'): self.Type = attrs.get('Type').value if attrs.get('Name'): self.Name = attrs.get('Name').value def buildChildren(self, child_, nodeName_): self.valueOf_ = '' for child in child_.childNodes: if child.nodeType == Node.TEXT_NODE: self.valueOf_ += child.nodeValue # end class Parameter from xml.sax import handler, make_parser class SaxStackElement: def __init__(self, name='', obj=None): self.name = name self.obj = obj self.content = '' # # SAX handler # class SaxGeneratemodelHandler(handler.ContentHandler): def __init__(self): self.stack = [] self.root = None def getRoot(self): return self.root def setDocumentLocator(self, locator): self.locator = locator def showError(self, msg): print '*** (showError):', msg sys.exit(-1) def startElement(self, name, attrs): done = 0 if name == 'GenerateModel': obj = GenerateModel.factory() stackObj = SaxStackElement('GenerateModel', obj) self.stack.append(stackObj) done = 1 elif name == 'Module': obj = Module.factory() stackObj = SaxStackElement('Module', obj) self.stack.append(stackObj) done = 1 elif name == 'PythonExport': obj = PythonExport.factory() val = attrs.get('FatherNamespace', None) if val is not None: obj.setFathernamespace(val) val = attrs.get('RichCompare', None) if val is not None: if val in ('true', '1'): obj.setRichcompare(1) elif val in ('false', '0'): obj.setRichcompare(0) else: self.reportError('"RichCompare" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('Name', None) if val is not None: obj.setName(val) val = attrs.get('Reference', None) if val is not None: if val in ('true', '1'): obj.setReference(1) elif val in ('false', '0'): obj.setReference(0) else: self.reportError('"Reference" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('FatherInclude', None) if val is not None: obj.setFatherinclude(val) val = attrs.get('Father', None) if val is not None: obj.setFather(val) val = attrs.get('Namespace', None) if val is not None: obj.setNamespace(val) val = attrs.get('Twin', None) if val is not None: obj.setTwin(val) val = attrs.get('Constructor', None) if val is not None: if val in ('true', '1'): obj.setConstructor(1) elif val in ('false', '0'): obj.setConstructor(0) else: self.reportError('"Constructor" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('Initialization', None) if val is not None: if val in ('true', '1'): obj.setInitialization(1) elif val in ('false', '0'): obj.setInitialization(0) else: self.reportError('"Initialization" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('TwinPointer', None) if val is not None: obj.setTwinpointer(val) val = attrs.get('Include', None) if val is not None: obj.setInclude(val) val = attrs.get('NumberProtocol', None) if val is not None: if val in ('true', '1'): obj.setNumberprotocol(1) elif val in ('false', '0'): obj.setNumberprotocol(0) else: self.reportError('"NumberProtocol" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('Delete', None) if val is not None: if val in ('true', '1'): obj.setDelete(1) elif val in ('false', '0'): obj.setDelete(0) else: self.reportError('"Delete" attribute must be boolean ("true", "1", "false", "0")') stackObj = SaxStackElement('PythonExport', obj) self.stack.append(stackObj) done = 1 elif name == 'Documentation': obj = Documentation.factory() stackObj = SaxStackElement('Documentation', obj) self.stack.append(stackObj) done = 1 elif name == 'Methode': obj = Methode.factory() val = attrs.get('Const', None) if val is not None: if val in ('true', '1'): obj.setConst(1) elif val in ('false', '0'): obj.setConst(0) else: self.reportError('"Const" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('Name', None) if val is not None: obj.setName(val) val = attrs.get('Keyword', None) if val is not None: if val in ('true', '1'): obj.setKeyword(1) elif val in ('false', '0'): obj.setKeyword(0) else: self.reportError('"Keyword" attribute must be boolean ("true", "1", "false", "0")') stackObj = SaxStackElement('Methode', obj) self.stack.append(stackObj) done = 1 elif name == 'Parameter': obj = Parameter.factory() val = attrs.get('Type', None) if val is not None: obj.setType(val) val = attrs.get('Name', None) if val is not None: obj.setName(val) stackObj = SaxStackElement('Parameter', obj) self.stack.append(stackObj) done = 1 elif name == 'Attribute': obj = Attribute.factory() val = attrs.get('ReadOnly', None) if val is not None: if val in ('true', '1'): obj.setReadonly(1) elif val in ('false', '0'): obj.setReadonly(0) else: self.reportError('"ReadOnly" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('Name', None) if val is not None: obj.setName(val) stackObj = SaxStackElement('Attribute', obj) self.stack.append(stackObj) done = 1 elif name == 'Sequence': obj = Sequence.factory() val = attrs.get('sq_slice', None) if val is not None: if val in ('true', '1'): obj.setSq_slice(1) elif val in ('false', '0'): obj.setSq_slice(0) else: self.reportError('"sq_slice" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_item', None) if val is not None: if val in ('true', '1'): obj.setSq_item(1) elif val in ('false', '0'): obj.setSq_item(0) else: self.reportError('"sq_item" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_concat', None) if val is not None: if val in ('true', '1'): obj.setSq_concat(1) elif val in ('false', '0'): obj.setSq_concat(0) else: self.reportError('"sq_concat" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_inplace_repeat', None) if val is not None: if val in ('true', '1'): obj.setSq_inplace_repeat(1) elif val in ('false', '0'): obj.setSq_inplace_repeat(0) else: self.reportError('"sq_inplace_repeat" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_ass_slice', None) if val is not None: if val in ('true', '1'): obj.setSq_ass_slice(1) elif val in ('false', '0'): obj.setSq_ass_slice(0) else: self.reportError('"sq_ass_slice" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_contains', None) if val is not None: if val in ('true', '1'): obj.setSq_contains(1) elif val in ('false', '0'): obj.setSq_contains(0) else: self.reportError('"sq_contains" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_ass_item', None) if val is not None: if val in ('true', '1'): obj.setSq_ass_item(1) elif val in ('false', '0'): obj.setSq_ass_item(0) else: self.reportError('"sq_ass_item" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_repeat', None) if val is not None: if val in ('true', '1'): obj.setSq_repeat(1) elif val in ('false', '0'): obj.setSq_repeat(0) else: self.reportError('"sq_repeat" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_length', None) if val is not None: if val in ('true', '1'): obj.setSq_length(1) elif val in ('false', '0'): obj.setSq_length(0) else: self.reportError('"sq_length" attribute must be boolean ("true", "1", "false", "0")') val = attrs.get('sq_inplace_concat', None) if val is not None: if val in ('true', '1'): obj.setSq_inplace_concat(1) elif val in ('false', '0'): obj.setSq_inplace_concat(0) else: self.reportError('"sq_inplace_concat" attribute must be boolean ("true", "1", "false", "0")') stackObj = SaxStackElement('Sequence', obj) self.stack.append(stackObj) done = 1 elif name == 'CustomAttributes': stackObj = SaxStackElement('CustomAttributes', None) self.stack.append(stackObj) done = 1 elif name == 'ClassDeclarations': stackObj = SaxStackElement('ClassDeclarations', None) self.stack.append(stackObj) done = 1 elif name == 'Dependencies': obj = Dependencies.factory() stackObj = SaxStackElement('Dependencies', obj) self.stack.append(stackObj) done = 1 elif name == 'Content': obj = Content.factory() stackObj = SaxStackElement('Content', obj) self.stack.append(stackObj) done = 1 elif name == 'Property': obj = Property.factory() stackObj = SaxStackElement('Property', obj) self.stack.append(stackObj) done = 1 elif name == 'Feature': obj = Feature.factory() val = attrs.get('Name', None) if val is not None: obj.setName(val) stackObj = SaxStackElement('Feature', obj) self.stack.append(stackObj) done = 1 elif name == 'ViewProvider': obj = ViewProvider.factory() stackObj = SaxStackElement('ViewProvider', obj) self.stack.append(stackObj) done = 1 elif name == 'DocObject': obj = DocObject.factory() val = attrs.get('Name', None) if val is not None: obj.setName(val) stackObj = SaxStackElement('DocObject', obj) self.stack.append(stackObj) done = 1 elif name == 'GuiCommand': stackObj = SaxStackElement('GuiCommand', None) self.stack.append(stackObj) done = 1 elif name == 'PreferencesPage': stackObj = SaxStackElement('PreferencesPage', None) self.stack.append(stackObj) done = 1 elif name == 'Author': obj = Author.factory() val = attrs.get('Name', None) if val is not None: obj.setName(val) val = attrs.get('Licence', None) if val is not None: obj.setLicence(val) val = attrs.get('EMail', None) if val is not None: obj.setEmail(val) stackObj = SaxStackElement('Author', obj) self.stack.append(stackObj) done = 1 elif name == 'DeveloperDocu': stackObj = SaxStackElement('DeveloperDocu', None) self.stack.append(stackObj) done = 1 elif name == 'UserDocu': stackObj = SaxStackElement('UserDocu', None) self.stack.append(stackObj) done = 1 if not done: self.reportError('"%s" element not allowed here.' % name) def endElement(self, name): done = 0 if name == 'GenerateModel': if len(self.stack) == 1: self.root = self.stack[-1].obj self.stack.pop() done = 1 elif name == 'Module': if len(self.stack) >= 2: self.stack[-2].obj.addModule(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'PythonExport': if len(self.stack) >= 2: self.stack[-2].obj.addPythonexport(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'Documentation': if len(self.stack) >= 2: self.stack[-2].obj.setDocumentation(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'Methode': if len(self.stack) >= 2: self.stack[-2].obj.addMethode(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'Parameter': if len(self.stack) >= 2: self.stack[-2].obj.addParameter(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'Attribute': if len(self.stack) >= 2: self.stack[-2].obj.addAttribute(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'Sequence': if len(self.stack) >= 2: self.stack[-2].obj.setSequence(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'CustomAttributes': if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setCustomattributes(content) self.stack.pop() done = 1 elif name == 'ClassDeclarations': if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setClassdeclarations(content) self.stack.pop() done = 1 elif name == 'Dependencies': if len(self.stack) >= 2: self.stack[-2].obj.setDependencies(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'Content': if len(self.stack) >= 2: self.stack[-2].obj.setContent(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'Property': if len(self.stack) >= 2: self.stack[-2].obj.addProperty(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'Feature': if len(self.stack) >= 2: self.stack[-2].obj.addFeature(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'ViewProvider': if len(self.stack) >= 2: self.stack[-2].obj.setViewprovider(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'DocObject': if len(self.stack) >= 2: self.stack[-2].obj.addDocobject(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'GuiCommand': if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.addGuicommand(content) self.stack.pop() done = 1 elif name == 'PreferencesPage': if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.addPreferencespage(content) self.stack.pop() done = 1 elif name == 'Author': if len(self.stack) >= 2: self.stack[-2].obj.setAuthor(self.stack[-1].obj) self.stack.pop() done = 1 elif name == 'DeveloperDocu': if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setDeveloperdocu(content) self.stack.pop() done = 1 elif name == 'UserDocu': if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setUserdocu(content) self.stack.pop() done = 1 if not done: self.reportError('"%s" element not allowed here.' % name) def characters(self, chrs, start, end): if len(self.stack) > 0: self.stack[-1].content += chrs[start:end] def reportError(self, mesg): locator = self.locator sys.stderr.write('Doc: %s Line: %d Column: %d\n' % \ (locator.getSystemId(), locator.getLineNumber(), locator.getColumnNumber() + 1)) sys.stderr.write(mesg) sys.stderr.write('\n') sys.exit(-1) #raise RuntimeError USAGE_TEXT = """ Usage: python <Parser>.py [ -s ] <in_xml_file> Options: -s Use the SAX parser, not the minidom parser. """ def usage(): print USAGE_TEXT sys.exit(-1) # # SAX handler used to determine the top level element. # class SaxSelectorHandler(handler.ContentHandler): def __init__(self): self.topElementName = None def getTopElementName(self): return self.topElementName def startElement(self, name, attrs): self.topElementName = name raise StopIteration def parseSelect(inFileName): infile = file(inFileName, 'r') topElementName = None parser = make_parser() documentHandler = SaxSelectorHandler() parser.setContentHandler(documentHandler) try: try: parser.parse(infile) except StopIteration: topElementName = documentHandler.getTopElementName() if topElementName is None: raise RuntimeError, 'no top level element' topElementName = topElementName.replace('-', '_').replace(':', '_') if topElementName not in globals(): raise RuntimeError, 'no class for top element: %s' % topElementName topElement = globals()[topElementName] infile.seek(0) doc = minidom.parse(infile) finally: infile.close() rootNode = doc.childNodes[0] rootObj = topElement.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0) return rootObj def saxParse(inFileName): parser = make_parser() documentHandler = SaxGeneratemodelHandler() parser.setDocumentHandler(documentHandler) parser.parse('file:%s' % inFileName) root = documentHandler.getRoot() sys.stdout.write('<?xml version="1.0" ?>\n') root.export(sys.stdout, 0) return root def saxParseString(inString): parser = make_parser() documentHandler = SaxGeneratemodelHandler() parser.setDocumentHandler(documentHandler) parser.feed(inString) parser.close() rootObj = documentHandler.getRoot() #sys.stdout.write('<?xml version="1.0" ?>\n') #rootObj.export(sys.stdout, 0) return rootObj def parse(inFileName): doc = minidom.parse(inFileName) rootNode = doc.documentElement rootObj = GenerateModel.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_="GenerateModel") return rootObj def parseString(inString): doc = minidom.parseString(inString) rootNode = doc.documentElement rootObj = GenerateModel.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_="GenerateModel") return rootObj def parseLiteral(inFileName): doc = minidom.parse(inFileName) rootNode = doc.documentElement rootObj = GenerateModel.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('from generateModel_Module import *\n\n') sys.stdout.write('rootObj = GenerateModel(\n') rootObj.exportLiteral(sys.stdout, 0, name_="GenerateModel") sys.stdout.write(')\n') return rootObj def main(): args = sys.argv[1:] if len(args) == 2 and args[0] == '-s': saxParse(args[1]) elif len(args) == 1: parse(args[0]) else: usage() if __name__ == '__main__': main() #import pdb #pdb.run('main()')
wood-galaxy/FreeCAD
src/Tools/generateBase/generateModel_Module.py
Python
lgpl-2.1
101,247
package train.common.entity.rollingStock; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityMinecart; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; import net.minecraftforge.common.util.Constants; import train.common.Traincraft; import train.common.api.LiquidManager; import train.common.api.SteamTrain; import train.common.library.EnumTrains; import train.common.library.GuiIDs; public class EntityLocoSteamBR80_DB extends SteamTrain { public EntityLocoSteamBR80_DB(World world) { super(world, EnumTrains.locoSteamBR80.getTankCapacity(), LiquidManager.WATER_FILTER); initLocoSteam(); } public void initLocoSteam() { fuelTrain = 0; locoInvent = new ItemStack[inventorySize]; } public EntityLocoSteamBR80_DB(World world, double d, double d1, double d2) { this(world); setPosition(d, d1 + (double) yOffset, d2); motionX = 0.0D; motionY = 0.0D; motionZ = 0.0D; prevPosX = d; prevPosY = d1; prevPosZ = d2; } @Override public void updateRiderPosition() { double distance = -0.1; double pitchRads = this.anglePitchClient * 3.141592653589793D / 180.0D; float rotationCos1 = (float) Math.cos(Math.toRadians(this.renderYaw + 90)); float rotationSin1 = (float) Math.sin(Math.toRadians((this.renderYaw + 90))); float pitch = (float) (posY + ((Math.tan(pitchRads)*distance)+getMountedYOffset()) + riddenByEntity.getYOffset()+0.45); double bogieX1 = (this.posX + (rotationCos1 * distance)); double bogieZ1 = (this.posZ + (rotationSin1* distance)); if(anglePitchClient>20 && rotationCos1 == 1){ bogieX1-=pitchRads*0.9; pitch-=pitchRads*0.3; } if(anglePitchClient>20 && rotationSin1 == 1){ bogieZ1-=pitchRads*0.9; pitch-=pitchRads*0.3; } riddenByEntity.setPosition(bogieX1, pitch, bogieZ1); //riddenByEntity.setPosition(posX, posY + getMountedYOffset() + riddenByEntity.getYOffset() + 0.45, posZ); } @Override public void setDead() { super.setDead(); isDead = true; if (worldObj.isRemote) { return; } label0: for (int i = 0; i < getSizeInventory(); i++) { ItemStack itemstack = getStackInSlot(i); if (itemstack == null) { continue; } float f = rand.nextFloat() * 0.8F + 0.1F; float f1 = rand.nextFloat() * 0.8F + 0.1F; float f2 = rand.nextFloat() * 0.8F + 0.1F; do { if (itemstack.stackSize <= 0) { continue label0; } int j = rand.nextInt(21) + 10; if (j > itemstack.stackSize) { j = itemstack.stackSize; } itemstack.stackSize -= j; EntityItem entityitem = new EntityItem(worldObj, posX + (double) f, posY + (double) f1, posZ + (double) f2, new ItemStack(itemstack.getItem(), j, itemstack.getItemDamage())); float f3 = 0.05F; entityitem.motionX = (float) rand.nextGaussian() * f3; entityitem.motionY = (float) rand.nextGaussian() * f3 + 0.2F; entityitem.motionZ = (float) rand.nextGaussian() * f3; worldObj.spawnEntityInWorld(entityitem); } while (true); } } @Override public void pressKey(int i) { if (i == 7 && riddenByEntity != null && riddenByEntity instanceof EntityPlayer) { ((EntityPlayer) riddenByEntity).openGui(Traincraft.instance, GuiIDs.LOCO, worldObj, (int) this.posX, (int) this.posY, (int) this.posZ); } } @Override public void onUpdate() { checkInvent(locoInvent[0], locoInvent[1], this); super.onUpdate(); } @Override protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); nbttagcompound.setShort("fuelTrain", (short) fuelTrain); NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < locoInvent.length; i++) { if (locoInvent[i] != null) { NBTTagCompound nbttagcompound1 = new NBTTagCompound(); nbttagcompound1.setByte("Slot", (byte) i); locoInvent[i].writeToNBT(nbttagcompound1); nbttaglist.appendTag(nbttagcompound1); } } nbttagcompound.setTag("Items", nbttaglist); } @Override protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); fuelTrain = nbttagcompound.getShort("fuelTrain"); NBTTagList nbttaglist = nbttagcompound.getTagList("Items", Constants.NBT.TAG_COMPOUND); locoInvent = new ItemStack[getSizeInventory()]; for (int i = 0; i < nbttaglist.tagCount(); i++) { NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttaglist.getCompoundTagAt(i); int j = nbttagcompound1.getByte("Slot") & 0xff; if (j >= 0 && j < locoInvent.length) { locoInvent[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1); } } } @Override public int getSizeInventory() { return inventorySize; } @Override public String getInventoryName() { return "BR80"; } @Override public boolean interactFirst(EntityPlayer entityplayer) { playerEntity = entityplayer; if ((super.interactFirst(entityplayer))) { return false; } if (!worldObj.isRemote) { if (riddenByEntity != null && (riddenByEntity instanceof EntityPlayer) && riddenByEntity != entityplayer) { return true; } entityplayer.mountEntity(this); } return true; } @Override public float getOptimalDistance(EntityMinecart cart) { float dist = 1.1F; return (dist); } @Override public boolean canBeAdjusted(EntityMinecart cart) { return canBeAdjusted; } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return true; } }
BlesseNtumble/Traincraft-5
src/main/java/train/common/entity/rollingStock/EntityLocoSteamBR80_DB.java
Java
lgpl-2.1
5,508
package tsxdk.entity.meta; import java.util.Collection; import tsxdk.entity.TsEntity; /** * Generic Type for Entity-lists. * Used For Channels, Clients, Complains * @param <E> The entity stored in this list * @param <S> The Slot for this entity (unique ID) */ public interface EntityList<E extends TsEntity, S> { /** * @param slot The identifier for this slot * @return An Entity for given slot */ E acquire (S slot); /** * Sets all registered entities to the initial state */ void setInitial (); /** * Sets all registered entities to the touched state */ void setTouched(); /** * Clears cached entities */ void clearCache(); /** * Removes all unused Entities */ void cleanUp(); /** * @return the count of entities in this list */ int getEntityCount (); TsEntity[] getIterable(); Collection<? super E> getContentList(); }
GerhardUlli/TSxBot
src/tsxdk/entity/meta/EntityList.java
Java
lgpl-2.1
928
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QTest> #ifdef Q_OS_WIN #include <winsock2.h> #endif #include <qcoreapplication.h> #include <qdatastream.h> #include <qhostaddress.h> #include <qdatetime.h> #ifdef Q_OS_UNIX #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #endif #ifdef Q_OS_VXWORKS #include <sockLib.h> #endif #include <stddef.h> #define PLATFORMSOCKETENGINE QNativeSocketEngine #define PLATFORMSOCKETENGINESTRING "QNativeSocketEngine" #include <private/qnativesocketengine_p.h> #include <qstringlist.h> #include "../../../network-settings.h" class tst_PlatformSocketEngine : public QObject { Q_OBJECT public: tst_PlatformSocketEngine(); virtual ~tst_PlatformSocketEngine(); public slots: void initTestCase(); void init(); void cleanup(); private slots: void construction(); void simpleConnectToIMAP(); void udpLoopbackTest(); void udpIPv6LoopbackTest(); void broadcastTest(); void serverTest(); void udpLoopbackPerformance(); void tcpLoopbackPerformance(); void readWriteBufferSize(); void bind(); void networkError(); void setSocketDescriptor(); void invalidSend(); void receiveUrgentData(); void tooManySockets(); }; tst_PlatformSocketEngine::tst_PlatformSocketEngine() { } tst_PlatformSocketEngine::~tst_PlatformSocketEngine() { } void tst_PlatformSocketEngine::initTestCase() { QVERIFY(QtNetworkSettings::verifyTestNetworkSettings()); } void tst_PlatformSocketEngine::init() { } void tst_PlatformSocketEngine::cleanup() { } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::construction() { PLATFORMSOCKETENGINE socketDevice; QVERIFY(!socketDevice.isValid()); // Initialize device QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol)); QVERIFY(socketDevice.isValid()); QVERIFY(socketDevice.protocol() == QAbstractSocket::IPv4Protocol); QVERIFY(socketDevice.socketType() == QAbstractSocket::TcpSocket); QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState); QVERIFY(socketDevice.socketDescriptor() != -1); QVERIFY(socketDevice.localAddress() == QHostAddress()); QVERIFY(socketDevice.localPort() == 0); QVERIFY(socketDevice.peerAddress() == QHostAddress()); QVERIFY(socketDevice.peerPort() == 0); QVERIFY(socketDevice.error() == QAbstractSocket::UnknownSocketError); QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::bytesAvailable() was called in QAbstractSocket::UnconnectedState"); QVERIFY(socketDevice.bytesAvailable() == -1); QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::hasPendingDatagrams() was called in QAbstractSocket::UnconnectedState"); QVERIFY(!socketDevice.hasPendingDatagrams()); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::simpleConnectToIMAP() { PLATFORMSOCKETENGINE socketDevice; // Initialize device QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol)); QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState); const bool isConnected = socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143); if (!isConnected) { QVERIFY(socketDevice.state() == QAbstractSocket::ConnectingState); QVERIFY(socketDevice.waitForWrite()); QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState); } QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState); QVERIFY(socketDevice.peerAddress() == QtNetworkSettings::serverIP()); // Wait for the greeting QVERIFY(socketDevice.waitForRead()); // Read the greeting qint64 available = socketDevice.bytesAvailable(); QVERIFY(available > 0); QByteArray array; array.resize(available); QVERIFY(socketDevice.read(array.data(), array.size()) == available); // Check that the greeting is what we expect it to be QVERIFY2(QtNetworkSettings::compareReplyIMAP(array), array.constData()); // Write a logout message QByteArray array2 = "ZZZ LOGOUT\r\n"; QVERIFY(socketDevice.write(array2.data(), array2.size()) == array2.size()); // Wait for the response QVERIFY(socketDevice.waitForRead()); available = socketDevice.bytesAvailable(); QVERIFY(available > 0); array.resize(available); QVERIFY(socketDevice.read(array.data(), array.size()) == available); // Check that the greeting is what we expect it to be QCOMPARE(array.constData(), "* BYE LOGOUT received\r\n" "ZZZ OK Completed\r\n"); // Wait for the response QVERIFY(socketDevice.waitForRead()); char c; QVERIFY(socketDevice.read(&c, sizeof(c)) == -1); QVERIFY(socketDevice.error() == QAbstractSocket::RemoteHostClosedError); QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::udpLoopbackTest() { PLATFORMSOCKETENGINE udpSocket; // Initialize device #1 QVERIFY(udpSocket.initialize(QAbstractSocket::UdpSocket)); QVERIFY(udpSocket.isValid()); QVERIFY(udpSocket.socketDescriptor() != -1); QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv4Protocol); QVERIFY(udpSocket.socketType() == QAbstractSocket::UdpSocket); QVERIFY(udpSocket.state() == QAbstractSocket::UnconnectedState); // Bind #1 to localhost QVERIFY(udpSocket.bind(QHostAddress("127.0.0.1"), 0)); QVERIFY(udpSocket.state() == QAbstractSocket::BoundState); quint16 port = udpSocket.localPort(); QVERIFY(port != 0); // Initialize device #2 PLATFORMSOCKETENGINE udpSocket2; QVERIFY(udpSocket2.initialize(QAbstractSocket::UdpSocket)); // Connect device #2 to #1 QVERIFY(udpSocket2.connectToHost(QHostAddress("127.0.0.1"), port)); QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState); // Write a message to #1 QByteArray message1 = "hei der"; QVERIFY(udpSocket2.write(message1.data(), message1.size()) == message1.size()); // Read the message from #2 QVERIFY(udpSocket.waitForRead()); QVERIFY(udpSocket.hasPendingDatagrams()); qint64 available = udpSocket.pendingDatagramSize(); QVERIFY(available > 0); QByteArray answer; answer.resize(available); QHostAddress senderAddress; quint16 senderPort = 0; QVERIFY(udpSocket.readDatagram(answer.data(), answer.size(), &senderAddress, &senderPort) == message1.size()); QVERIFY(senderAddress == QHostAddress("127.0.0.1")); QVERIFY(senderPort != 0); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::udpIPv6LoopbackTest() { PLATFORMSOCKETENGINE udpSocket; // Initialize device #1 bool init = udpSocket.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::IPv6Protocol); if (!init) { QVERIFY(udpSocket.error() == QAbstractSocket::UnsupportedSocketOperationError); } else { QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv6Protocol); // Bind #1 to localhost QVERIFY(udpSocket.bind(QHostAddress("::1"), 0)); QVERIFY(udpSocket.state() == QAbstractSocket::BoundState); quint16 port = udpSocket.localPort(); QVERIFY(port != 0); // Initialize device #2 PLATFORMSOCKETENGINE udpSocket2; QVERIFY(udpSocket2.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::IPv6Protocol)); // Connect device #2 to #1 QVERIFY(udpSocket2.connectToHost(QHostAddress("::1"), port)); QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState); // Write a message to #1 QByteArray message1 = "hei der"; QVERIFY(udpSocket2.write(message1.data(), message1.size()) == message1.size()); // Read the message from #2 QVERIFY(udpSocket.waitForRead()); QVERIFY(udpSocket.hasPendingDatagrams()); qint64 available = udpSocket.pendingDatagramSize(); QVERIFY(available > 0); QByteArray answer; answer.resize(available); QHostAddress senderAddress; quint16 senderPort = 0; QVERIFY(udpSocket.readDatagram(answer.data(), answer.size(), &senderAddress, &senderPort) == message1.size()); QVERIFY(senderAddress == QHostAddress("::1")); QVERIFY(senderPort != 0); } } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::broadcastTest() { #ifdef Q_OS_AIX QSKIP("Broadcast does not work on darko"); #endif PLATFORMSOCKETENGINE broadcastSocket; // Initialize a regular Udp socket QVERIFY(broadcastSocket.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::AnyIPProtocol)); // Bind to any port on all interfaces QVERIFY(broadcastSocket.bind(QHostAddress::Any, 0)); QVERIFY(broadcastSocket.state() == QAbstractSocket::BoundState); quint16 port = broadcastSocket.localPort(); QVERIFY(port > 0); // Broadcast an inappropriate troll message QByteArray trollMessage = "MOOT wtf is a MOOT? talk english not your sutpiD ENGLISH."; qint64 written = broadcastSocket.writeDatagram(trollMessage.data(), trollMessage.size(), QHostAddress::Broadcast, port); QCOMPARE((int)written, trollMessage.size()); // Wait until we receive it ourselves #if defined(Q_OS_FREEBSD) QEXPECT_FAIL("", "Broadcasting to 255.255.255.255 does not work on FreeBSD", Abort); #endif QVERIFY(broadcastSocket.waitForRead()); QVERIFY(broadcastSocket.hasPendingDatagrams()); qlonglong available = broadcastSocket.pendingDatagramSize(); QByteArray response; response.resize(available); QVERIFY(broadcastSocket.readDatagram(response.data(), response.size()) == response.size()); QCOMPARE(response, trollMessage); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::serverTest() { PLATFORMSOCKETENGINE server; // Initialize a Tcp socket QVERIFY(server.initialize(QAbstractSocket::TcpSocket)); // Bind to any port on all interfaces QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0)); QVERIFY(server.state() == QAbstractSocket::BoundState); quint16 port = server.localPort(); // Listen for incoming connections QVERIFY(server.listen()); QVERIFY(server.state() == QAbstractSocket::ListeningState); // Initialize a Tcp socket PLATFORMSOCKETENGINE client; QVERIFY(client.initialize(QAbstractSocket::TcpSocket)); if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) { QVERIFY(client.state() == QAbstractSocket::ConnectingState); QVERIFY(client.waitForWrite()); QVERIFY(client.state() == QAbstractSocket::ConnectedState); } // The server accepts the connection int socketDescriptor = server.accept(); QVERIFY(socketDescriptor > 0); // A socket device is initialized on the server side, passing the // socket descriptor from accept(). It's pre-connected. PLATFORMSOCKETENGINE serverSocket; QVERIFY(serverSocket.initialize(socketDescriptor)); QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState); // The server socket sends a greeting to the clietn QByteArray greeting = "Greetings!"; QVERIFY(serverSocket.write(greeting.data(), greeting.size()) == greeting.size()); // The client waits for the greeting to arrive QVERIFY(client.waitForRead()); qint64 available = client.bytesAvailable(); QVERIFY(available > 0); // The client reads the greeting and checks that it's correct QByteArray response; response.resize(available); QVERIFY(client.read(response.data(), response.size()) == response.size()); QCOMPARE(response, greeting); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::udpLoopbackPerformance() { PLATFORMSOCKETENGINE udpSocket; // Initialize device #1 QVERIFY(udpSocket.initialize(QAbstractSocket::UdpSocket)); QVERIFY(udpSocket.isValid()); QVERIFY(udpSocket.socketDescriptor() != -1); QVERIFY(udpSocket.protocol() == QAbstractSocket::IPv4Protocol); QVERIFY(udpSocket.socketType() == QAbstractSocket::UdpSocket); QVERIFY(udpSocket.state() == QAbstractSocket::UnconnectedState); // Bind #1 to localhost QVERIFY(udpSocket.bind(QHostAddress("127.0.0.1"), 0)); QVERIFY(udpSocket.state() == QAbstractSocket::BoundState); quint16 port = udpSocket.localPort(); QVERIFY(port != 0); // Initialize device #2 PLATFORMSOCKETENGINE udpSocket2; QVERIFY(udpSocket2.initialize(QAbstractSocket::UdpSocket)); // Connect device #2 to #1 QVERIFY(udpSocket2.connectToHost(QHostAddress("127.0.0.1"), port)); QVERIFY(udpSocket2.state() == QAbstractSocket::ConnectedState); const int messageSize = 8192; QByteArray message1(messageSize, '@'); QByteArray answer(messageSize, '@'); QHostAddress localhost = QHostAddress::LocalHost; qlonglong readBytes = 0; QTime timer; timer.start(); while (timer.elapsed() < 5000) { udpSocket2.write(message1.data(), message1.size()); udpSocket.waitForRead(); while (udpSocket.hasPendingDatagrams()) { readBytes += (qlonglong) udpSocket.readDatagram(answer.data(), answer.size()); } } qDebug("\t\t%.1fMB/%.1fs: %.1fMB/s", readBytes / (1024.0 * 1024.0), timer.elapsed() / 1024.0, (readBytes / (timer.elapsed() / 1000.0)) / (1024 * 1024)); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::tcpLoopbackPerformance() { PLATFORMSOCKETENGINE server; // Initialize a Tcp socket QVERIFY(server.initialize(QAbstractSocket::TcpSocket)); // Bind to any port on all interfaces QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0)); QVERIFY(server.state() == QAbstractSocket::BoundState); quint16 port = server.localPort(); // Listen for incoming connections QVERIFY(server.listen()); QVERIFY(server.state() == QAbstractSocket::ListeningState); // Initialize a Tcp socket PLATFORMSOCKETENGINE client; QVERIFY(client.initialize(QAbstractSocket::TcpSocket)); // Connect to our server if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) { QVERIFY(client.state() == QAbstractSocket::ConnectingState); QVERIFY(client.waitForWrite()); QVERIFY(client.state() == QAbstractSocket::ConnectedState); } // The server accepts the connection int socketDescriptor = server.accept(); QVERIFY(socketDescriptor > 0); // A socket device is initialized on the server side, passing the // socket descriptor from accept(). It's pre-connected. PLATFORMSOCKETENGINE serverSocket; QVERIFY(serverSocket.initialize(socketDescriptor)); QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState); const int messageSize = 1024 * 256; QByteArray message1(messageSize, '@'); QByteArray answer(messageSize, '@'); QTime timer; timer.start(); qlonglong readBytes = 0; while (timer.elapsed() < 5000) { qlonglong written = serverSocket.write(message1.data(), message1.size()); while (written > 0) { client.waitForRead(); if (client.bytesAvailable() > 0) { qlonglong readNow = client.read(answer.data(), answer.size()); written -= readNow; readBytes += readNow; } } } qDebug("\t\t%.1fMB/%.1fs: %.1fMB/s", readBytes / (1024.0 * 1024.0), timer.elapsed() / 1024.0, (readBytes / (timer.elapsed() / 1000.0)) / (1024 * 1024)); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::readWriteBufferSize() { PLATFORMSOCKETENGINE device; QVERIFY(device.initialize(QAbstractSocket::TcpSocket)); qint64 bufferSize = device.receiveBufferSize(); QVERIFY(bufferSize != -1); device.setReceiveBufferSize(bufferSize + 1); #if defined(Q_OS_WINCE) QEXPECT_FAIL(0, "Not supported by default on WinCE", Continue); #endif QVERIFY(device.receiveBufferSize() > bufferSize); bufferSize = device.sendBufferSize(); QVERIFY(bufferSize != -1); device.setSendBufferSize(bufferSize + 1); QVERIFY(device.sendBufferSize() > bufferSize); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::tooManySockets() { #if defined Q_OS_WIN QSKIP("Certain windows machines suffocate and spend too much time in this test."); #endif QList<PLATFORMSOCKETENGINE *> sockets; PLATFORMSOCKETENGINE *socketLayer = 0; for (;;) { socketLayer = new PLATFORMSOCKETENGINE; sockets.append(socketLayer); if (!socketLayer->initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol)) break; } QCOMPARE(socketLayer->error(), QAbstractSocket::SocketResourceError); qDeleteAll(sockets); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::bind() { #if !defined Q_OS_WIN PLATFORMSOCKETENGINE binder; QVERIFY(binder.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol)); QVERIFY(!binder.bind(QHostAddress::AnyIPv4, 82)); QVERIFY(binder.error() == QAbstractSocket::SocketAccessError); #endif PLATFORMSOCKETENGINE binder2; QVERIFY(binder2.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol)); QVERIFY(binder2.bind(QHostAddress::AnyIPv4, 31180)); PLATFORMSOCKETENGINE binder3; QVERIFY(binder3.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol)); QVERIFY(!binder3.bind(QHostAddress::AnyIPv4, 31180)); QVERIFY(binder3.error() == QAbstractSocket::AddressInUseError); if (QtNetworkSettings::hasIPv6()) { PLATFORMSOCKETENGINE binder4; QVERIFY(binder4.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv6Protocol)); QVERIFY(binder4.bind(QHostAddress::AnyIPv6, 31180)); PLATFORMSOCKETENGINE binder5; QVERIFY(binder5.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv6Protocol)); QVERIFY(!binder5.bind(QHostAddress::AnyIPv6, 31180)); QVERIFY(binder5.error() == QAbstractSocket::AddressInUseError); } PLATFORMSOCKETENGINE binder6; QVERIFY(binder6.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::AnyIPProtocol)); QVERIFY(binder6.bind(QHostAddress::Any, 31181)); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::networkError() { PLATFORMSOCKETENGINE client; QVERIFY(client.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol)); const bool isConnected = client.connectToHost(QtNetworkSettings::serverIP(), 143); if (!isConnected) { QVERIFY(client.state() == QAbstractSocket::ConnectingState); QVERIFY(client.waitForWrite()); QVERIFY(client.state() == QAbstractSocket::ConnectedState); } QVERIFY(client.state() == QAbstractSocket::ConnectedState); // An unexpected network error! #ifdef Q_OS_WIN // could use shutdown to produce different errors ::closesocket(client.socketDescriptor()); #else ::close(client.socketDescriptor()); #endif QVERIFY(client.read(0, 0) == -1); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::setSocketDescriptor() { PLATFORMSOCKETENGINE socket1; QVERIFY(socket1.initialize(QAbstractSocket::TcpSocket)); PLATFORMSOCKETENGINE socket2; QVERIFY(socket2.initialize(socket1.socketDescriptor())); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::invalidSend() { PLATFORMSOCKETENGINE socket; QVERIFY(socket.initialize(QAbstractSocket::TcpSocket)); QTest::ignoreMessage(QtWarningMsg, PLATFORMSOCKETENGINESTRING "::writeDatagram() was" " called by a socket other than QAbstractSocket::UdpSocket"); QCOMPARE(socket.writeDatagram("hei", 3, QHostAddress::LocalHost, 143), (qlonglong) -1); } //--------------------------------------------------------------------------- void tst_PlatformSocketEngine::receiveUrgentData() { PLATFORMSOCKETENGINE server; QVERIFY(server.initialize(QAbstractSocket::TcpSocket)); // Bind to any port on all interfaces QVERIFY(server.bind(QHostAddress("0.0.0.0"), 0)); QVERIFY(server.state() == QAbstractSocket::BoundState); quint16 port = server.localPort(); QVERIFY(server.listen()); QVERIFY(server.state() == QAbstractSocket::ListeningState); PLATFORMSOCKETENGINE client; QVERIFY(client.initialize(QAbstractSocket::TcpSocket)); if (!client.connectToHost(QHostAddress("127.0.0.1"), port)) { QVERIFY(client.state() == QAbstractSocket::ConnectingState); QVERIFY(client.waitForWrite()); QVERIFY(client.state() == QAbstractSocket::ConnectedState); } int socketDescriptor = server.accept(); QVERIFY(socketDescriptor > 0); PLATFORMSOCKETENGINE serverSocket; QVERIFY(serverSocket.initialize(socketDescriptor)); QVERIFY(serverSocket.state() == QAbstractSocket::ConnectedState); char msg; int available; QByteArray response; // Native OOB data test doesn't work on HP-UX or WinCE #if !defined(Q_OS_HPUX) && !defined(Q_OS_WINCE) // The server sends an urgent message msg = 'Q'; QCOMPARE(int(::send(socketDescriptor, &msg, sizeof(msg), MSG_OOB)), 1); // The client receives the urgent message QVERIFY(client.waitForRead()); available = client.bytesAvailable(); QCOMPARE(available, 1); response.resize(available); QCOMPARE(client.read(response.data(), response.size()), qint64(1)); QCOMPARE(response.at(0), msg); // The client sends an urgent message msg = 'T'; int clientDescriptor = client.socketDescriptor(); QCOMPARE(int(::send(clientDescriptor, &msg, sizeof(msg), MSG_OOB)), 1); // The server receives the urgent message QVERIFY(serverSocket.waitForRead()); available = serverSocket.bytesAvailable(); QCOMPARE(available, 1); response.resize(available); QCOMPARE(serverSocket.read(response.data(), response.size()), qint64(1)); QCOMPARE(response.at(0), msg); #endif } QTEST_MAIN(tst_PlatformSocketEngine) #include "tst_platformsocketengine.moc"
CodeDJ/qt5-hidpi
qt/qtbase/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp
C++
lgpl-2.1
25,201