repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
LeonanCarvalho/jataka-commons
jataka-common-dao-impl/src/main/java/org/jatakasource/common/dao/GenericHibernateDao.java
518
package org.jatakasource.common.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.StatelessSession; import org.springframework.beans.factory.annotation.Autowired; public abstract class GenericHibernateDao implements GenericDao { @Autowired private SessionFactory sessionFactory; public Session getCurrentSession() { return sessionFactory.getCurrentSession(); } public StatelessSession getStatelessSession() { return sessionFactory.openStatelessSession(); } }
gpl-3.0
SDCC-Ken/Ghost-Leg-Game
Ajax/finish.php
2607
<?php function sendemail($id, $players) { require "../Mailer/PHPMailerAutoload.php"; $ok = false; foreach ($players AS $player) { $tempplayer = (object) $player; $name = $tempplayer->name; $email = $tempplayer->email; if ($email != "") { $mail = new PHPMailer; $mail->isSMTP(); $mail->Host = "mail.kwanwing.tk"; $mail->SMTPAuth = true; $mail->Username = "kwanwing@kwanwing.tk"; $mail->Password = "abcd1234!"; $mail->Port = 25; $mail->setFrom("kwanwing@kwanwing.tk", "Ghost Leg Game Admin"); $mail->addAddress($email, $name); $mail->isHTML(true); $mail->Subject = "The game have ended. Check out what you get"; $mail->Body = "" . "<p>Dear " . $name . " </p>" . "<p>Hello, The game is end. </p>" . "<p>You can come to the link to see what you get.</p>" . "<p><a href='http://spd4517ia.kwanwing.tk/game.php?ID=" . $id . "'>http://spd4517ia.kwanwing.tk/game.php?ID=" . $id . "</a></p>" . "<p>Regards,</p>" . "<p>Admin</p>"; $mail->AltBody = "" . "Dear " . $name . " \n" . "Hello, The game is end. \n" . "You can come to the link to see what you get\n" . "Link: http://spd4517ia.kwanwing.tk/game.php?ID=" . $id . "\n" . "Regards,\n" . "Admin\n"; $ok = $mail->send(); } } return $ok; } include_once '../Class/JSONDatabase.php'; $id = isset($_GET["ID"]) ? $_GET["ID"] : "" or exit("No ID"); $name = isset($_POST["name"]) ? $_POST["name"] : "" or exit("No Name"); $db = new JSONDatabase(); $game = $db->readJSON($id) or exit("No Such game"); $allfinish = 0; foreach ($game->player AS $i => $player) { if ($player->name == $name) { $game->player[$i] = array( "name" => $game->player[$i]->name, "email" => $game->player[$i]->email, "seat" => $game->player[$i]->seat, "finish" => TRUE, ); $allfinish++; continue; } if ($player->finish == TRUE) { $allfinish++; } } if ($allfinish >= sizeof($game->player)) { $game->end = true; $ok = $db->updateJSON($id, $game) ? TRUE : FALSE; sendemail($id, $game->player); echo $ok ? "S" : "Error"; } else { $ok = $db->updateJSON($id, $game) ? TRUE : FALSE; echo $ok ? "S" : "Error"; }
gpl-3.0
alaineman/PowerGrid
src/Bridge/rs/worldcontroller.cpp
145
#include "worldcontroller.h" namespace RS { IMPL_JACE_CONSTRUCTORS(WorldController) IMPL_RSCLASS_GET(WorldController) } // namespace bridge
gpl-3.0
firebirdberlin/nightdream
src/com/firebirdberlin/nightdream/services/SqliteIntentService.java
2872
package com.firebirdberlin.nightdream.services; import android.content.Context; import android.util.Log; import androidx.work.Data; import androidx.work.OneTimeWorkRequest; import androidx.work.WorkManager; import com.firebirdberlin.nightdream.models.SimpleTime; import com.google.gson.Gson; public class SqliteIntentService { private static final String TAG = "SqliteIntentService"; static void saveTime(Context context, SimpleTime time) { SqliteIntentServiceWorker.save(context, time); //enqueueWork(context, time, SqliteIntentServiceWorker.ACTION_SAVE); } static void snooze(Context context, SimpleTime time) { SqliteIntentServiceWorker.save(context, time); //enqueueWork(context, time, SqliteIntentServiceWorker.ACTION_SNOOZE); } public static void skipAlarm(Context context, SimpleTime time) { SqliteIntentServiceWorker.skipAlarm(context, time); //enqueueWork(context, time, SqliteIntentServiceWorker.ACTION_SKIP_ALARM); } public static void deleteAlarm(Context context, SimpleTime time) { SqliteIntentServiceWorker.delete(context, time); //enqueueWork(context, time, SqliteIntentServiceWorker.ACTION_DELETE_ALARM); } public static void scheduleAlarm(Context context) { enqueueWork(context, SqliteIntentServiceWorker.ACTION_SCHEDULE_ALARM); } public static void broadcastAlarm(Context context) { enqueueWork(context, SqliteIntentServiceWorker.ACTION_BROADCAST_ALARM); } static void enqueueWork(Context context, SimpleTime time, String action) { Log.d(TAG, "enqueueWork(Context,SimpleTime, Action)"); if (time == null) { return; } Gson gson = new Gson(); String jsonTime = gson.toJson(time); Data myData = new Data.Builder() .putString("action", action) .putString("time", jsonTime) .build(); OneTimeWorkRequest sqliteWork = new OneTimeWorkRequest.Builder(SqliteIntentServiceWorker.class) .setInputData(myData) // TODO enable with target level 31 //.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) .build(); WorkManager.getInstance(context).enqueue(sqliteWork); } static void enqueueWork(Context context, String action) { Log.d(TAG, "enqueueWork(Context, Action)"); Data myData = new Data.Builder() .putString("action", action) .build(); OneTimeWorkRequest mathWork = new OneTimeWorkRequest.Builder(SqliteIntentServiceWorker.class) .setInputData(myData) .build(); WorkManager.getInstance(context).enqueue(mathWork); } }
gpl-3.0
unsftn/bisis-v4
src/com/gint/app/bisis4/commandservice/JdbcServiceFactory.java
643
package com.gint.app.bisis4.commandservice; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class JdbcServiceFactory implements ServiceFactory{ private static Log log = LogFactory.getLog(JdbcServiceFactory.class.getName()); public Service createService(int type, String param){ Service service = null; if (type == ServiceType.LOCAL){ try{ service = new JdbcServiceLocal(); }catch (Exception e){ log.fatal(e.getMessage()); } } else if (type == ServiceType.REMOTE){ service = new ServiceBroker(param); } return service; } }
gpl-3.0
rafaelqueiroz89/design_patterns_in_csharp
Builder/ClassAttribute.cs
2110
using System.Collections.Generic; using System.Text; /* * A builder is a separate component for builing an object * Can either give builder a constructor or return it via a static function * To make builder fluent, return this (AddChild Thing nested on the same element) * Different facets of an object can be built with different builders working in tandem (conjunto) via a base class * Facets are methods or a particular behavior of an object like (object home, home.At(), home.InCountry() */ namespace Builder { public class ClassAttribute { public string Type, Name, ClassName; public List<ClassAttribute> Attributes = new List<ClassAttribute>(); private const int indentSize = 2; public ClassAttribute() { } public ClassAttribute(string name, string type) { Type = type; Name = name; } private string ToStringImpl(int indent) { var sb = new StringBuilder(); var i = new string(' ', indentSize * indent); int cont = 0; if (!string.IsNullOrWhiteSpace(ClassName)) { sb.Append($"{i}public class {ClassName}\n"); sb.Append("{\n"); } if (!string.IsNullOrWhiteSpace(Type) && !string.IsNullOrWhiteSpace(Name)) { sb.Append(new string(' ', indentSize * (indent + 1))); sb.Append($"public {Type} {Name};\n"); } else if (Attributes.Count == 0) sb.Append("}"); foreach (var e in Attributes) { cont++; sb.Append(e.ToStringImpl(indent)); if (cont == Attributes.Count) sb.Append("}"); } return sb.ToString(); } public override string ToString() { return ToStringImpl(0); } } }
gpl-3.0
hpl1nk/nonamegame
xray/editor/world/sources/resource_editor.cpp
4509
//////////////////////////////////////////////////////////////////////////// // Created : 09.02.2010 // Author : Evgeniy Obertyukh // Copyright (C) GSC Game World - 2010 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "window_ide.h" #include "resource_editor.h" #include "resource_editor_base.h" #include "texture_options.h" #include "resource_selector.h" #include "resource_document_factory.h" #include "resource_editor_commit.h" #include "resource_editor_cancel.h" using namespace System::Windows; namespace xray { namespace editor { RegistryKey^ resource_editor::editor_registry_key() { RegistryKey^ base_registry_key = m_world->ide()->base_registry_key(); RegistryKey^ windows = base_registry_key->CreateSubKey("windows"); return windows->CreateSubKey(m_multidocument->Name); } void resource_editor::in_constructor (resource_document_factory^ document_factory, controls::tree_view_source^ resources_source) { m_is_closed = false; m_multidocument = gcnew resource_editor_base(*m_world, document_factory, resources_source, false); m_multidocument->Dock = DockStyle::Fill; Controls->Add (m_multidocument); Controls->SetChildIndex (m_multidocument, 0); } void resource_editor::resource_editor_Load (Object^ , EventArgs^ ) { m_multidocument->load_panels(this); RegistryKey^ editor_key = editor_registry_key(); String^ selected_path = safe_cast<String^>(editor_key->GetValue("tree_view_selected_path")); if(selected_path != nullptr && selected_path != String::Empty) m_multidocument->view_panel->tree_view->track_active_node(selected_path); } String^ resource_editor::name::get () { return m_multidocument->Name; } void resource_editor::name::set (String^ value) { m_multidocument->Name = value; } String^ resource_editor::view_panel_caption::get () { return m_multidocument->view_panel_caption; } void resource_editor::view_panel_caption::set (String^ value) { m_multidocument->view_panel_caption = value; } String^ resource_editor::properties_panel_caption::get () { return m_multidocument->properties_panel_caption; } void resource_editor::properties_panel_caption::set (String^ value) { m_multidocument->properties_panel_caption = value; } void resource_editor::resource_editor_FormClosing (System::Object^ , System::Windows::Forms::FormClosingEventArgs^ e) { m_is_closed = true; if(m_multidocument->changed_resources->Count > 0) { resource_editor_cancel^ cancel_dlg = gcnew resource_editor_cancel(m_multidocument->changed_resources); if(cancel_dlg->ShowDialog() == Forms::DialogResult::Cancel) { e->Cancel = true; return; } } RegistryKey^ editor_key = editor_registry_key(); if( m_multidocument->view_panel->tree_view->selected_nodes->Count > 0 ) editor_key->SetValue( "tree_view_selected_path", m_multidocument->view_panel->tree_view->selected_nodes[0]->FullPath ); m_multidocument->close_all_documents(); m_multidocument->save_panels (this); m_multidocument->free_resources (); } void resource_editor::manual_close () { //Save panel settings if(!m_is_closed) { m_multidocument->close_all_documents(); m_multidocument->save_panels (this); this->Close(); } } void resource_editor::m_ok_button_Click (Object^ , EventArgs^ ) { if(m_multidocument->changed_resources->Count > 0) { resource_editor_commit^ commint_box = gcnew resource_editor_commit(m_multidocument->changed_resources); Forms::DialogResult result = commint_box->ShowDialog(); if(result == Forms::DialogResult::OK) { for each(options_wrapper^ wrapper in m_multidocument->changed_resources->Values) { static_cast<resource_options*>(wrapper->m_resource->c_ptr())->save(); } m_multidocument->changed_resources->Clear(); this->Close(); } } else { m_multidocument->changed_resources->Clear(); this->Close(); } } void resource_editor::m_cancel_button_Click (Object^ , EventArgs^ ) { if(m_multidocument->changed_resources->Count > 0) { if(System::Windows::Forms::MessageBox::Show("There is change in resources, if you continue, the changes will be lost. Do you want to exit anyway?", "Resource Editor", Forms::MessageBoxButtons::YesNo, Forms::MessageBoxIcon::Question) == Forms::DialogResult::Yes) { m_multidocument->changed_resources->Clear(); this->Close(); } } else { m_multidocument->changed_resources->Clear(); this->Close(); } } }//namespace editor }//namespace xray
gpl-3.0
motlib/simple-sin
cfg/styles.php
459
<?php $styles = array( 'default' => array( 'head-color' => 'lightgray', 'border-color' =>'lightgray', 'border-hover-color' => 'gray', 'background-color' => 'white', 'text-color' => 'black', ), 'hacker' => array( 'head-color' => 'black', 'border-color' =>'green', 'border-hover-color' => 'lightgreen', 'background-color' => 'black', 'text-color' => 'green', ), );
gpl-3.0
luwrain/app-calc
src/main/java/org/luwrain/app/calc/Strings.java
677
/* Copyright 2012-2015 Michael Pozhidaev <msp@altlinux.org> This file is part of the Luwrain. Luwrain 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. Luwrain 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. */ package org.luwrain.app.calc; public interface Strings { String appName(); }
gpl-3.0
QiuLihua83/Magento_with_some_popular_mods
app/code/local/Autocompleteplus/Autosuggest/Model/Observer.php
23189
<?php /** * InstantSearchPlus (Autosuggest) * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * * @category Mage * @package InstantSearchPlus * @copyright Copyright (c) 2014 Fast Simon (http://www.instantsearchplus.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class Autocompleteplus_Autosuggest_Model_Observer extends Mage_Core_Model_Abstract { const AUTOCOMPLETEPLUS_WEBHOOK_URI = 'https://acp-magento.appspot.com/ma_webhook'; const WEBHOOK_CURL_TIMEOUT_LENGTH = 2; private $imageField; private $standardImageFields=array(); private $currency; public function adminhtml_controller_catalogrule_prepare_save($observer){ //Mage::log(print_r($observer,true),null,'autocompleteplus.log'); } public function catalogrule_after_apply($observer){ //Mage::log('apply: '.print_r($observer,true),null,'autocompleteplus.log'); } public function catalog_controller_product_init($observer){ try{ $helper=Mage::helper('autocompleteplus_autosuggest'); $_tableprefix = (string)Mage::getConfig()->getTablePrefix(); $write = Mage::getSingleton('core/resource')->getConnection('core_write'); $tblExist=$write->showTableStatus($_tableprefix.'autocompleteplus_config'); if(!$tblExist){return;} $keyList=$write->describeTable($_tableprefix.'autocompleteplus_config'); if(!isset($keyList['site_url'])){return;} $sqlFetch ='SELECT * FROM '. $_tableprefix.'autocompleteplus_config WHERE id = 1'; $config=$write->fetchAll($sqlFetch); if(isset($config[0]['site_url'])){ $old_url=$config[0]['site_url']; }else{ $old_url='no_old_url'; } if(isset($config[0]['licensekey'])){ $licensekey=$config[0]['licensekey']; }else{ $licensekey='no_uuid'; } //getting site url $url=$helper->getConfigDataByFullPath('web/unsecure/base_url'); if($old_url!=$url){ $command="http://magento.autocompleteplus.com/ext_update_host"; $data=array(); $data['old_url']=$old_url; $data['new_url']=$url; $data['uuid']=$licensekey; $res=$helper->sendPostCurl($command,$data); $result=json_decode($res); if(strtolower($result->status)=='ok'){ $sql='UPDATE '. $_tableprefix.'autocompleteplus_config SET site_url=? WHERE id = 1'; $write->query($sql, array($url)); } Mage::log(print_r($res,true),null,'autocompleteplus.log'); } }catch(Exception $e){ Mage::log($e->getMessage(),null,'autocompleteplus.log'); } } public function catalog_product_save_after_depr($observer){ $helper=Mage::helper('autocompleteplus_autosuggest'); $product=$observer->getProduct(); $this->imageField=Mage::getStoreConfig('autocompleteplus/config/imagefield'); if(!$this->imageField){ $this->imageField='thumbnail'; } $this->standardImageFields=array('image','small_image','thumbnail'); $this->currency=Mage::app()->getStore()->getCurrentCurrencyCode(); $domain =Mage::getStoreConfig('web/unsecure/base_url'); $key =$helper->getUUID(); $mage=Mage::getVersion(); $ext=(string) Mage::getConfig()->getNode()->modules->Autocompleteplus_Autosuggest->version; $xml='<?xml version="1.0"?>'; $xml.='<catalog version="'.$ext.'" magento="'.$mage.'">'; $xml.=$this->__getProductData($product); $xml.='</catalog>'; $data=array( 'site'=>$domain, 'key'=>$key, 'catalog'=>$xml ); $res=$this->__sendUpdate($data); Mage::log(print_r($res,true),null,'autocomplete.log'); } public function catalog_product_save_after($observer){ date_default_timezone_set('Asia/Jerusalem'); $product=$observer->getProduct(); $origData=$observer->getProduct()->getOrigData(); $storeId=$product->getStoreId(); $productId=$product->getId(); $sku=$product->getSku(); // if ($sku == null || $productId == null){ // Mage::log('catalog_product_save_after - either sku null or identifier is null', null, 'autocompleteplus.log'); // return; // } if(is_array($origData)){ if(array_key_exists('sku',$origData)){ $oldSku=$origData['sku']; if($sku!=$oldSku){ $this->__writeproductDeletion($oldSku,$productId,$storeId, $product); } } } $dt = strtotime('now'); //$mysqldate = date( 'Y-m-d h:m:s', $dt ); $simple_product_parents = array(); if ($product->getTypeID() == 'simple'){ $simple_product_parents = Mage::getModel('catalog/product_type_configurable') ->getParentIdsByChild($product->getId()); } try{ $_tableprefix = (string)Mage::getConfig()->getTablePrefix(); $read = Mage::getSingleton('core/resource')->getConnection('core_read'); $write = Mage::getSingleton('core/resource')->getConnection('core_write'); $tblExist = $write->showTableStatus($_tableprefix.'autocompleteplus_batches'); if(!$tblExist){return;} try{ if ($storeId == 0 && method_exists($product, 'getStoreIds')){ $product_stores = $product->getStoreIds(); } else { $product_stores = array($storeId); } } catch (Exception $e){ $product_stores = array($storeId); } foreach ($product_stores as $product_store){ $sqlFetch = 'SELECT * FROM '. $_tableprefix.'autocompleteplus_batches WHERE product_id = ? AND store_id=?'; $updates = $write->fetchAll($sqlFetch, array($productId, $product_store)); if($updates&&count($updates) != 0){ $sql = 'UPDATE '. $_tableprefix.'autocompleteplus_batches SET update_date=?,action=? WHERE product_id = ? AND store_id=?'; $write->query($sql, array($dt, "update", $productId, $product_store)); }else{ $sql='INSERT INTO '. $_tableprefix.'autocompleteplus_batches (product_id,store_id,update_date,action,sku) VALUES (?,?,?,?,?)'; $write->query($sql, array($productId, $product_store, $dt, "update", $sku)); } try{ $helper = Mage::helper('autocompleteplus_autosuggest'); if ($helper->isChecksumTableExists()){ $checksum = $helper->calculateChecksum($product); $helper->updateSavedProductChecksum($_tableprefix, $read, $write, $productId, $sku, $product_store, $checksum); } } catch (Exception $e){ Mage::log('checksum failed - ' . $e->getMessage(), null, 'autocompleteplus.log'); } // trigger update for simple product's configurable parent if (!empty($simple_product_parents)){ // simple product has configural parent foreach ($simple_product_parents as $configurable_product){ $sqlFetch = 'SELECT * FROM '. $_tableprefix.'autocompleteplus_batches WHERE product_id = ? AND store_id=?'; $updates = $read->fetchAll($sqlFetch, array($configurable_product, $product_store)); if (!$updates || (count($updates) == 0) || $updates[0]['action'] != 'remove'){ if($updates && count($updates) != 0){ $sql = 'UPDATE '. $_tableprefix.'autocompleteplus_batches SET update_date=?,action=? WHERE product_id = ? AND store_id=?'; $write->query($sql, array($dt, "update", $configurable_product, $product_store)); } else { $sql = 'INSERT INTO '. $_tableprefix.'autocompleteplus_batches (product_id,store_id,update_date,action,sku) VALUES (?,?,?,?,?)'; $write->query($sql, array($configurable_product, $product_store, $dt, "update", 'ISP_NO_SKU')); } } } } } }catch(Exception $e){ Mage::log($e->getMessage(),null,'autocompleteplus.log'); } } private function __getProductData($product){ $sku =$product->getSku(); $status=$product->isInStock(); $stockItem = $product->getStockItem(); $storeId=$product->getStoreId(); if($stockItem&&$stockItem->getIsInStock()&&$status) { $sell=1; }else{ $sell=0; } $price =$this->getPrice($product); $productUrl =Mage::helper('catalog/product')->getProductUrl($product->getId()); $prodDesc =$product->getDescription(); $prodShortDesc =$product->getShortDescription(); $prodName =$product->getName(); try{ if(in_array($this->imageField,$this->standardImageFields)){ $prodImage =Mage::helper('catalog/image')->init($product, $this->imageField); }else{ $function='get'.$this->imageField; $prodImage =$product->$function(); } }catch(Exception $e){ $prodImage=''; } $visibility =$product->getVisibility(); $row='<product store="'.$storeId.'" currency="'.$this->currency.'" visibility="'.$visibility.'" price="'.$price.'" url="'.$productUrl.'" thumbs="'.$prodImage.'" selleable="'.$sell.'" action="update" >'; $row.='<description><![CDATA['.$prodDesc.']]></description>'; $row.='<short><![CDATA['.$prodShortDesc.']]></short>'; $row.='<name><![CDATA['.$prodName.']]></name>'; $row.='<sku><![CDATA['.$sku.']]></sku>'; $row.='</product>'; return $row; } private function __makeSafeString($str){ $str=strip_tags($str); $str=str_replace('"','',$str); $str=str_replace("'",'',$str); $str=str_replace('/','',$str); $str=str_replace('<','',$str); $str=str_replace('>','',$str); $str=str_replace('\\','',$str); return $str; } private function __sendUpdate($data){ $ch=curl_init(); $command='http://magento.autocompleteplus.com/update'; curl_setopt($ch, CURLOPT_URL, $command); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); //curl_setopt($ch,CURLOPT_POST,0); if(!empty($data)){ curl_setopt_array($ch, array( CURLOPT_POSTFIELDS => $data, )); } return curl_exec($ch); } private function getPrice($product){ $price = 0; $helper=Mage::helper('autocompleteplus_autosuggest'); if ($product->getTypeId()=='grouped'){ $helper->prepareGroupedProductPrice($product); $_minimalPriceValue = $product->getPrice(); if($_minimalPriceValue){ $price=$_minimalPriceValue; } }elseif($product->getTypeId()=='bundle'){ if(!$product->getFinalPrice()){ $price=$helper->getBundlePrice($product); }else{ $price=$product->getFinalPrice(); } }else{ $price =$product->getFinalPrice(); } if(!$price){ $price=0; } return $price; } public function catalog_product_delete_before($observer){ $product=$observer->getProduct(); $storeId=$product->getStoreId(); $productId=$product->getId(); $sku=$product->getSku(); $this->__writeproductDeletion($sku,$productId,$storeId, $product); } private function __writeproductDeletion($sku, $productId, $storeId, $product = null){ $dt = strtotime('now'); //$mysqldate = date( 'Y-m-d h:m:s', $dt ); try{ // if ($productId == null){ // Mage::log('__writeproductDeletion - identifier is null', null, 'autocompleteplus.log'); // return; // } $_tableprefix = (string)Mage::getConfig()->getTablePrefix(); $read = Mage::getSingleton('core/resource')->getConnection('core_read'); $write = Mage::getSingleton('core/resource')->getConnection('core_write'); $tblExist=$write->showTableStatus($_tableprefix.'autocompleteplus_batches'); if(!$tblExist){return;} try{ $helper = Mage::helper('autocompleteplus_autosuggest'); if ($helper->isChecksumTableExists()){ try{ if (!$product){ $product = Mage::getModel('catalog/product')->load($productId); } if ($storeId == 0 && method_exists($product, 'getStoreIds')){ $product_stores = $product->getStoreIds(); } else { $product_stores = array($storeId); } } catch (Exception $e){ Mage::log('exception raised: ' . $e->getMessage(),null,'autocompleteplus.log'); $product_stores = array($storeId); } if ($sku == null){ $sku = 'dummy_sku'; } foreach ($product_stores as $product_store){ $sqlFetch = 'SELECT * FROM '. $_tableprefix.'autocompleteplus_batches WHERE product_id = ? AND store_id=?'; $updates = $read->fetchAll($sqlFetch, array($productId, $product_store)); if($updates && count($updates) != 0){ $sql = 'UPDATE '. $_tableprefix.'autocompleteplus_batches SET update_date=?,action=? WHERE product_id = ? AND store_id = ?'; $write->query($sql, array($dt, "remove", $productId, $product_store)); } else { $sql='INSERT INTO '. $_tableprefix.'autocompleteplus_batches (product_id,store_id,update_date,action,sku) VALUES (?,?,?,?,?)'; $write->query($sql, array($productId, $product_store, $dt, "remove", $sku)); } $helper->updateDeletedProductChecksum($_tableprefix, $read, $write, $productId, $sku, $product_store); } } } catch (Exception $e){ Mage::log('__writeproductDeletion failed on remove - ' . $e->getMessage(), null, 'autocompleteplus.log'); } }catch(Exception $e){ Mage::log('__writeproductDeletion: ' . $e->getMessage(),null,'autocompleteplus.log'); } } public function adminSessionUserLoginSuccess() { $notifications = array(); /** @var Autocompleteplus_Autosuggest_Helper_Data $helper */ $helper = Mage::helper('autocompleteplus_autosuggest'); $command = "http://magento.autocompleteplus.com/ext_info?u=". $helper->getUUID(); $res = $helper->sendCurl($command); $result = json_decode($res); if (isset($result->alerts)) { foreach ($result->alerts as $alert) { $notification = array( 'type' => (string) $alert->type, 'message' => (string) $alert->message, 'timestamp' => (string) $alert->timestamp, ); if (isset($alert->subject)) { $notification['subject'] = (string) $alert->subject; } $notifications[] = $notification; } } if (!empty($notifications)) { Mage::getResourceModel('autocompleteplus_autosuggest/notifications')->addNotifications($notifications); } $this->sendNotificationMails(); } public function sendNotificationMails() { /** @var Autocompleteplus_Autosuggest_Model_Mysql4_Notifications_Collection $notifications */ $notifications = Mage::getModel('autocompleteplus_autosuggest/notifications')->getCollection(); $notifications->addTypeFilter('email')->addActiveFilter(); foreach ($notifications as $notification) { $this->_sendStatusMail($notification); } } /** * @param Autocompleteplus_Autosuggest_Model_Notifications $notification */ protected function _sendStatusMail($notification) { /** @var Autocompleteplus_Autosuggest_Helper_Data $helper */ $helper = Mage::helper('autocompleteplus_autosuggest'); // Getting site owner email $storeMail = $helper->getConfigDataByFullPath('autocompleteplus/config/store_email'); if ($storeMail) { $emailTemplate = Mage::getModel('core/email_template'); $emailTemplate->loadDefault('autosuggest_status_notification'); $emailTemplate->setTemplateSubject($notification->getSubject()); // Get General email address (Admin->Configuration->General->Store Email Addresses) $emailTemplate->setSenderName(Mage::getStoreConfig('trans_email/ident_general/email')); $emailTemplate->setSenderEmail(Mage::getStoreConfig('trans_email/ident_general/name')); $emailTemplateVariables['message'] = $notification->getMessage(); $emailTemplate->send($storeMail, null, $emailTemplateVariables); $notification->setIsActive(0) ->save(); } } /** * The generic webhook service caller * @param Varien_Event_Observer $observer * @return void */ public function webhook_service_call($observer) { $curl = new Varien_Http_Adapter_Curl(); $curl->setConfig(array( 'timeout' => static::WEBHOOK_CURL_TIMEOUT_LENGTH )); $curl->write(Zend_Http_Client::GET, $this->_getWebhookObjectUri()); $curl->read(); $curl->close(); } /** * Returns the quote id if it exists, otherwise it will * return the last order id. This only is set in the session * when an order has been recently completed. Therefore * this call may also return null. * @return string|null */ public function getQuoteId() { if($quoteId = Mage::getSingleton('checkout/session')->getQuoteId()){ return $quoteId; } return $this->getOrder()->getQuoteId(); } /** * Get the order associated with the previous quote id * used as a fallback when the quote is no longer available * @return Mage_Sales_Model_Order */ public function getOrder() { $orderId = Mage::getSingleton('checkout/session')->getLastOrderId(); return Mage::getModel('sales/order')->load($orderId); } /** * Return a label for webhooks based on the current * controller route. This cannot be handled by layout * XML because the layout engine may not be init in all * future uses of the webhook * @return string|void */ public function getWebhookEventLabel() { $request = Mage::app()->getRequest(); $route = $request->getRouteName(); $controller = $request->getControllerName(); $action = $request->getActionName(); if($route != 'checkout'){ return; } if($controller == 'cart' && $action == 'index'){ return 'cart'; } if($controller == 'onepage' && $action == 'index'){ return 'checkout'; } if($controller == 'onepage' && $action == 'success'){ return 'success'; } } /** * Create the webhook URI * @return string */ protected function _getWebhookObjectUri() { $helper = Mage::helper('autocompleteplus_autosuggest'); $parameters = array( 'event' =>$this->getWebhookEventLabel(), 'UUID' =>$helper->getUUID(), 'key' =>$helper->getKey(), 'store_id' =>Mage::app()->getStore()->getStoreId(), 'st' =>$helper->getSessionId(), 'cart_token' =>$this->getQuoteId(), 'serp' =>'', 'cart_product' => $this->getCartContentsAsJson() ); return static::AUTOCOMPLETEPLUS_WEBHOOK_URI . '?' . http_build_query($parameters,'','&'); } /** * JSON encode the cart contents * @return string */ public function getCartContentsAsJson() { return json_encode($this->_getVisibleItems()); } /** * Format visible cart contents into a multidimensional keyed array * @return array */ protected function _getVisibleItems() { if($cartItems = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems()){ return $this->_buildCartArray($cartItems); } return $this->_buildCartArray($this->getOrder()->getAllVisibleItems()); } /** * Return a formatted array of quote or order items * @param array $cartItems * @todo fork this for quote items vs sales order items * @return array */ protected function _buildCartArray($cartItems) { $items = array(); foreach($cartItems as $item){ /** * @todo fix this check by providing separate models for MSMQI and MSMOI */ if($item instanceof Mage_Sales_Model_Order_Item){ $quantity = (int)$item->getQtyOrdered(); } else { $quantity = $item->getQty(); } $items[] = array( 'product_id' =>$item->getProduct()->getId(), 'price' =>$item->getProduct()->getFinalPrice(), 'quantity' =>$quantity, 'currency' =>Mage::app()->getStore()->getCurrentCurrencyCode(), 'attribution' =>$item->getAddedFromSearch() ); } return $items; } }
gpl-3.0
peteyhayman/peteyhayman.github.io
Projects/Flowfield/Particle.js
1731
function Particle() { this.reset = function () { this.pos = createVector(random(width), random(height)); this.vel = createVector(); //this.vel = p5.Vector.random2D(); this.acc = createVector(); this.radius = 1; this.maxSpeed = random(0.5, 1.2) this.lifespan = random(512) } this.reset() this.setHue = function (_hueMin, _hueMax) { this.color = random(_hueMin, _hueMax); } this.addForce = function (_force) { this.acc.add(_force); } this.border = function () { if (this.pos.x < 0) this.pos.x = width; if (this.pos.x > width) this.pos.x = 0; if (this.pos.y < 0) this.pos.y = height; if (this.pos.y > height) this.pos.y = 0; } this.follow = function (flowfield, res) { const cols = floor(width / res) const rows = floor(height / res) let ix = floor(this.pos.x / res) ix = (ix > cols - 1) ? cols - 1 : ix let iy = floor(this.pos.y / res) iy = (iy > rows - 1) ? rows - 1 : iy if (ix > cols - 1 || iy > rows - 1) print('error') const i = ix + iy * cols this.addForce(flowfield[i]) } this.update = function () { //print(this.pos); this.vel.add(this.acc); this.vel.limit(this.maxSpeed) this.pos.add(this.vel); this.border(); this.acc.mult(0); this.lifespan-- if (this.lifespan <= 0) { this.reset() //console.log('dead') } } this.show = function (alpha = 255) { strokeWeight(0.5); //stroke(0, 0, 255, 0); //fill(0, alpha)//point is now stroke, not fill stroke(0, alpha) point(this.pos.x, this.pos.y); //ellipse(this.pos.x, this.pos.y, this.radius, this.radius) } }
gpl-3.0
ubbi86/rootg
src/utility/Menu.java
3201
package utility; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.util.ArrayList; import main.Main; public class Menu extends ArrayList<String> { private Main main; private Font font; private ArrayList<RoundRectangle2D.Float> buttons; private ArrayList<Boolean> highlight; // CONSTRUCTORS public Menu(Main main) { this.main = main; font = main.getFont().deriveFont(50f); buttons = new ArrayList<RoundRectangle2D.Float>(); highlight = new ArrayList<Boolean>(); } // GETTERS&SETTERS public void setHighlight(Point p) { boolean ans = highlight.indexOf(true) >= 0; int i = select(p); for (int j = 0; j < buttons.size(); j++) if (i == j) highlight.set(j, true); else highlight.set(j, false); if (ans ^ highlight.indexOf(true) >= 0) main.setRefresh(1); } // METHODS public void scrollMenu(int index) { int pos = highlight.indexOf(true); index += pos; while (index < 0) index += size(); index %= size(); if (pos >= 0) highlight.set(pos, false); highlight.set(index, true); main.setRefresh(1); } public void selectMenu() { int pos = highlight.indexOf(true); if (pos >= 0) { RoundRectangle2D.Float btn = buttons.get(pos); main.getStateController().nextState((int) btn.getCenterX(), (int) btn.getCenterY()); } } public boolean add(String item) { super.add(item); buttons.clear(); int xStep = main.WIDTH / 5; int yStep = main.HEIGHT / (size() * 2 + 1); for (int i = 0; i < size(); i++) { RoundRectangle2D.Float r = new RoundRectangle2D.Float(xStep, yStep * (2 * i + 1), xStep * 3, yStep, yStep, yStep); buttons.add(r); highlight.add(false); } return true; } private void centerString(Graphics2D g2d, RoundRectangle2D r, String s) { FontRenderContext frc = new FontRenderContext(null, true, true); Rectangle2D rec = font.getStringBounds(s, frc); int rWidth = (int) Math.round(rec.getWidth()); int rHeight = (int) Math.round(rec.getHeight()); int rX = (int) Math.round(rec.getX()); int rY = (int) Math.round(rec.getY()); int a = (int) ((r.getWidth() / 2) - (rWidth / 2) - rX); int b = (int) ((r.getHeight() / 2) - (rHeight / 2) - rY); g2d.drawString(s, (int) (r.getX() + a), (int) (r.getY() + b)); } public int select(Point p) { for (RoundRectangle2D r : buttons) if (r.contains(p)) return buttons.indexOf(r); return -1; } public void render(Graphics2D g2d) { g2d.setColor(new Color(255, 255, 255, 128)); g2d.fillRect(0, 0, Main.WIDTH, Main.HEIGHT); g2d.setFont(font); g2d.setColor(Color.BLACK); FontRenderContext frc = new FontRenderContext(null, true, true); for (int i = 0; i < buttons.size(); i++) { RoundRectangle2D r = buttons.get(i); if (highlight.get(i)) { g2d.setColor(new Color(0x3F7F7F7F, true)); g2d.fill(r); g2d.setColor(Color.BLACK); } g2d.draw(r); centerString(g2d, r, get(i)); } } }
gpl-3.0
BerserkerDotNet/Ether
src/Ether/Types/OrderByConfiguration.cs
363
using System; namespace Ether.Types { public class OrderByConfiguration<T> { public OrderByConfiguration(Func<T, object> property, bool isDesc) { Property = property; IsDescending = isDesc; } public Func<T, object> Property { get; set; } public bool IsDescending { get; set; } } }
gpl-3.0
WVDR/LittleBlackBook
IreneAdler/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs
19492
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace IreneAdler.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
gpl-3.0
Richterrettich/slidemgr
lib/commands/create.rb
1444
require 'thor' require 'thor/group' require 'pathname' require 'util' require 'nokogiri' require 'net/http' require 'json' require 'yaml' class Create < Thor::Group include Thor::Actions include Util argument :name, :type => :string, :desc => 'The presentation name' def self.source_root File.expand_path('../',__dir__) end def prepare_parameters @snake_case_name = @name.sub ' ','_' end def create_master @config = parse_config @token = request_token @client = false template 'template/index.erb', "#{content_root}/master/slides/#{@snake_case_name}/index.html" template 'template/content.md.erb', "#{content_root}/master/slides/" \ "#{@snake_case_name}/content/content.md" end def create_client @client = true template 'template/index.erb', "#{content_root}/client/slides/#{@snake_case_name}/index.html" end def append_index index = "#{content_root}/client/index.html" template 'template/overview_index.erb',index unless File.exist?(index) alter_index_html do | doc | unless doc.xpath('//a').map(&:content).include? @name body = doc.at_css 'body' h2 = Nokogiri::XML::Node.new 'h2', doc link = Nokogiri::XML::Node.new 'a', doc link['href'] = "slides/#{@snake_case_name}/" link.content= "#{@name}" h2 << link body << h2 end end end end
gpl-3.0
mathisdt/sdb2
src/main/java/org/zephyrsoft/sdb2/model/SongElementEnum.java
1227
/* * This file is part of the Song Database (SDB). * * SDB is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License 3.0 as published by * the Free Software Foundation. * * SDB 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 3.0 for more details. * * You should have received a copy of the GNU General Public License 3.0 * along with SDB. If not, see <http://www.gnu.org/licenses/>. */ package org.zephyrsoft.sdb2.model; /** * Indicates specific elements of a {@link Song}. */ public enum SongElementEnum { /** the title (if present, it is always exactly one line) */ TITLE, /** a lyrics element (not always a whole line, see NEW_LINE) */ LYRICS, /** a chord element (not always a whole line, see NEW_LINE) */ CHORDS, /** a translation element (not always a whole line, see NEW_LINE) */ TRANSLATION, /** a copyright element (always a whole line) */ COPYRIGHT, /** indicates a line break between LYRICS, CHORDS and TRANSLATION elements - this element is only used there! */ NEW_LINE; }
gpl-3.0
ybAmazing/encrypt_pymongo
cursor.py
42415
# Copyright 2009-2014 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Cursor class to iterate over Mongo query results.""" import copy from collections import deque from bson import RE_TYPE from bson.code import Code from bson.son import SON from pymongo import helpers, message, read_preferences from pymongo.read_preferences import ReadPreference, secondary_ok_commands from pymongo.errors import (AutoReconnect, InvalidOperation, OperationFailure) from pymongo import aes _QUERY_OPTIONS = { "tailable_cursor": 2, "slave_okay": 4, "oplog_replay": 8, "no_timeout": 16, "await_data": 32, "exhaust": 64, "partial": 128} # This has to be an old style class due to # http://bugs.jython.org/issue1057 class _SocketManager: """Used with exhaust cursors to ensure the socket is returned. """ def __init__(self, sock, pool): self.sock = sock self.pool = pool self.__closed = False def __del__(self): self.close() def close(self): """Return this instance's socket to the connection pool. """ if not self.__closed: self.__closed = True self.pool.maybe_return_socket(self.sock) self.sock, self.pool = None, None def error(self): """Clean up after an error on the managed socket. """ if self.sock: self.sock.close() # Return the closed socket to avoid a semaphore leak in the pool. self.close() # TODO might be cool to be able to do find().include("foo") or # find().exclude(["bar", "baz"]) or find().slice("a", 1, 2) as an # alternative to the fields specifier. class Cursor(object): """A cursor / iterator over Mongo query results. """ def __init__(self, collection, spec=None, fields=None, skip=0, limit=0, timeout=True, snapshot=False, tailable=False, sort=None, max_scan=None, as_class=None, slave_okay=False, await_data=False, partial=False, manipulate=True, read_preference=ReadPreference.PRIMARY, tag_sets=[{}], secondary_acceptable_latency_ms=None, exhaust=False, compile_re=True, _must_use_master=False, _uuid_subtype=None, **kwargs): """Create a new cursor. Should not be called directly by application developers - see :meth:`~pymongo.collection.Collection.find` instead. .. mongodoc:: cursors """ self.__id = None if spec is None: spec = {} if not isinstance(spec, dict): raise TypeError("spec must be an instance of dict") if not isinstance(skip, int): raise TypeError("skip must be an instance of int") if not isinstance(limit, int): raise TypeError("limit must be an instance of int") if not isinstance(timeout, bool): raise TypeError("timeout must be an instance of bool") if not isinstance(snapshot, bool): raise TypeError("snapshot must be an instance of bool") if not isinstance(tailable, bool): raise TypeError("tailable must be an instance of bool") if not isinstance(slave_okay, bool): raise TypeError("slave_okay must be an instance of bool") if not isinstance(await_data, bool): raise TypeError("await_data must be an instance of bool") if not isinstance(partial, bool): raise TypeError("partial must be an instance of bool") if not isinstance(exhaust, bool): raise TypeError("exhaust must be an instance of bool") if fields is not None: if not fields: fields = {"_id": 1} if not isinstance(fields, dict): fields = helpers._fields_list_to_dict(fields) if as_class is None: as_class = collection.database.connection.document_class self.__collection = collection self.__spec = spec self.__fields = fields self.__skip = skip self.__limit = limit self.__max_time_ms = None self.__batch_size = 0 self.__max = None self.__min = None # Exhaust cursor support if self.__collection.database.connection.is_mongos and exhaust: raise InvalidOperation('Exhaust cursors are ' 'not supported by mongos') if limit and exhaust: raise InvalidOperation("Can't use limit and exhaust together.") self.__exhaust = exhaust self.__exhaust_mgr = None # This is ugly. People want to be able to do cursor[5:5] and # get an empty result set (old behavior was an # exception). It's hard to do that right, though, because the # server uses limit(0) to mean 'no limit'. So we set __empty # in that case and check for it when iterating. We also unset # it anytime we change __limit. self.__empty = False self.__snapshot = snapshot self.__ordering = sort and helpers._index_document(sort) or None self.__max_scan = max_scan self.__explain = False self.__hint = None self.__comment = None self.__as_class = as_class self.__slave_okay = slave_okay self.__manipulate = manipulate self.__read_preference = read_preference self.__tag_sets = tag_sets self.__secondary_acceptable_latency_ms = secondary_acceptable_latency_ms self.__tz_aware = collection.database.connection.tz_aware self.__compile_re = compile_re self.__must_use_master = _must_use_master self.__uuid_subtype = _uuid_subtype or collection.uuid_subtype self.__data = deque() self.__connection_id = None self.__retrieved = 0 self.__killed = False self.__query_flags = 0 if tailable: self.__query_flags |= _QUERY_OPTIONS["tailable_cursor"] if not timeout: self.__query_flags |= _QUERY_OPTIONS["no_timeout"] if tailable and await_data: self.__query_flags |= _QUERY_OPTIONS["await_data"] if exhaust: self.__query_flags |= _QUERY_OPTIONS["exhaust"] if partial: self.__query_flags |= _QUERY_OPTIONS["partial"] # this is for passing network_timeout through if it's specified # need to use kwargs as None is a legit value for network_timeout self.__kwargs = kwargs @property def collection(self): """The :class:`~pymongo.collection.Collection` that this :class:`Cursor` is iterating. .. versionadded:: 1.1 """ return self.__collection @property def conn_id(self): """The server/client/pool this cursor lives on. Could be (host, port), -1, or None depending on what client class executed the initial query or this cursor being advanced at all. """ return self.__connection_id @property def retrieved(self): """The number of documents retrieved so far. """ return self.__retrieved def __del__(self): if self.__id and not self.__killed: self.__die() def rewind(self): """Rewind this cursor to its unevaluated state. Reset this cursor if it has been partially or completely evaluated. Any options that are present on the cursor will remain in effect. Future iterating performed on this cursor will cause new queries to be sent to the server, even if the resultant data has already been retrieved by this cursor. """ self.__data = deque() self.__id = None self.__connection_id = None self.__retrieved = 0 self.__killed = False return self def clone(self): """Get a clone of this cursor. Returns a new Cursor instance with options matching those that have been set on the current instance. The clone will be completely unevaluated, even if the current instance has been partially or completely evaluated. """ return self._clone(True) def _clone(self, deepcopy=True): clone = self._clone_base() values_to_clone = ("spec", "fields", "skip", "limit", "max_time_ms", "comment", "max", "min", "snapshot", "ordering", "explain", "hint", "batch_size", "max_scan", "as_class", "slave_okay", "manipulate", "read_preference", "tag_sets", "secondary_acceptable_latency_ms", "must_use_master", "uuid_subtype", "compile_re", "query_flags", "kwargs") data = dict((k, v) for k, v in self.__dict__.iteritems() if k.startswith('_Cursor__') and k[9:] in values_to_clone) if deepcopy: data = self._deepcopy(data) clone.__dict__.update(data) return clone def _clone_base(self): """Creates an empty Cursor object for information to be copied into. """ return Cursor(self.__collection) def __die(self): """Closes this cursor. """ if self.__id and not self.__killed: if self.__exhaust and self.__exhaust_mgr: # If this is an exhaust cursor and we haven't completely # exhausted the result set we *must* close the socket # to stop the server from sending more data. self.__exhaust_mgr.sock.close() else: connection = self.__collection.database.connection if self.__connection_id is not None: connection.close_cursor(self.__id, self.__connection_id) else: connection.close_cursor(self.__id) if self.__exhaust and self.__exhaust_mgr: self.__exhaust_mgr.close() self.__killed = True def close(self): """Explicitly close / kill this cursor. Required for PyPy, Jython and other Python implementations that don't use reference counting garbage collection. """ self.__die() def __query_spec(self): """Get the spec to use for a query. """ operators = {} if self.__ordering: operators["$orderby"] = self.__ordering if self.__explain: operators["$explain"] = True if self.__hint: operators["$hint"] = self.__hint if self.__comment: operators["$comment"] = self.__comment if self.__snapshot: operators["$snapshot"] = True if self.__max_scan: operators["$maxScan"] = self.__max_scan if self.__max_time_ms is not None: operators["$maxTimeMS"] = self.__max_time_ms if self.__max: operators["$max"] = self.__max if self.__min: operators["$min"] = self.__min # Only set $readPreference if it's something other than # PRIMARY to avoid problems with mongos versions that # don't support read preferences. if (self.__collection.database.connection.is_mongos and self.__read_preference != ReadPreference.PRIMARY): has_tags = self.__tag_sets and self.__tag_sets != [{}] # For maximum backwards compatibility, don't set $readPreference # for SECONDARY_PREFERRED unless tags are in use. Just rely on # the slaveOkay bit (set automatically if read preference is not # PRIMARY), which has the same behavior. if (self.__read_preference != ReadPreference.SECONDARY_PREFERRED or has_tags): read_pref = { 'mode': read_preferences.mongos_mode(self.__read_preference) } if has_tags: read_pref['tags'] = self.__tag_sets operators['$readPreference'] = read_pref if operators: # Make a shallow copy so we can cleanly rewind or clone. spec = self.__spec.copy() # Only commands that can be run on secondaries should have any # operators added to the spec. Command queries can be issued # by db.command or calling find_one on $cmd directly if self.collection.name == "$cmd": # Don't change commands that can't be sent to secondaries command_name = spec and spec.keys()[0].lower() or "" if command_name not in secondary_ok_commands: return spec elif command_name == 'mapreduce': # mapreduce shouldn't be changed if its not inline out = spec.get('out') if not isinstance(out, dict) or not out.get('inline'): return spec # White-listed commands must be wrapped in $query. if "$query" not in spec: # $query has to come first spec = SON([("$query", spec)]) if not isinstance(spec, SON): # Ensure the spec is SON. As order is important this will # ensure its set before merging in any extra operators. spec = SON(spec) spec.update(operators) return spec # Have to wrap with $query if "query" is the first key. # We can't just use $query anytime "query" is a key as # that breaks commands like count and find_and_modify. # Checking spec.keys()[0] covers the case that the spec # was passed as an instance of SON or OrderedDict. elif ("query" in self.__spec and (len(self.__spec) == 1 or self.__spec.keys()[0] == "query")): return SON({"$query": self.__spec}) return self.__spec def __query_options(self): """Get the query options string to use for this query. """ options = self.__query_flags if (self.__slave_okay or self.__read_preference != ReadPreference.PRIMARY ): options |= _QUERY_OPTIONS["slave_okay"] return options def __check_okay_to_chain(self): """Check if it is okay to chain more options onto this cursor. """ if self.__retrieved or self.__id is not None: raise InvalidOperation("cannot set options after executing query") def add_option(self, mask): """Set arbitrary query flags using a bitmask. To set the tailable flag: cursor.add_option(2) """ if not isinstance(mask, int): raise TypeError("mask must be an int") self.__check_okay_to_chain() if mask & _QUERY_OPTIONS["slave_okay"]: self.__slave_okay = True if mask & _QUERY_OPTIONS["exhaust"]: if self.__limit: raise InvalidOperation("Can't use limit and exhaust together.") if self.__collection.database.connection.is_mongos: raise InvalidOperation('Exhaust cursors are ' 'not supported by mongos') self.__exhaust = True self.__query_flags |= mask return self def remove_option(self, mask): """Unset arbitrary query flags using a bitmask. To unset the tailable flag: cursor.remove_option(2) """ if not isinstance(mask, int): raise TypeError("mask must be an int") self.__check_okay_to_chain() if mask & _QUERY_OPTIONS["slave_okay"]: self.__slave_okay = False if mask & _QUERY_OPTIONS["exhaust"]: self.__exhaust = False self.__query_flags &= ~mask return self def limit(self, limit): """Limits the number of results to be returned by this cursor. Raises :exc:`TypeError` if `limit` is not an integer. Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has already been used. The last `limit` applied to this cursor takes precedence. A limit of ``0`` is equivalent to no limit. :Parameters: - `limit`: the number of results to return .. mongodoc:: limit """ if not isinstance(limit, (int, long)): raise TypeError("limit must be an integer") if self.__exhaust: raise InvalidOperation("Can't use limit and exhaust together.") self.__check_okay_to_chain() self.__empty = False self.__limit = limit return self def batch_size(self, batch_size): """Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer. .. note:: batch_size can not override MongoDB's internal limits on the amount of data it will return to the client in a single batch (i.e if you set batch size to 1,000,000,000, MongoDB will currently only return 4-16MB of results per batch). Raises :exc:`TypeError` if `batch_size` is not an integer. Raises :exc:`ValueError` if `batch_size` is less than ``0``. Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has already been used. The last `batch_size` applied to this cursor takes precedence. :Parameters: - `batch_size`: The size of each batch of results requested. .. versionadded:: 1.9 """ if not isinstance(batch_size, (int, long)): raise TypeError("batch_size must be an integer") if batch_size < 0: raise ValueError("batch_size must be >= 0") self.__check_okay_to_chain() self.__batch_size = batch_size == 1 and 2 or batch_size return self def skip(self, skip): """Skips the first `skip` results of this cursor. Raises :exc:`TypeError` if `skip` is not an integer. Raises :exc:`ValueError` if `skip` is less than ``0``. Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has already been used. The last `skip` applied to this cursor takes precedence. :Parameters: - `skip`: the number of results to skip """ if not isinstance(skip, (int, long)): raise TypeError("skip must be an integer") if skip < 0: raise ValueError("skip must be >= 0") self.__check_okay_to_chain() self.__skip = skip return self def max_time_ms(self, max_time_ms): """Specifies a time limit for a query operation. If the specified time is exceeded, the operation will be aborted and :exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms` is ``None`` no limit is applied. Raises :exc:`TypeError` if `max_time_ms` is not an integer or ``None``. Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has already been used. :Parameters: - `max_time_ms`: the time limit after which the operation is aborted """ if not isinstance(max_time_ms, (int, long)) and max_time_ms is not None: raise TypeError("max_time_ms must be an integer or None") self.__check_okay_to_chain() self.__max_time_ms = max_time_ms return self def __getitem__(self, index): """Get a single document or a slice of documents from this cursor. Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has already been used. To get a single document use an integral index, e.g.:: >>> db.test.find()[50] An :class:`IndexError` will be raised if the index is negative or greater than the amount of documents in this cursor. Any limit previously applied to this cursor will be ignored. To get a slice of documents use a slice index, e.g.:: >>> db.test.find()[20:25] This will return this cursor with a limit of ``5`` and skip of ``20`` applied. Using a slice index will override any prior limits or skips applied to this cursor (including those applied through previous calls to this method). Raises :class:`IndexError` when the slice has a step, a negative start value, or a stop value less than or equal to the start value. :Parameters: - `index`: An integer or slice index to be applied to this cursor """ self.__check_okay_to_chain() self.__empty = False if isinstance(index, slice): if index.step is not None: raise IndexError("Cursor instances do not support slice steps") skip = 0 if index.start is not None: if index.start < 0: raise IndexError("Cursor instances do not support" "negative indices") skip = index.start if index.stop is not None: limit = index.stop - skip if limit < 0: raise IndexError("stop index must be greater than start" "index for slice %r" % index) if limit == 0: self.__empty = True else: limit = 0 self.__skip = skip self.__limit = limit return self if isinstance(index, (int, long)): if index < 0: raise IndexError("Cursor instances do not support negative" "indices") clone = self.clone() clone.skip(index + self.__skip) clone.limit(-1) # use a hard limit # comment by ating on 2016/08/29 # for doc in clone: # return doc # added by ating on 2016/08/29 for doc in clone: return aes.decrypt_doc(doc) raise IndexError("no such item for Cursor instance") raise TypeError("index %r cannot be applied to Cursor " "instances" % index) def max_scan(self, max_scan): """Limit the number of documents to scan when performing the query. Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has already been used. Only the last :meth:`max_scan` applied to this cursor has any effect. :Parameters: - `max_scan`: the maximum number of documents to scan .. note:: Requires server version **>= 1.5.1** .. versionadded:: 1.7 """ self.__check_okay_to_chain() self.__max_scan = max_scan return self def max(self, spec): """Adds `max` operator that specifies upper bound for specific index. :Parameters: - `spec`: a list of field, limit pairs specifying the exclusive upper bound for all keys of a specific index in order. .. versionadded:: 2.7 """ if not isinstance(spec, (list, tuple)): raise TypeError("spec must be an instance of list or tuple") self.__check_okay_to_chain() self.__max = SON(spec) return self def min(self, spec): """Adds `min` operator that specifies lower bound for specific index. :Parameters: - `spec`: a list of field, limit pairs specifying the inclusive lower bound for all keys of a specific index in order. .. versionadded:: 2.7 """ if not isinstance(spec, (list, tuple)): raise TypeError("spec must be an instance of list or tuple") self.__check_okay_to_chain() self.__min = SON(spec) return self def sort(self, key_or_list, direction=None): """Sorts this cursor's results. Pass a field name and a direction, either :data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`:: for doc in collection.find().sort('field', pymongo.ASCENDING): print(doc) To sort by multiple fields, pass a list of (key, direction) pairs:: for doc in collection.find().sort([ ('field1', pymongo.ASCENDING), ('field2', pymongo.DESCENDING)]): print(doc) Beginning with MongoDB version 2.6, text search results can be sorted by relevance:: cursor = db.test.find( {'$text': {'$search': 'some words'}}, {'score': {'$meta': 'textScore'}}) # Sort by 'score' field. cursor.sort([('score', {'$meta': 'textScore'})]) for doc in cursor: print(doc) Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has already been used. Only the last :meth:`sort` applied to this cursor has any effect. :Parameters: - `key_or_list`: a single key or a list of (key, direction) pairs specifying the keys to sort on - `direction` (optional): only used if `key_or_list` is a single key, if not given :data:`~pymongo.ASCENDING` is assumed """ self.__check_okay_to_chain() keys = helpers._index_list(key_or_list, direction) self.__ordering = helpers._index_document(keys) return self def count(self, with_limit_and_skip=False): """Get the size of the results set for this query. Returns the number of documents in the results set for this query. Does not take :meth:`limit` and :meth:`skip` into account by default - set `with_limit_and_skip` to ``True`` if that is the desired behavior. Raises :class:`~pymongo.errors.OperationFailure` on a database error. With :class:`~pymongo.mongo_replica_set_client.MongoReplicaSetClient` or :class:`~pymongo.master_slave_connection.MasterSlaveConnection`, if `read_preference` is not :attr:`pymongo.read_preferences.ReadPreference.PRIMARY` or :attr:`pymongo.read_preferences.ReadPreference.PRIMARY_PREFERRED`, or (deprecated) `slave_okay` is `True`, the count command will be sent to a secondary or slave. :Parameters: - `with_limit_and_skip` (optional): take any :meth:`limit` or :meth:`skip` that has been applied to this cursor into account when getting the count .. note:: The `with_limit_and_skip` parameter requires server version **>= 1.1.4-** .. note:: ``count`` ignores ``network_timeout``. For example, the timeout is ignored in the following code:: collection.find({}, network_timeout=1).count() .. versionadded:: 1.1.1 The `with_limit_and_skip` parameter. :meth:`~pymongo.cursor.Cursor.__len__` was deprecated in favor of calling :meth:`count` with `with_limit_and_skip` set to ``True``. """ if not isinstance(with_limit_and_skip, bool): raise TypeError("with_limit_and_skip must be an instance of bool") command = {"query": self.__spec, "fields": self.__fields} command['read_preference'] = self.__read_preference command['tag_sets'] = self.__tag_sets command['secondary_acceptable_latency_ms'] = ( self.__secondary_acceptable_latency_ms) command['slave_okay'] = self.__slave_okay use_master = not self.__slave_okay and not self.__read_preference command['_use_master'] = use_master if self.__max_time_ms is not None: command["maxTimeMS"] = self.__max_time_ms if self.__comment: command['$comment'] = self.__comment if with_limit_and_skip: if self.__limit: command["limit"] = self.__limit if self.__skip: command["skip"] = self.__skip database = self.__collection.database r = database.command("count", self.__collection.name, allowable_errors=["ns missing"], uuid_subtype=self.__uuid_subtype, compile_re=self.__compile_re, **command) if r.get("errmsg", "") == "ns missing": return 0 return int(r["n"]) def distinct(self, key): """Get a list of distinct values for `key` among all documents in the result set of this query. Raises :class:`TypeError` if `key` is not an instance of :class:`basestring` (:class:`str` in python 3). With :class:`~pymongo.mongo_replica_set_client.MongoReplicaSetClient` or :class:`~pymongo.master_slave_connection.MasterSlaveConnection`, if `read_preference` is not :attr:`pymongo.read_preferences.ReadPreference.PRIMARY` or (deprecated) `slave_okay` is `True` the distinct command will be sent to a secondary or slave. :Parameters: - `key`: name of key for which we want to get the distinct values .. note:: Requires server version **>= 1.1.3+** .. seealso:: :meth:`pymongo.collection.Collection.distinct` .. versionadded:: 1.2 """ if not isinstance(key, basestring): raise TypeError("key must be an instance " "of %s" % (basestring.__name__,)) options = {"key": key} if self.__spec: options["query"] = self.__spec options['read_preference'] = self.__read_preference options['tag_sets'] = self.__tag_sets options['secondary_acceptable_latency_ms'] = ( self.__secondary_acceptable_latency_ms) options['slave_okay'] = self.__slave_okay use_master = not self.__slave_okay and not self.__read_preference options['_use_master'] = use_master if self.__max_time_ms is not None: options['maxTimeMS'] = self.__max_time_ms if self.__comment: options['$comment'] = self.__comment database = self.__collection.database return database.command("distinct", self.__collection.name, uuid_subtype=self.__uuid_subtype, compile_re=self.__compile_re, **options)["values"] def explain(self): """Returns an explain plan record for this cursor. .. mongodoc:: explain """ c = self.clone() c.__explain = True # always use a hard limit for explains if c.__limit: c.__limit = -abs(c.__limit) return c.next() def hint(self, index): """Adds a 'hint', telling Mongo the proper index to use for the query. Judicious use of hints can greatly improve query performance. When doing a query on multiple fields (at least one of which is indexed) pass the indexed field as a hint to the query. Hinting will not do anything if the corresponding index does not exist. Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has already been used. `index` should be an index as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). If `index` is ``None`` any existing hints for this query are cleared. The last hint applied to this cursor takes precedence over all others. :Parameters: - `index`: index to hint on (as an index specifier) """ self.__check_okay_to_chain() if index is None: self.__hint = None return self self.__hint = helpers._index_document(index) return self def comment(self, comment): """Adds a 'comment' to the cursor. http://docs.mongodb.org/manual/reference/operator/comment/ :Parameters: - `comment`: A string or document .. versionadded:: 2.7 """ self.__check_okay_to_chain() self.__comment = comment return self def where(self, code): """Adds a $where clause to this query. The `code` argument must be an instance of :class:`basestring` (:class:`str` in python 3) or :class:`~bson.code.Code` containing a JavaScript expression. This expression will be evaluated for each document scanned. Only those documents for which the expression evaluates to *true* will be returned as results. The keyword *this* refers to the object currently being scanned. Raises :class:`TypeError` if `code` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has already been used. Only the last call to :meth:`where` applied to a :class:`Cursor` has any effect. :Parameters: - `code`: JavaScript expression to use as a filter """ self.__check_okay_to_chain() if not isinstance(code, Code): code = Code(code) self.__spec["$where"] = code return self def __send_message(self, message): """Send a query or getmore message and handles the response. If message is ``None`` this is an exhaust cursor, which reads the next result batch off the exhaust socket instead of sending getMore messages to the server. """ client = self.__collection.database.connection if message: kwargs = {"_must_use_master": self.__must_use_master} kwargs["read_preference"] = self.__read_preference kwargs["tag_sets"] = self.__tag_sets kwargs["secondary_acceptable_latency_ms"] = ( self.__secondary_acceptable_latency_ms) kwargs['exhaust'] = self.__exhaust if self.__connection_id is not None: kwargs["_connection_to_use"] = self.__connection_id kwargs.update(self.__kwargs) try: res = client._send_message_with_response(message, **kwargs) self.__connection_id, (response, sock, pool) = res if self.__exhaust: self.__exhaust_mgr = _SocketManager(sock, pool) except AutoReconnect: # Don't try to send kill cursors on another socket # or to another server. It can cause a _pinValue # assertion on some server releases if we get here # due to a socket timeout. self.__killed = True raise else: # Exhaust cursor - no getMore message. try: response = client._exhaust_next(self.__exhaust_mgr.sock) except AutoReconnect: self.__killed = True self.__exhaust_mgr.error() raise try: response = helpers._unpack_response(response, self.__id, self.__as_class, self.__tz_aware, self.__uuid_subtype, self.__compile_re) except OperationFailure: self.__killed = True # Make sure exhaust socket is returned immediately, if necessary. self.__die() # If this is a tailable cursor the error is likely # due to capped collection roll over. Setting # self.__killed to True ensures Cursor.alive will be # False. No need to re-raise. if self.__query_flags & _QUERY_OPTIONS["tailable_cursor"]: return raise except AutoReconnect: # Don't send kill cursors to another server after a "not master" # error. It's completely pointless. self.__killed = True # Make sure exhaust socket is returned immediately, if necessary. self.__die() client.disconnect() raise self.__id = response["cursor_id"] # starting from doesn't get set on getmore's for tailable cursors if not (self.__query_flags & _QUERY_OPTIONS["tailable_cursor"]): assert response["starting_from"] == self.__retrieved, ( "Result batch started from %s, expected %s" % ( response['starting_from'], self.__retrieved)) self.__retrieved += response["number_returned"] #added by ating on 2016/08/30 aes.decrypt_doc(response["data"]) self.__data = deque(response["data"]) if self.__limit and self.__id and self.__limit <= self.__retrieved: self.__die() # Don't wait for garbage collection to call __del__, return the # socket to the pool now. if self.__exhaust and self.__id == 0: self.__exhaust_mgr.close() def _refresh(self): """Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query. """ if len(self.__data) or self.__killed: return len(self.__data) if self.__id is None: # Query ntoreturn = self.__batch_size if self.__limit: if self.__batch_size: ntoreturn = min(self.__limit, self.__batch_size) else: ntoreturn = self.__limit self.__send_message( message.query(self.__query_options(), self.__collection.full_name, self.__skip, ntoreturn, self.__query_spec(), self.__fields, self.__uuid_subtype)) if not self.__id: self.__killed = True elif self.__id: # Get More if self.__limit: limit = self.__limit - self.__retrieved if self.__batch_size: limit = min(limit, self.__batch_size) else: limit = self.__batch_size # Exhaust cursors don't send getMore messages. if self.__exhaust: self.__send_message(None) else: self.__send_message( message.get_more(self.__collection.full_name, limit, self.__id)) else: # Cursor id is zero nothing else to return self.__killed = True return len(self.__data) @property def alive(self): """Does this cursor have the potential to return more data? This is mostly useful with `tailable cursors <http://www.mongodb.org/display/DOCS/Tailable+Cursors>`_ since they will stop iterating even though they *may* return more results in the future. .. versionadded:: 1.5 """ return bool(len(self.__data) or (not self.__killed)) @property def cursor_id(self): """Returns the id of the cursor Useful if you need to manage cursor ids and want to handle killing cursors manually using :meth:`~pymongo.mongo_client.MongoClient.kill_cursors` .. versionadded:: 2.2 """ return self.__id def __iter__(self): return self def next(self): if self.__empty: raise StopIteration db = self.__collection.database if len(self.__data) or self._refresh(): if self.__manipulate: return db._fix_outgoing(self.__data.popleft(), self.__collection) else: return self.__data.popleft() else: raise StopIteration def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.__die() def __copy__(self): """Support function for `copy.copy()`. .. versionadded:: 2.4 """ return self._clone(deepcopy=False) def __deepcopy__(self, memo): """Support function for `copy.deepcopy()`. .. versionadded:: 2.4 """ return self._clone(deepcopy=True) def _deepcopy(self, x, memo=None): """Deepcopy helper for the data dictionary or list. Regular expressions cannot be deep copied but as they are immutable we don't have to copy them when cloning. """ if not hasattr(x, 'items'): y, is_list, iterator = [], True, enumerate(x) else: y, is_list, iterator = {}, False, x.iteritems() if memo is None: memo = {} val_id = id(x) if val_id in memo: return memo.get(val_id) memo[val_id] = y for key, value in iterator: if isinstance(value, (dict, list)) and not isinstance(value, SON): value = self._deepcopy(value, memo) elif not isinstance(value, RE_TYPE): value = copy.deepcopy(value, memo) if is_list: y.append(value) else: if not isinstance(key, RE_TYPE): key = copy.deepcopy(key, memo) y[key] = value return y
gpl-3.0
sergiovilar/backbonejs-mvc-boilerplate
app/scripts/router.js
971
/* global define, Backbone */ define([ ], function () { 'use strict'; var AppRouter = Backbone.Router.extend({ routes: { '*actions': 'index' } }); var initialize = function (init) { if (init === true) { var router = new AppRouter(); router.on('route:index', function () { require(['views/sampleView'], function (Route) { new Route(); }); }); Backbone.history.start({ pushState: true }); // Pega os clicks $('body').delegate('a', 'click', function () { router.navigate($(this).attr('href'), true); return false; }); if (window.location.hash) { var hash = window.location.hash; router.navigate(hash, true); } } }; return { initialize: initialize }; });
gpl-3.0
Towerism/ascii-engine
ascii-engine/render/matrix_renderer.hh
967
// Copyright 2016 Martin Fracker, Jr. // All Rights Reserved. // // AsciiEngine is free software, released under the terms // of the GNU General Public License v3. Please see the // file LICENSE in the root directory or visit // www.gnu.org/licenses/gpl-3.0.en.html for license terms. #pragma once #include <memory> #include <sstream> #include <vector> #include "char_matrix.hh" #include "renderable.hh" #include "renderer.hh" class Matrix_renderer : Renderer { public: Matrix_renderer(int width = 0, int height = 0); void add(Renderable* renderable) override; std::vector<std::string> render() override; int get_width() const override; int get_height() const override; const Renderable* get_renderable(int index) const override; private: int width, height; std::vector<std::shared_ptr<Renderable>> renderables; Char_matrix char_matrix; void render_to_matrix(); void render_renderable(std::shared_ptr<Renderable> renderable); };
gpl-3.0
CARTAvis/carta
carta/cpp/core/Viewer.cpp
4267
#include "CartaLib/CartaLib.h" #include "CartaLib/Hooks/ColormapsScalar.h" #include "CartaLib/Hooks/Initialize.h" #include "GrayColormap.h" #include "Viewer.h" #include "Globals.h" #include "IPlatform.h" #include "State/ObjectManager.h" #include "Data/ViewManager.h" #include "Data/Image/Controller.h" #include "PluginManager.h" #include "MainConfig.h" #include "MyQApp.h" #include "CmdLine.h" #include "ScriptedClient/Listener.h" #include "ScriptedClient/ScriptedCommandInterpreter.h" #include "CartaLib/Hooks/GetPersistentCache.h" #include <QImage> #include <QColor> #include <QPainter> #include <QDebug> #include <QCache> #include <QCoreApplication> #include <QJsonObject> #include <QDir> #include <QJsonArray> #include <cmath> #include <iostream> #include <limits> #include <rapidjson/document.h> using namespace rapidjson; /// Recursively parse through a directory structure contained in a json value static QStringList _parseDirectory( const Value& dir, QString prefix ) { QStringList fileList; for (rapidjson::SizeType i = 0; i < dir.Size(); i++) { const Value& name = dir[i]; QString filename = QString::fromStdString(name["name"].GetString()); if (name.HasMember("dir")) { const Value& subdir = name["dir"]; QStringList subFileList = _parseDirectory( subdir, prefix + "/" + filename ); fileList.append( subFileList ); } else { if (prefix != "") { filename = prefix + "/" + filename; } fileList.append(filename); //const char *printableName = filename.toLocal8Bit().constData(); //printf("%s \n", printableName); } } //return fileList.join(','); return fileList; } Viewer::Viewer() : QObject( nullptr ), m_viewManager( nullptr) { int port = Globals::instance()->cmdLineInfo()-> scriptPort(); qDebug() << "Port="<<port; if ( port < 0 ) { qDebug() << "Not listening to scripted commands."; } else { // m_scl = new ScriptedCommandListener( port, this ); qDebug() << "Listening to scripted commands on port " << port; // create Pavol's testing controller on port+1 //new Carta::Core::ScriptedClient::ScriptedCommandInterpreter( port+1, this); new Carta::Core::ScriptedClient::ScriptedCommandInterpreter( port, this); } m_devView = false; } void Viewer::start() { qDebug() << "Viewer::start() starting"; auto & globals = * Globals::instance(); // tell all plugins that the core has initialized globals.pluginManager()-> prepare < Carta::Lib::Hooks::Initialize > ().executeAll(); // ask plugins to load the image qDebug() << "======== trying to load image ========"; QString fname; if( ! Globals::instance()-> platform()-> initialFileList().isEmpty()) { fname = Globals::instance()-> platform()-> initialFileList() [0]; } if ( m_viewManager == nullptr ){ Carta::State::ObjectManager* objectManager = Carta::State::ObjectManager::objectManager(); Carta::Data::ViewManager* vm = objectManager->createObject<Carta::Data::ViewManager> (); m_viewManager.reset( vm ); } else { m_viewManager->reload(); } if ( m_devView ){ m_viewManager->setDeveloperView(); } if ( fname.length() > 0 ) { QString controlId = m_viewManager->getObjectId( Carta::Data::Controller::PLUGIN_NAME, 0); bool successfulLoad = false; QString result = m_viewManager->loadFile( controlId, fname, &successfulLoad ); if ( !successfulLoad ){ qDebug() << result; } } qDebug() << "Viewer has been initialized."; } void Viewer::DBClose() { std::shared_ptr<Carta::Lib::IPCache> m_diskCache; // find the unique shared_ptr of cache and release it by force auto res = Globals::instance()-> pluginManager() -> prepare < Carta::Lib::Hooks::GetPersistentCache > ().first(); if ( res.isNull() || ! res.val() ) { qWarning( "Could not find a disk cache plugin." ); m_diskCache = nullptr; } else { m_diskCache = res.val(); m_diskCache->Release(); } } void Viewer::setDeveloperView( ){ m_devView = true; }
gpl-3.0
ADyson/clDM-EWR
AdjustRecon.cpp
7266
// AdjustRecon.cpp : implementation file // #include "stdafx.h" #include "AdjustRecon.h" #include "afxdialogex.h" #include "FTSR.h" #include "boost\lexical_cast.hpp" #include "Utility.h" #include "ClKernelsAdjust.h" #include "clState.h" // AdjustRecon dialog IMPLEMENT_DYNAMIC(AdjustRecon, CDialog) AdjustRecon::AdjustRecon(CWnd* pParent /*=NULL*/) : CDialog(AdjustRecon::IDD, pParent) { mParent = pParent; C1 = "0"; C3 = "0"; A1r = "0"; A1i = "0"; A2r = "0"; B2r = "0"; A3r = "0"; S3r = "0"; A2i = "0"; B2i = "0"; A3i = "0"; S3i = "0"; } AdjustRecon::~AdjustRecon() { } void AdjustRecon::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_C1, m_C1); DDX_Text(pDX,IDC_C1,C1); DDX_Control(pDX, IDC_C3, m_C3); DDX_Text(pDX,IDC_C3,C3); DDX_Control(pDX, IDC_A1R, m_A1r); DDX_Text(pDX,IDC_A1R,A1r); DDX_Control(pDX, IDC_A1I, m_A1i); DDX_Text(pDX,IDC_A1I,A1i); DDX_Control(pDX, IDC_A2R, m_A2r); DDX_Text(pDX,IDC_A2R,A2r); DDX_Control(pDX, IDC_B2R, m_B2r); DDX_Text(pDX,IDC_B2R,B2r); DDX_Control(pDX, IDC_A3R, m_A3r); DDX_Text(pDX,IDC_A3R,A3r); DDX_Control(pDX, IDC_S3R, m_S3r); DDX_Text(pDX,IDC_S3R,S3r); DDX_Control(pDX, IDC_A2I, m_A2i); DDX_Text(pDX,IDC_A2I,A2i); DDX_Control(pDX, IDC_B2I, m_B2i); DDX_Text(pDX,IDC_B2I,B2i); DDX_Control(pDX, IDC_A3I, m_A3i); DDX_Text(pDX,IDC_A3I,A3i); DDX_Control(pDX, IDC_S3I, m_S3i); DDX_Text(pDX,IDC_S3I,S3i); } BEGIN_MESSAGE_MAP(AdjustRecon, CDialog) ON_BN_CLICKED(IDC_MAKECORRECTED, &AdjustRecon::OnBnClickedAdjust) END_MESSAGE_MAP() // AdjustRecon message handlers // This is apparently needed for Modeless dialogs to not have a memory leak when they are closed. void AdjustRecon::PostNcDestroy() { CDialog::PostNcDestroy(); delete this; } void AdjustRecon::OnBnClickedAdjust() { // Get Reconstructed Image - > Make a new one with aberrations corrected UpdateData(true); EWR* ParentClass = (EWR*)mParent; clQueue* clq = clState::clq; cl_context context = clState::context; clDevice* cldev = clState::cldev; DigitalMicrograph::Image Recon = DigitalMicrograph::GetFrontImage(); DigitalMicrograph::TagGroup ReconTags = Recon.GetTagGroup(); float wavelength; float kmax; try { ReconTags.GetTagAsFloat("Reconstruction:Wavelength",&wavelength); ReconTags.GetTagAsFloat("Reconstruction:Kmax",&kmax); } catch(...) { DigitalMicrograph::Result("Are you sure this is a reconstructed image, some tags are missing \n"); } // Get image size and calibrations. Gatan::uint32 xDim; // Dont use these in a sum that can go negative, will break things i.e. (1-xdim)/2 wont work... Gatan::uint32 yDim; // Dont use these in a sum that can go negative, will break things i.e. (1-xdim)/2 wont work... Recon.GetDimensionSizes(xDim,yDim); float reconpixelscale = Recon.GetDimensionScale(0); int xSize = xDim; int ySize = yDim; // Get abberation values from dialog. float fC1 = boost::lexical_cast<float>(C1); float fC3 = boost::lexical_cast<float>(C3); float fA1r = boost::lexical_cast<float>(A1r); float fA1i = boost::lexical_cast<float>(A1i); float fA2r = boost::lexical_cast<float>(A2r); float fB2r = boost::lexical_cast<float>(B2r); float fA3r = boost::lexical_cast<float>(A3r); float fS3r = boost::lexical_cast<float>(S3r); float fA2i = boost::lexical_cast<float>(A2i); float fB2i = boost::lexical_cast<float>(B2i); float fA3i = boost::lexical_cast<float>(A3i); float fS3i = boost::lexical_cast<float>(S3i); // Make frequency arrays float* xFrequencies = new float[xDim]; float* yFrequencies = new float[yDim]; int midX = ceil(float(xDim)/2); int midY = ceil(float(yDim)/2); for(int i = 1 ; i <= xDim ; i++) { if(i <= midX) xFrequencies[i-1] = (i - 1)/(reconpixelscale * xSize); else xFrequencies[i-1] = (i - 1 - xSize)/(reconpixelscale * xSize); } for(int i = 1 ; i <= yDim ; i++) { if(i <= midY) yFrequencies[i-1] = (i - 1)/(reconpixelscale * ySize); else { float a = (i - 1 - ySize); yFrequencies[i-1] = a/(reconpixelscale * ySize); } } // Upload to GPU cl_mem clxFrequencies = clCreateBuffer ( context, CL_MEM_READ_WRITE, xDim * sizeof(cl_float), 0, &status); cl_mem clyFrequencies = clCreateBuffer ( context, CL_MEM_READ_WRITE, yDim * sizeof(cl_float), 0, &status); clEnqueueWriteBuffer( clq->cmdQueue, clxFrequencies, CL_FALSE, 0, xDim*sizeof(float), &xFrequencies[0], 0, NULL, NULL ); clEnqueueWriteBuffer( clq->cmdQueue, clyFrequencies, CL_TRUE, 0, yDim*sizeof(float), &yFrequencies[0], 0, NULL, NULL ); cl_mem clReconstruction = clCreateBuffer ( context, CL_MEM_READ_WRITE, xDim * yDim * sizeof(cl_float2), 0, &status); cl_mem clReconstruction2 = clCreateBuffer ( context, CL_MEM_READ_WRITE, xDim * yDim * sizeof(cl_float2), 0, &status); cl_mem clCorrected = clCreateBuffer ( context, CL_MEM_READ_WRITE, xDim * yDim * sizeof(cl_float2), 0, &status); ; // Upload the image to the GPU // FFT it Gatan::PlugIn::ImageDataLocker ReconLocker(Recon); Gatan::complex64* data = (Gatan::complex64*)ReconLocker.get(); std::vector<cl_float2> datavec(xSize*ySize); for(int i = 1 ; i < xDim * yDim ; i++) { datavec[i].s[0] = data[i].real() - 1; datavec[i].s[1] = data[i].imag(); } clFourier* FFT = new clFourier(context, clq); FFT->Setup(xSize,ySize); clEnqueueWriteBuffer(clq->cmdQueue, clReconstruction , CL_TRUE, 0 , xDim * yDim * sizeof(cl_float2) , &datavec[0] , 0 , NULL , NULL); ReconLocker.~ImageDataLocker(); FFT->Enqueue(clReconstruction,clReconstruction2,CLFFT_FORWARD); // Create kernel to do reconstruction correction clKernel* clThirdOrderCorrection = new clKernel(ThirdOrderCorrectionsource,context,cldev,"clThirdOrderCorrection",clq); clThirdOrderCorrection->BuildKernel(); clThirdOrderCorrection->SetArgT(0,clReconstruction2); clThirdOrderCorrection->SetArgT(1,clCorrected); clThirdOrderCorrection->SetArgT(2,clxFrequencies); clThirdOrderCorrection->SetArgT(3,clyFrequencies); clThirdOrderCorrection->SetArgT(4,xSize); clThirdOrderCorrection->SetArgT(5,ySize); clThirdOrderCorrection->SetArgT(6,wavelength); clThirdOrderCorrection->SetArgT(7,fA1r); clThirdOrderCorrection->SetArgT(8,fA1i); clThirdOrderCorrection->SetArgT(9,fA2r); clThirdOrderCorrection->SetArgT(10,fA2i); clThirdOrderCorrection->SetArgT(11,fA3r); clThirdOrderCorrection->SetArgT(12,fA3i); clThirdOrderCorrection->SetArgT(13,fB2r); clThirdOrderCorrection->SetArgT(14,fB2i); clThirdOrderCorrection->SetArgT(15,fS3r); clThirdOrderCorrection->SetArgT(16,fS3i); clThirdOrderCorrection->SetArgT(17,fC1); clThirdOrderCorrection->SetArgT(18,fC3); clThirdOrderCorrection->SetArgT(19,kmax); size_t* globalWorkSize = new size_t[3]; globalWorkSize[0] = xSize; globalWorkSize[1] = ySize; globalWorkSize[2] = 1; clThirdOrderCorrection->Enqueue(globalWorkSize); // FFT back FFT->Enqueue(clCorrected,clReconstruction,CLFFT_BACKWARD); DigitalMicrograph::Image CorrectedImage = Utility::PrintCLMemToImagePlusOne(clReconstruction,"Adjusted Reconstruction",xSize,ySize,clFloat2,clq); CorrectedImage.GetImageDisplay(0).SetComplexMode(5); clThirdOrderCorrection->~clKernel(); clReleaseMemObject(clCorrected); clReleaseMemObject(clReconstruction); clReleaseMemObject(clReconstruction2); }
gpl-3.0
projectestac/alexandria
html/langpacks/de/availability_role.php
2031
<?php // This file is part of Moodle - https://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <https://www.gnu.org/licenses/>. /** * Strings for component 'availability_role', language 'de', version '3.11'. * * @package availability_role * @category string * @copyright 1999 Martin Dougiamas and contributors * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['description'] = 'Zugriff über eine bestimmte Rolle regeln'; $string['error_selectrole'] = 'Sie müssen eine Rolle auswählen.'; $string['missing'] = '[Rolle fehlt]'; $string['pluginname'] = 'Voraussetzung: Kursrolle'; $string['privacy:metadata'] = 'Das Plugin \'Voraussetzung: Kursrolle\' speichert keine personenbezogene Daten.'; $string['requires_notrole'] = 'Sie sind nicht <em>{$a}</em>'; $string['requires_role'] = 'Sie sind <em>{$a}</em>'; $string['setting_supportedrolesheading'] = 'Unterstützte Rollen'; $string['setting_supportguestrole'] = 'Gastzugang'; $string['setting_supportguestrole_desc'] = 'Wenn diese Option aktiviert ist, kann die Voraussetzung auch für Nutzer/innen gesetzt werden, die den Kurs als Gast betrachten.'; $string['setting_supportnotloggedinrole'] = 'Nicht eingeloggt'; $string['setting_supportnotloggedinrole_desc'] = 'Wenn diese Option aktiviert ist, kann die Voraussetzung auch für Nutzer/innen gesetzt werden, die in Moodle nicht eingeloggt sind.'; $string['title'] = 'Rolle';
gpl-3.0
samszo/open-edition
plugins/auto/compositions/v3.5.3/lang/compositions_sk.php
2155
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // extrait automatiquement de http://trad.spip.net/tradlang_module/compositions?lang_cible=sk // ** ne pas modifier le fichier ** if (!defined('_ECRIRE_INC_VERSION')) { return; } $GLOBALS[$GLOBALS['idx_lang']] = array( // C 'composition' => 'Rozmiestnenie', 'composition_defaut' => 'predvolené rozmiestnenie', 'composition_heritee' => 'zdedené', 'composition_utilisee' => 'Rozmiestnenie:', 'composition_verrouillee' => 'Toto rozmiestnenie webmaster zamkol.', 'compositions' => 'Rozmiestnenia', // D 'des_utilisations' => '@nb@ použití', // H 'heritages' => 'Toto rozmiestnenie je predvolených rozmiestnením pre tieto objekty:', // I 'info_aucune_composition' => 'Žiadne rozmiestnenie', // L 'label_activer_composition_objets' => 'Rozmiestnenia používať na objekty', 'label_branche_verrouillee' => 'Rozmiestnenia tejto vetvy sú zamknuté.', 'label_chemin_compositions' => 'Priečinok s rozmiestneniami', 'label_chemin_compositions_details' => 'Zadajte umiestnenie, v ktorom sa budú hľadať šablóny rozmiestnenia.', 'label_composition' => 'Rozmiestnenie', 'label_composition_branche_lock' => 'Zamknúť rozmiestnenie všetkých objektov vetvy', 'label_composition_explication' => 'Vy ste webmaster, môžete', 'label_composition_lock' => 'Zamknúť rozmiestnenie', 'label_composition_rubrique' => 'Rozmiestnenie pre rubriky', 'label_information' => 'Informácie', 'label_masquer_formulaire' => 'Schovať formulár', 'label_masquer_formulaire_composition' => 'Schovať formulár s výberom rozmiestnenia, ak ho používateľ nemá právo meniť.', 'label_pas_de_composition' => 'Žiadne rozmiestnenie', 'label_styliser' => 'Výber šablón', 'label_styliser_auto' => 'Nepoužívajte automatický výber. Výber podporujú moje šablóny.', 'label_tout_verrouiller' => 'Zamknúť všetky', 'label_toutes_verrouilles' => 'Všetky rozmiestnenia sú zamknuté.', 'label_verrouiller_toutes_compositions' => 'Zamknúť všetky rozmiestnenia (môže to zmeniť len webmaster).', // U 'une_utilisation' => '1 použitie' ); ?>
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-6.js
782
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.4/15.4.4/15.4.4.18/15.4.4.18-5-6.js * @description Array.prototype.forEach - thisArg is function */ function testcase() { var res = false; var result; function callbackfn(val, idx, obj) { result = this.res; } function foo(){} foo.res = true; var arr = [1]; arr.forEach(callbackfn,foo) if( result === true) return true; } runTestCase(testcase);
gpl-3.0
catdoru/taxi
i/zakaz_otmenen_clientom.php
457
<? require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php"); CModule::IncludeModule("iblock"); global $USER; CIBlockElement::SetPropertyValues($z, 5, Array("VALUE"=>"" ) ,"vkorzine_ukogo_id" ); //очистить UF_LIVEZAKAZ у текущего водителя $user = new CUser; $fields = Array( "UF_LIVEZAKAZ" => "" ); $user->Update($USER->GetID(), $fields); echo "y"; require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php"); ?>
gpl-3.0
villagedefrance/OpenCart-Overclocked
upload/system/vendor/stripe-php/lib/Stripe/Recipient.php
1768
<?php class Stripe_Recipient extends Stripe_ApiResource { /** * @param string $id The ID of the recipient to retrieve. * @param string|null $apiKey * * @return Stripe_Recipient */ public static function retrieve($id, $apiKey=null) { $class = get_class(); return self::_scopedRetrieve($class, $id, $apiKey); } /** * @param array|null $params * @param string|null $apiKey * * @return array An array of Stripe_Recipients. */ public static function all($params=null, $apiKey=null) { $class = get_class(); return self::_scopedAll($class, $params, $apiKey); } /** * @param array|null $params * @param string|null $apiKey * * @return Stripe_Recipient The created recipient. */ public static function create($params=null, $apiKey=null) { $class = get_class(); return self::_scopedCreate($class, $params, $apiKey); } /** * @return Stripe_Recipient The saved recipient. */ public function save() { $class = get_class(); return self::_scopedSave($class); } /** * @param array|null $params * * @return Stripe_Recipient The deleted recipient. */ public function delete($params=null) { $class = get_class(); return self::_scopedDelete($class, $params); } /** * @param array|null $params * * @return array An array of the recipient's Stripe_Transfers. */ public function transfers($params=null) { if (!$params) { $params = array(); } $params['recipient'] = $this->id; $transfers = Stripe_Transfer::all($params, $this->_apiKey); return $transfers; } }
gpl-3.0
15Mpedia/15Mpedia-scripts
youtube-missingparams.py
5645
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2014 emijrp # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import catlib import datetime import re import os import subprocess import sys import time import pagegenerators import urllib2 import wikipedia """ Bot para copiar la duración y tags de YouTube """ def main(): site = wikipedia.Site('15mpedia', '15mpedia') cat = catlib.Category(site, u"Category:Archivos en YouTube") gen = pagegenerators.CategorizedPageGenerator(cat, start=u'Archivo:YouTube - raffaellopinta - mnQdKhVzRek.jpg') pre = pagegenerators.PreloadingGenerator(gen, pageNumber=60) for page in pre: wtitle = page.title() wtext = page.get() print wtitle if re.search(ur"\|\s*palabras[ _]clave\s*=", wtext) and \ re.search(ur"\|\s*duración\s*=", wtext): print u"Nada que añadir" continue youtubeid = re.findall(ur'(?im)\|\s*embebido id\s*=\s*([^\r\n]*?)[\r\n]', wtext)[0] youtubeid = re.sub(' ', '_', youtubeid) youtubeurl = 'http://www.youtube.com/watch?v=%s' % (youtubeid) req = urllib2.Request(youtubeurl, headers={ 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0' }) raw = unicode(urllib2.urlopen(req).read(), 'utf-8') if not re.search(ur"'IS_UNAVAILABLE_PAGE': false,", raw) and re.search(ur"<h1 id=\"unavailable-message\"", raw): disponibilidad = u"" if re.search(ur"<h1 id=\"unavailable-message\" class=\"message\">[^<]*?(This video is unavailable|Este vídeo no está disponible)[^<]*?</h1>", raw): disponibilidad = u"unavailable" elif re.search(ur"<h1 id=\"unavailable-message\" class=\"message\">[^<]*?(This video is private|Este vídeo es privado)[^<]*?</h1>", raw): disponibilidad = u"private" elif re.search(ur"<h1 id=\"unavailable-message\" class=\"message\">[^<]*?(cancelado la cuenta)[^<]*?</h1>", raw): disponibilidad = u"canceled-account" elif re.search(ur"<h1 id=\"unavailable-message\" class=\"message\">[^<]*?(El usuario ha suprimido este vídeo)[^<]*?</h1>", raw): disponibilidad = u"deleted-by-user" elif re.search(ur"<h1 id=\"unavailable-message\" class=\"message\">[^<]*?(el usuario que lo ha subido ha cerrado su cuenta)[^<]*?</h1>", raw): disponibilidad = u"account-closed-by-user" else: print u"New error message for video" print youtubeid print re.findall(ur"<h1 id=\"unavailable-message\"[^>]*?>\s*([^<]*?)\s*</h1>", raw) sys.exit() if disponibilidad: newtext = wtext summary = [] if re.search(ur"(?im)\|\s*disponibilidad\s*=", newtext): newtext = re.sub(ur"(?im)\|\s*disponibilidad\s*=\s*[a-z\s*-]+?(?P<g1>[\r\n])", ur"|disponibilidad=%s\g<g1>" % (disponibilidad), newtext) else: newtext = re.sub(ur"(?im)(?P<g1>\|autor)", ur"|disponibilidad=%s\n\g<g1>" % (disponibilidad), newtext) summary.append(u"disponibilidad=%s" % (disponibilidad)) if newtext != wtext: wikipedia.showDiff(wtext, newtext) summary = u', '.join(summary) print summary page.put(newtext, u"BOT - Añadiendo: %s" % summary) time.sleep(3) else: youtubetags = [] m = re.findall(ur"(?im)<meta property=\"og:video:tag\" content=\"([^>]*?)\">", raw) if m: for tag in m: youtubetags.append(tag) youtubetags = ', '.join(youtubetags) print youtubetags youtubeduration = '' youtubeduration = subprocess.Popen(["python", "youtube-dl", youtubeurl, "--get-duration"], stdout=subprocess.PIPE).communicate()[0].strip() print youtubeduration newtext = wtext summary = [] if youtubeduration and not re.search(ur"(?im)\|\s*duración\s*=", newtext): newtext = re.sub(ur"(?im)(?P<g1>\|autor)", ur"|duración=%s\n\g<g1>" % (youtubeduration), newtext) summary.append(u"duración=%s" % (youtubeduration)) if youtubetags and not re.search(ur"(?im)\|\s*palabras clave\s*=", newtext): newtext = re.sub(ur"(?im)(?P<g1>\|autor)", ur"|palabras clave=%s\n\g<g1>" % (youtubetags), newtext) summary.append(u"palabras clave=%s" % (youtubetags)) if newtext != wtext: wikipedia.showDiff(wtext, newtext) summary = u', '.join(summary) print summary page.put(newtext, u"BOT - Añadiendo: %s" % summary) time.sleep(3) if __name__ == '__main__': main()
gpl-3.0
mcisse3007/moodle_esco_master
mod/dataform/backup/moodle2/restore_dataform_stepslib.php
13902
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package mod_dataform * @copyright 2011 Itamar Tzadok * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /** * Define all the restore steps that will be used by the restore_dataform_activity_task. */ /** * Structure step to restore one dataform activity. */ class restore_dataform_activity_structure_step extends restore_activity_structure_step { /** * */ protected function define_structure() { $paths = array(); $userinfo = $this->get_setting_value('userinfo'); // Restore content and user info (requires the backup users). $paths[] = new restore_path_element('dataform', '/activity/dataform'); $paths[] = new restore_path_element('dataform_field', '/activity/dataform/fields/field'); $paths[] = new restore_path_element('dataform_filter', '/activity/dataform/filters/filter'); $paths[] = new restore_path_element('dataform_view', '/activity/dataform/views/view'); if ($userinfo) { $paths[] = new restore_path_element('dataform_entry', '/activity/dataform/entries/entry'); $paths[] = new restore_path_element('dataform_content', '/activity/dataform/entries/entry/contents/content'); $paths[] = new restore_path_element('dataform_rating', '/activity/dataform/entries/entry/ratings/rating'); } // Return the paths wrapped into standard activity structure. return $this->prepare_activity_structure($paths); } /** * */ protected function process_dataform($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->course = $this->get_courseid(); $data->timemodified = $this->apply_date_offset($data->timemodified); $data->timeavailable = $this->apply_date_offset($data->timeavailable); $data->timedue = $this->apply_date_offset($data->timedue); if ($data->grade < 0) { // Scale found, get mapping. $data->grade = -($this->get_mappingid('scale', abs($data->grade))); } $newitemid = $this->task->get_activityid(); if ($newitemid) { $data->id = $newitemid; $DB->update_record('dataform', $data); } else { // Insert the dataform record. $newitemid = $DB->insert_record('dataform', $data); } $this->apply_activity_instance($newitemid); } /** * This must be invoked immediately after creating/updating the "module" activity record * and will adjust the new activity id (the instance) in various places * Overriding the parent method to handle restoring into the activity. */ protected function apply_activity_instance($newitemid) { global $DB; if ($newitemid == $this->task->get_activityid()) { // Remap task module id. $this->set_mapping('course_module', $this->task->get_old_moduleid(), $this->task->get_moduleid()); // Remap task context id. $this->set_mapping('context', $this->task->get_old_contextid(), $this->task->get_contextid()); } else { // Save activity id in task. $this->task->set_activityid($newitemid); // Apply the id to course_modules->instance. $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid())); } // Do the mapping for modulename, preparing it for files by oldcontext. $oldid = $this->task->get_old_activityid(); $this->set_mapping('dataform', $oldid, $newitemid, true); } /** * */ protected function process_dataform_field($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->dataid = $this->get_new_parentid('dataform'); // Insert the dataform_fields record. $newitemid = $DB->insert_record('dataform_fields', $data); $this->set_mapping('dataform_field', $oldid, $newitemid, true); // Process any field specific data. $data->id = $newitemid; $restoreclass = 'dataformfield_'. $data->type. "_restore"; if (method_exists($restoreclass, 'process')) { $restoreclass::process($this, $data); } } /** * */ protected function process_dataform_filter($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->dataid = $this->get_new_parentid('dataform'); // Adjust customsort field ids. if ($data->customsort) { $customsort = unserialize($data->customsort); $sortfields = array(); foreach ($customsort as $sortfield => $sortdir) { if ($sortfield > 0) { $sortfields[$this->get_mappingid('dataform_field', $sortfield)] = $sortdir; } else { $sortfields[$sortfield] = $sortdir; } } $data->customsort = serialize($sortfields); } // Adjust customsearch field ids. if ($data->customsearch) { $customsearch = unserialize($data->customsearch); $searchfields = array(); foreach ($customsearch as $searchfield => $options) { if ($searchfield > 0) { $searchfields[$this->get_mappingid('dataform_field', $searchfield)] = $options; } else { $searchfields[$searchfield] = $options; } } $data->customsearch = serialize($searchfields); } // Insert the dataform_filters record. $newitemid = $DB->insert_record('dataform_filters', $data); $this->set_mapping('dataform_filter', $oldid, $newitemid, false); // No files associated. } /** * */ protected function process_dataform_view($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->dataid = $this->get_new_parentid('dataform'); // Adjust view filter id. if ($data->filterid) { $data->filterid = $this->get_mappingid('dataform_filter', $data->filterid); } // Adjust pattern field ids. if ($data->patterns) { $patterns = unserialize($data->patterns); $newpatterns = array(); if (!empty($patterns['view'])) { $newpatterns['view'] = $patterns['view']; } if (!empty($patterns['field'])) { $newpatterns['field'] = array(); foreach ($patterns['field'] as $fieldid => $tags) { if ($fieldid > 0) { $newpatterns['field'][$this->get_mappingid('dataform_field', $fieldid)] = $tags; } else { $newpatterns['field'][$fieldid] = $tags; } } } $data->patterns = serialize($newpatterns); } // Insert the dataform_views record. $newitemid = $DB->insert_record('dataform_views', $data); $this->set_mapping('dataform_view', $oldid, $newitemid, true); // Process any view specific data. $data->id = $newitemid; $restoreclass = 'dataformview_'. $data->type. "_restore"; if (method_exists($restoreclass, 'process')) { $restoreclass::process($this, $data); } } /** * */ protected function process_dataform_entry($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->dataid = $this->get_new_parentid('dataform'); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); if ($userid = $this->task->get_ownerid()) { $data->userid = $userid; } else { $data->userid = $this->get_mappingid('user', $data->userid); } $data->groupid = $this->get_mappingid('group', $data->groupid); // Insert the dataform_entries record. $newitemid = $DB->insert_record('dataform_entries', $data); $this->set_mapping('dataform_entry', $oldid, $newitemid, false); // No files associated. } /** * */ protected function process_dataform_content($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->fieldid = $this->get_mappingid('dataform_field', $data->fieldid); $data->entryid = $this->get_new_parentid('dataform_entry'); // Insert the data_content record. $newitemid = $DB->insert_record('dataform_contents', $data); $this->set_mapping('dataform_content', $oldid, $newitemid, true); // Files by this item id. } /** * */ protected function process_dataform_rating($data) { $data = (object)$data; $data->itemid = $this->get_new_parentid('dataform_entry'); $this->process_this_rating($data); } /** * */ protected function process_this_rating($data) { global $DB; $data = (object)$data; $data->contextid = $this->task->get_contextid(); if ($data->scaleid < 0) { // Scale found, get mapping. $data->scaleid = -($this->get_mappingid('scale', abs($data->scaleid))); } $data->rating = $data->value; $data->userid = $this->get_mappingid('user', $data->userid); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $newitemid = $DB->insert_record('rating', $data); } /** * TODO Add preset related files, matching by itemname (data_content). * $this->add_related_files('mod_dataform', 'course_presets', 'dataform'); * */ protected function after_execute() { global $DB; // Add dataform related files, no need to match by itemname (just internally handled context). $this->add_related_files('mod_dataform', 'intro', null); $this->add_related_files('mod_dataform', 'activityicon', null); // Add content related files, matching by item id (dataform_content). $this->add_related_files('mod_dataform', 'content', 'dataform_content'); $dataformnewid = $this->get_new_parentid('dataform'); // Default view. if ($defaultview = $DB->get_field('dataform', 'defaultview', array('id' => $dataformnewid))) { if ($defaultview = $this->get_mappingid('dataform_view', $defaultview)) { $DB->set_field('dataform', 'defaultview', $defaultview, array('id' => $dataformnewid)); } } // Default filter. if ($defaultfilter = $DB->get_field('dataform', 'defaultfilter', array('id' => $dataformnewid))) { if ($defaultfilter = $this->get_mappingid('dataform_filter', $defaultfilter)) { $DB->set_field('dataform', 'defaultfilter', $defaultfilter, array('id' => $dataformnewid)); } } // Submission redirect view. $this->adjust_view_submission_redirect(); // Process dataformview after execute. $this->after_execute_dataform_plugin('dataformview', 'dataform_view'); // Process dataformfield after execute. $this->after_execute_dataform_plugin('dataformfield', 'dataform_field'); } /** * */ protected function after_execute_dataform_plugin($plugintype, $source) { $plugins = core_component::get_plugin_list($plugintype); foreach ($plugins as $type => $unused) { // Process any plugin specific data. $restoreclass = $plugintype. "_$type". "_restore"; if (method_exists($restoreclass, 'after_execute')) { $restoreclass::after_execute($this); } // Add related files, matching by item id. $pluginclass = $plugintype. "_$type". "_$type"; foreach ($pluginclass::get_file_areas() as $filearea) { $this->add_related_files($pluginclass, $filearea, $source); } } } /** * Adjusts view submission redirect view id. */ protected function adjust_view_submission_redirect() { global $DB; $dataformnewid = $this->get_new_parentid('dataform'); if ($views = $DB->get_records('dataform_views', array('dataid' => $dataformnewid))) { foreach ($views as $viewid => $view) { if (empty($view->submission)) { continue; } $submission = unserialize(base64_decode($view->submission)); if (empty($submission['redirect'])) { continue; } $submission['redirect'] = $this->get_mappingid('dataform_view', $submission['redirect']); $submission = base64_encode(serialize($submission)); $DB->set_field('dataform_views', 'submission', $submission, array('id' => $viewid)); } } } }
gpl-3.0
tfossi/APolGe
src/tfossi/apolge/common/state/guard/After_.java
1884
/** * */ package tfossi.apolge.common.state.guard; import static tfossi.apolge.time.pit.ConstCPPit.*; import tfossi.apolge.common.scripting.PreAddress; import tfossi.apolge.data.core.ICoreData; import tfossi.apolge.data.guide.IGuideData; import tfossi.apolge.time.pit.PPiT; /** * Guard überwacht, dass eine Transition vor einem Zeitpunkt stattfindet. * * @author tfossi * @version 26.01.2015 * @modified - * @since Java 1.6 */ public class After_ implements _Guard{ /** clock */ private final PPiT clock; /** * Guard überwacht, dass eine Transition vor einem Zeitpunkt stattfindet. * * @param address * ist Datenquelle * @param datetime * ist Referenzzeitpunkt * @modified - */ public After_(final PreAddress address, Object datetime){ this.clock = string2DataTime((String)datetime); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString(){ return this.getClass().getSimpleName()+": "+this.clock.getDatetime(DATE|TIME); } /* (non-Javadoc) * @see tfossi.apolge.common.p_state.guard._Guard#tstIndexGuard(java.lang.Object) */ @Override public final boolean tstGuard4Chg2Passiv(final Object index, final double[] yk){ assert false; // CPiT tstClock = CM_DateTime.fill(this.clock, (CPiT)index); // return CM_DateTime.after((CPiT)index, tstClock); return false; } @Override public final boolean tstGuard4Chg2Passiv(final ICoreData data) { return false; } /* (non-Javadoc) * @see tfossi.apolge.common.p_state.guard._Guard#getVertex() */ @Override public final IGuideData getVertex(){ return null; } /* (non-Javadoc) * @see tfossi.apolge.common.p_state.guard._Guard#getGuardType() */ @Override public Class<?> getGuardType() { return PPiT.class; } }
gpl-3.0
OlafLee/RankSys
RankSys-core/src/main/java/es/uam/eps/ir/ranksys/core/util/topn/package-info.java
867
/* * Copyright (C) 2015 Information Retrieval Group at Universidad Autonoma * de Madrid, http://ir.ii.uam.es * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Bounded min-heaps to keep the top-n values. */ package es.uam.eps.ir.ranksys.core.util.topn;
gpl-3.0
crayner/Gibbon
modules/Students/report_students_byRollGroup.php
6806
<?php /* Gibbon, Flexible & Open School System Copyright (C) 2010, Ross Parker This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ use Gibbon\Forms\Form; use Gibbon\Forms\DatabaseFormFactory; use Gibbon\Tables\Prefab\ReportTable; use Gibbon\Services\Format; use Gibbon\Domain\Students\StudentGateway; use Gibbon\Domain\Students\MedicalGateway; use Gibbon\Domain\RollGroups\RollGroupGateway; //Module includes require_once __DIR__ . '/moduleFunctions.php'; if (isActionAccessible($guid, $connection2, '/modules/Students/report_students_byRollGroup.php') == false) { //Acess denied echo "<div class='error'>"; echo __('You do not have access to this action.'); echo '</div>'; } else { //Proceed! $gibbonRollGroupID = (isset($_GET['gibbonRollGroupID']) ? $_GET['gibbonRollGroupID'] : null); $view = isset($_GET['view']) ? $_GET['view'] : 'basic'; $viewMode = isset($_REQUEST['format']) ? $_REQUEST['format'] : ''; if (empty($viewMode)) { $page->breadcrumbs->add(__('Students by Roll Group')); $form = Form::create('action', $_SESSION[$guid]['absoluteURL'].'/index.php', 'get'); $form->setTitle(__('Choose Roll Group')) ->setFactory(DatabaseFormFactory::create($pdo)) ->setClass('noIntBorder fullWidth'); $form->addHiddenValue('q', "/modules/".$_SESSION[$guid]['module']."/report_students_byRollGroup.php"); $row = $form->addRow(); $row->addLabel('gibbonRollGroupID', __('Roll Group')); $row->addSelectRollGroup('gibbonRollGroupID', $_SESSION[$guid]['gibbonSchoolYearID'], true)->selected($gibbonRollGroupID)->placeholder()->isRequired(); $row = $form->addRow(); $row->addLabel('view', __('View')); $row->addSelect('view')->fromArray(array('basic' => __('Basic'), 'extended' =>__('Extended')))->selected($view)->isRequired(); $row = $form->addRow(); $row->addFooter(); $row->addSearchSubmit($gibbon->session); echo $form->getOutput(); } // Cancel out early if there's no roll group selected if (empty($gibbonRollGroupID)) return; $rollGroupGateway = $container->get(RollGroupGateway::class); $studentGateway = $container->get(StudentGateway::class); $medicalGateway = $container->get(MedicalGateway::class); // QUERY $criteria = $studentGateway->newQueryCriteria() ->sortBy(['rollGroup', 'surname', 'preferredName']) ->pageSize(!empty($viewMode) ? 0 : 50) ->filterBy('view', $view) ->fromArray($_POST); $students = $studentGateway->queryStudentEnrolmentByRollGroup($criteria, $gibbonRollGroupID != '*' ? $gibbonRollGroupID : null); // DATA TABLE $table = ReportTable::createPaginated('studentsByRollGroup', $criteria)->setViewMode($viewMode, $gibbon->session); $table->setTitle(__('Report Data')); $table->setDescription(function () use ($gibbonRollGroupID, $rollGroupGateway) { $output = ''; if ($gibbonRollGroupID == '*') return $output; if ($rollGroup = $rollGroupGateway->getRollGroupByID($gibbonRollGroupID)) { $output .= '<b>'.__('Roll Group').'</b>: '.$rollGroup['name']; } if ($tutors = $rollGroupGateway->selectTutorsByRollGroup($gibbonRollGroupID)->fetchAll()) { $output .= '<br/><b>'.__('Tutors').'</b>: '.Format::nameList($tutors, 'Staff'); } return $output; }); $table->addMetaData('filterOptions', [ 'view:basic' => __('View').': '.__('Basic'), 'view:extended' => __('View').': '.__('Extended'), ]); $table->addColumn('rollGroup', __('Roll Group'))->width('5%'); $table->addColumn('student', __('Student')) ->sortable(['surname', 'preferredName']) ->format(function ($person) { return Format::name('', $person['preferredName'], $person['surname'], 'Student', true, true) . '<br/><small><i>'.Format::userStatusInfo($person).'</i></small>'; }); if ($criteria->hasFilter('view', 'extended')) { $table->addColumn('gender', __('Gender')); $table->addColumn('dob', __('Age').'<br/>'.Format::small('DOB')) ->format(function ($values) { return !empty($values['dob']) ? Format::age($values['dob'], true).'<br/>'.Format::small(Format::date($values['dob'])) : ''; }); $table->addColumn('citizenship1', __('Nationality')) ->format(function ($values) { $output = ''; if (!empty($values['citizenship1'])) { $output .= $values['citizenship1'].'<br/>'; } if (!empty($values['citizenship2'])) { $output .= $values['citizenship2'].'<br/>'; } return $output; }); $table->addColumn('transport', __('Transport')); $table->addColumn('house', __('House')); $table->addColumn('lockerNumber', __('Locker')); $table->addColumn('longTermMedication', __('Medical'))->format(function ($values) use ($medicalGateway) { $output = ''; if (!empty($values['longTermMedication'])) { if ($values['longTermMedication'] == 'Y') { $output .= '<b><i>'.__('Long Term Medication').'</i></b>: '.$values['longTermMedicationDetails'].'<br/>'; } if ($values['conditionCount'] > 0) { $conditions = $medicalGateway->selectMedicalConditionsByID($values['gibbonPersonMedicalID'])->fetchAll(); foreach ($conditions as $index => $condition) { $output .= '<b><i>'.__('Condition').' '.($index+1).'</i></b>: '.$condition['name']; $output .= ' <span style="color: #'.$condition['alertColor'].'; font-weight: bold">('.__($condition['risk']).' '.__('Risk').')</span>'; $output .= '<br/>'; } } } else { $output = '<i>'.__('No medical data').'</i>'; } return $output; }); } echo $table->render($students); }
gpl-3.0
idega/platform2
src/com/idega/servlet/filter/IWEncodingFilter.java
1837
package com.idega.servlet.filter; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.idega.presentation.IWContext; /** * * This filter should always be the first filter in the filter chain. It sets the correct encoding to the request * and response that has to be done before anything is written to the headers or gotten from the request. * @author <a href="mailto:eiki@idega.is">Eirikur S. Hrafnsson</a> */ public class IWEncodingFilter implements Filter { private static Logger log = Logger.getLogger(IWEncodingFilter.class.getName()); /* * (non-Javadoc) * * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest myRequest, ServletResponse myResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)myRequest; HttpServletResponse response = (HttpServletResponse)myResponse; //FIXME move the real methods from the constructor to this filter! IWContext iwc = new IWContext(request,response, request.getSession().getServletContext()); iwc.getParameter("just forcing the getting of parameters, remove later"); chain.doFilter(request, response); } /* (non-Javadoc) * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ public void init(FilterConfig arg0) throws ServletException { } /* (non-Javadoc) * @see javax.servlet.Filter#destroy() */ public void destroy() { } }
gpl-3.0
darkware-dev/ObjectPortal
src/test/java/org/darkware/objportal/ObjectPortalFacadeTests.java
4117
/* * Copyright (c) 2016. darkware.org and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.darkware.objportal; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; /** * @author jeff@darkware.org * @since 2016-06-16 */ public class ObjectPortalFacadeTests { protected PortalProvider provider; protected final Integer intObj = new Integer(42); protected final SimpleTestClass testObj = new SimpleTestClass(); protected final PortalContextToken defToken = new SimpleContextToken("DEFAULT"); protected final PortalContextToken newToken = new SimpleContextToken("NEW"); protected PortalContext defContext; protected PortalContext newContext; @Before public void init() { this.provider = mock(PortalProvider.class); ObjectPortal.useProvider(this.provider); this.defContext = new SimplePortalContext(); this.defContext.place(Integer.class, 42); this.newContext = new SimplePortalContext(); this.newContext.place(Integer.class, 99); when(this.provider.getDefaultToken()).thenReturn(this.defToken); when(this.provider.requestNewContext()).thenReturn(this.newToken); when(this.provider.getPortalContext()).thenReturn(this.defContext); when(this.provider.getPortalContext(this.defToken)).thenReturn(this.defContext); when(this.provider.getPortalContext(this.newToken)).thenReturn(this.newContext); } @Test public void check_classLoadable() { assertThat(new ObjectPortal()).isNotNull(); } @Test public void autoInject_default() { ObjectPortal.autoInject(this.testObj); verify(this.provider).getPortalContext(); verifyNoMoreInteractions(this.provider); } @Test public void autoInject_other() { ObjectPortal.autoInject(this.newToken, this.testObj); verify(this.provider).getPortalContext(this.newToken); verifyNoMoreInteractions(this.provider); } @Test public void newInstance_default() { SimpleTestClass instance = ObjectPortal.newInstance(SimpleTestClass.class); verify(this.provider).getPortalContext(); verifyNoMoreInteractions(this.provider); } @Test public void newInstance_other() { SimpleTestClass instance = ObjectPortal.newInstance(this.newToken, SimpleTestClass.class); verify(this.provider).getPortalContext(this.newToken); verifyNoMoreInteractions(this.provider); } @Test public void take_default() { Integer i = ObjectPortal.take(Integer.class); verify(this.provider).getPortalContext(); verifyNoMoreInteractions(this.provider); } @Test public void take_other() { Integer i = ObjectPortal.take(this.newToken, Integer.class); verify(this.provider).getPortalContext(this.newToken); verifyNoMoreInteractions(this.provider); } @Test public void place_default() { ObjectPortal.place(Integer.class, 42); verify(this.provider).getPortalContext(); verifyNoMoreInteractions(this.provider); } @Test public void place_other() { ObjectPortal.place(this.newToken, Integer.class, 42); verify(this.provider).getPortalContext(this.newToken); verifyNoMoreInteractions(this.provider); } }
gpl-3.0
Raising/Animations
14_10_28_Bloque 1/AnimationRaisingModule.js
5684
/* ARM, Animation Raising Module. @autor: Ignacio Medina Castillo, AKA Raising. */ var ARM = {version:"1"}; ARM.timeline = function (/* .... */){ var tl = new TimelineLite(); var executor = "tl"; for(var i = 0; i < arguments.length; i++){ executor= executor.concat(arguments[i]); } executor = executor.concat(";"); console.log(executor); eval(executor); } ARM.clipedImageColumToSide = function(imagePath,duration,sizeH,sizeV,columWidth,direction){// //ease:Circ.easeInOut} var divimage = $('<div>'); var image = $('<img>');// var end =(columWidth+sizeH); var doubletall = sizeV*4; var exterminate = function(){ divimage.remove(); console.log("divimage exterminted"); } ; var onloadHandler = function () { if (direction === "toLeft"){ TweenMax.to(divimage,duration, {css:{clip:'rect(-800px, 0px, '+doubletall+'px, -'+columWidth+'px)'}/*, ease:Elastic.easeOut*/, onComplete: exterminate}); } else if (direction === "toRight"){ TweenMax.to(divimage, duration, {css:{clip:"rect(-800px,"+end+"px, "+doubletall+"px,"+sizeH+"px)"}/*, ease:Elastic.easeOut*/, onComplete: exterminate }); }else{ console.log("argumento de direccion incorrecto"); } } image.css({position:"absolute", width:"sizeH", height:"sizeV", left:"0px", top:"0px", transform: "rotate(30deg)"}); divimage.css({position:"absolute", width:sizeH*2+"px", height:sizeV*2+"px", left:"0px", top:"-400px", transform: "rotate(-30deg)"}); divimage.append(image); $(document.body).append(divimage); if (direction === "toLeft"){ divimage.css('clip', "rect(-800px,"+end+"px, "+doubletall+"px,"+sizeH+"px)"); }else if (direction === "toRight"){ divimage.css('clip', 'rect(-800px, 0px, '+doubletall+'px, -'+columWidth+'px)'); }else { console.log("argumento de direccion incorrecto"); } image.load(onloadHandler); image.attr('src', imagePath); } ARM.hangingImage = function(imagePath,targetImg,duration,sizeH,sizeV,aditionalArgs){ aditionalArgs = aditionalArgs || ""; var image = $('#'+targetImg); TweenLite.set(image, {transformPerspective:800}); image.css({position:"relative", width:sizeH+"px", height:sizeV+"px", left:"100px", top:"10px", transform:"translate3d(0.5px,0,0)", transform: "rotateY(50deg)" }); //image.load(onloadHandler); image.attr('src', imagePath); return('.from($("#'+targetImg+'"),'+duration+', {rotationX:-90,autoAlpha:0, transformOrigin:"50% top",yoyo:true,repeat: 1,ease:Elastic.easeOut }'+aditionalArgs+')'); } ARM.tonelVerticalElastico = function(targetDiv,duration,sizeH,sizeV,aditionalArgs){ aditionalArgs = aditionalArgs || ""; var animatedDiv = $('#'+targetDiv); TweenLite.set(animatedDiv, {transformPerspective:800}); /*var onloadHandler = function () { TweenMax.fromTo (animatedDiv, duration, {rotationY:90, transformOrigin:"left 50% -400"},{rotationY:0, transformOrigin:"left 50% -200",ease:Elastic.easeOut }); }*/ animatedDiv.css({position:"relative", width:sizeH+"px", height:sizeV+"px", left:"100px", top:"100px" }); //onloadHandler(); return('.fromTo($("#'+targetDiv+'"),'+duration+', {rotationY:90, transformOrigin:"left 50% -400"},{rotationY:0, transformOrigin:"left 50% -200",ease:Elastic.easeOut }'+aditionalArgs+')'); } ARM.tonelVertical = function(targetDiv,duration,sizeH,sizeV,aditionalArgs){ aditionalArgs = aditionalArgs || ""; var animatedDiv = $('#'+targetDiv); TweenLite.set(animatedDiv, {transformPerspective:800}); animatedDiv.css({position:"relative", width:sizeH+"px", height:sizeV+"px", left:"100px", top:"100px" }); return('.fromTo($("#'+targetDiv+'"), '+duration+', {rotationY:90, transformOrigin:"50% 50% 0"},{rotationY:0, transformOrigin:"50% 50% -1000",ease:Sine.easeInOut}'+aditionalArgs+')'); } ARM.recursivetest = function(targetDiv,duration,sizeH,sizeV,number){ if(number==0){}else{ var animatedDiv = $('#'+targetDiv); TweenLite.set(animatedDiv, {transformPerspective:800}); /*var onloadHandler = function () { TweenMax.fromTo (animatedDiv, duration,{rotationY:90, transformOrigin:"50% 50% 0"},{rotationY:0, transformOrigin:"50% 50% -1000",ease:Sine.easeInOut}); }*/ var randomColor = Math.floor(Math.random()*16777215).toString(16); animatedDiv.css({position:"relative", width:sizeH+"px", height:sizeV+"px", left:"2%", top:"2%", backgroundColor:randomColor }); //animatedDiv.load(onloadHandler); onloadHandler(); var next = $('<div id="'+targetDiv+'a"></div>'); animatedDiv.append(next); ARM.recursivetest(targetDiv+'a',duration,sizeH*0.95,sizeV*0.95,number-1); } } ARM.tweenTonelVertical = function(targetDiv,duration,sizeH,sizeV,aditionalArgs){ aditionalArgs = aditionalArgs || ""; var animatedDiv = $('#'+targetDiv); TweenLite.set(animatedDiv, {transformPerspective:800}); animatedDiv.css({position:"relative", width:sizeH+"px", height:sizeV+"px", left:"100px", top:"100px" }); return(TweenMax.fromTo(animatedDiv, duration, {rotationY:90, transformOrigin:"50% 50% 0"},{rotationY:0, transformOrigin:"50% 50% -1000",ease:Sine.easeInOut})); } ARM.tweenHangingImage = function(imagePath,targetImg,duration,sizeH,sizeV,aditionalArgs){ aditionalArgs = aditionalArgs || ""; var image = $('#'+targetImg); TweenLite.set(image, {transformPerspective:800}); image.css({position:"relative", width:sizeH+"px", height:sizeV+"px", left:"100px", top:"10px", transform: "rotate(50deg)" }); //image.load(onloadHandler); image.attr('src', imagePath); return(TweenMax.from(image,duration, {rotationX:-90,autoAlpha:0, transformOrigin:"50% top",yoyo:true,repeat: 1,ease:Elastic.easeOut })); }
gpl-3.0
mikelmaron/OpenMapKit
app/src/main/java/org/redcross/openmapkit/odkcollect/ODKCollectTagActivity.java
5880
package org.redcross.openmapkit.odkcollect; import android.app.Activity; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.GridLayout; import android.widget.TextView; import com.spatialdev.osm.model.OSMElement; import org.redcross.openmapkit.R; import org.redcross.openmapkit.odkcollect.tag.ODKTag; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class ODKCollectTagActivity extends ActionBarActivity { private PlaceholderFragment fragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_odkcollect_tag); if (savedInstanceState == null) { fragment = new PlaceholderFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.container, fragment) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_odkcollect_tag, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // save to odk collect action bar button if (id == R.id.action_save_to_odk_collect) { saveToOdkCollect(); } //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } void saveToOdkCollect() { OSMElement osmElement = fragment.updateTagsInOSMElement(); String osmXmlFileFullPath = ODKCollectHandler.saveXmlInODKCollect(osmElement); Intent resultIntent = new Intent(); resultIntent.putExtra("OSM_PATH", osmXmlFileFullPath); setResult(Activity.RESULT_OK, resultIntent); finish(); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * MODEL FIELDS * * * */ private OSMElement osmElement; private Collection<ODKTag> requiredTags; private Map<String, String> tags; /** * UI FIELDS * * * */ private View rootView; private GridLayout gridLayout; /** * TAG KEY TO TEXT EDIT HASH, * USED TO GET EDITED VALUES * * * * */ private Map<String, TextView> tagEditTextHash; public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_odkcollect_tag, container, false); gridLayout = (GridLayout) rootView.findViewById(R.id.odkCollectTagGridLayout); setupModel(); insertRequiredOSMTags(); return rootView; } private void setupModel() { osmElement = OSMElement.getSelectedElements().getFirst(); tags = osmElement.getTags(); tagEditTextHash = new HashMap<>(); } private void insertRequiredOSMTags() { requiredTags = ODKCollectHandler.getODKCollectData().getRequiredTags(); int row = 1; // The first row in the GridView is the instructions. for (ODKTag reqTag : requiredTags) { String initialTagVal = tags.get(reqTag.getKey()); insertTagKeyAndValueForRow(row++, reqTag, initialTagVal); } } private void insertTagKeyAndValueForRow(int row, ODKTag reqTag, String initialTagVal) { Activity activity = getActivity(); TextView keyTextView = reqTag.createTagKeyTextView(activity); GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.rowSpec = GridLayout.spec(row); params.columnSpec = GridLayout.spec(0); keyTextView.setLayoutParams(params); gridLayout.addView(keyTextView); TextView tagValueTextView = reqTag.createTagValueTextView(activity, initialTagVal); GridLayout.LayoutParams params2 = new GridLayout.LayoutParams(); params2.rowSpec = GridLayout.spec(row); params2.columnSpec = GridLayout.spec(1); params2.width = GridLayout.LayoutParams.MATCH_PARENT; tagValueTextView.setLayoutParams(params2); gridLayout.addView(tagValueTextView); tagEditTextHash.put(reqTag.getKey(), tagValueTextView); } /** * Updates the tags in the OSMElement according to the values in the * EditText UI * * * * * @return OSMElement with edited tags */ public OSMElement updateTagsInOSMElement() { Set<String> keySet = tagEditTextHash.keySet(); for( String key : keySet) { TextView et = tagEditTextHash.get(key); String val = et.getText().toString(); osmElement.addOrEditTag(key, val); } return osmElement; } } }
gpl-3.0
coding-books/website
migrations/m170530_185658_add_format_column_to_books_lins_table.php
665
<?php use yii\db\Migration; /** * Handles adding format to table `books_lins`. */ class m170530_185658_add_format_column_to_books_lins_table extends Migration { /** * @inheritdoc */ public function up() { $this->dropColumn('books', 'download_link'); $this->addColumn('books_links', 'format', $this->string(11)->notNull()); $this->createIndex('book_link', 'books_links', ['format', 'language_code', 'book_id']); } /** * @inheritdoc */ public function down() { $this->dropColumn('books_links', 'format'); $this->addColumn('books', 'download_link', $this->text()); } }
gpl-3.0
tsiakmaki/jcropeditor
src/edu/teilar/jcropeditor/swing/action/AddKObjectAction.java
2769
/* * (C) Copyright 2010-2013 Maria Tsiakmaki. * * This file is part of jcropeditor. * * jcropeditor is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) * as published by the Free Software Foundation, version 3. * * jcropeditor 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 jcropeditor. If not, see <http://www.gnu.org/licenses/>. */ package edu.teilar.jcropeditor.swing.action; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import com.mxgraph.util.mxEventObject; import edu.teilar.jcropeditor.Core; import edu.teilar.jcropeditor.util.KObject; import edu.teilar.jcropeditor.util.mxCropEvent; /** * * * * @version 0.1 2010 * @author Maria Tsiakmaki */ public class AddKObjectAction extends AbstractAction { /** * */ private static final long serialVersionUID = -1324490478635977433L; private String krcNodeLabel; private String kObjectLabel; private Core core; public AddKObjectAction(String krcNodeLabel, String kObjectLabel, Core core) { super(kObjectLabel); this.krcNodeLabel = krcNodeLabel; this.kObjectLabel = kObjectLabel; this.core = core; } @Override public void actionPerformed(ActionEvent e) { KObject kobjParent = core.getActiveKObject(); KObject kobjChild = core.getCropProject().getKObjectByName(kObjectLabel); // fire event to trigger core.getKrcGraphComponent().getGraph().fireEvent( new mxEventObject(mxCropEvent.KRC_LEARNING_OBJ_ADDED, "synchronizer", core.getOntologySynchronizer(), "krcNodeLabel", krcNodeLabel, "kObject", kobjChild, "activekObjectName", kobjParent.getName())); core.getExecutionGraphComponent().getGraph().fireEvent( new mxEventObject(mxCropEvent.KRC_LEARNING_OBJ_ADDED, "xNodeLabel", krcNodeLabel, "kObject", kobjChild, "synchronizer", core.getOntologySynchronizer(), "activekObjectName", kobjParent.getName())); // update the krc node properties core.updatePropertiesPanels(krcNodeLabel); // Recalculate prerequisites core.getKrcGraphComponent().getGraph().fireEvent( new mxEventObject(mxCropEvent.SYNC_PREREQUISITES, "synchronizer", core.getOntologySynchronizer(), "kobject", kobjParent, "problemspane", core.getProblemsPane())); // check for problems in the prerequisites core.getProblemsPane().recalculatePrerequisitesProblems(kobjParent); } }
gpl-3.0
huzheng001/stardict-3
tools/src/edict.cpp
5628
/* * This file is part of StarDict. * * StarDict 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. * * StarDict 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 StarDict. If not, see <http://www.gnu.org/licenses/>. */ #include "stdio.h" #include "stdlib.h" #include <locale.h> #include <string.h> #include <sys/stat.h> #include <glib.h> struct _worditem { gchar *word; gchar *pinyin; gchar *definition; }; gint stardict_strcmp(const gchar *s1, const gchar *s2) { gint a; a = g_ascii_strcasecmp(s1, s2); if (a == 0) return strcmp(s1, s2); else return a; } gint comparefunc(gconstpointer a,gconstpointer b) { return stardict_strcmp(((struct _worditem *)a)->word,((struct _worditem *)b)->word); } void to_definition(gchar *str) { while (*str) { if (*str=='/') *str='\n'; str++; } } void convert(char *filename) { struct stat stats; if (stat (filename, &stats) == -1) { printf("file not exist!\n"); return; } gchar *basefilename = g_path_get_basename(filename); FILE *tabfile; tabfile = fopen(filename,"r"); gchar *buffer = (gchar *)g_malloc (stats.st_size + 1); size_t fread_size; fread_size = fread (buffer, 1, stats.st_size, tabfile); if (fread_size != (size_t)stats.st_size) { g_print("fread error!\n"); } fclose (tabfile); buffer[stats.st_size] = '\0'; GArray *array = g_array_sized_new(FALSE,FALSE, sizeof(struct _worditem),20000); gchar *p, *p1, *p2, *p3; p = buffer; if ((guchar)*p==0xEF && (guchar)*(p+1)==0xBB && (guchar)*(p+2)==0xBF) // UTF-8 order characters. p+=3; struct _worditem worditem; glong linenum=1; while (1) { if (*p == '\0') { g_print("over\n"); break; } p1 = strchr(p,'\n'); if (!p1) { g_print("error, no end line\n"); return; } *p1 = '\0'; p1++; p2 = strchr(p,'['); if (!p2) { p2 = strchr(p, '/'); if (!p2) { g_print("error, no /, %ld\n", linenum); return; } *p2 = '\0'; p3 = p2+1; } else { *p2 = '\0'; p2++; p3 = strchr(p2, ']'); if (!p3) { g_print("error, no ], %ld\n", linenum); return; } *p3 = '\0'; p3++; } worditem.word = p; worditem.pinyin = p2; to_definition(p3); worditem.definition = p3; g_strstrip(worditem.word); g_strstrip(worditem.pinyin); g_strstrip(worditem.definition); if (!worditem.word[0]) { g_print("%s-%ld, bad word!!!\n", basefilename, linenum); p= p1; linenum++; continue; } if (!worditem.pinyin[0]) { //g_print("%s-%ld, bad pinyin!!!\n", basefilename, linenum); } if (!worditem.definition[0]) { g_print("%s-%ld, bad definition!!!\n", basefilename, linenum); } g_array_append_val(array, worditem); p= p1; linenum++; } g_array_sort(array,comparefunc); gchar idxfilename[256]; gchar dicfilename[256]; sprintf(idxfilename, "%s.idx", basefilename); sprintf(dicfilename, "%s.dict", basefilename); FILE *idxfile = fopen(idxfilename,"w"); FILE *dicfile = fopen(dicfilename,"w"); glong wordcount = array->len; long offset_old; glong tmpglong; const gchar *previous_word = ""; struct _worditem *pworditem; gulong i=0; glong thedatasize; const gchar *insert_word = "\n\n"; gboolean flag; pworditem = &g_array_index(array, struct _worditem, i); gint pinyin_len, definition_len; gboolean firsttime; while (i<array->len) { thedatasize = 0; offset_old = ftell(dicfile); flag = true; firsttime = TRUE; while (flag == true) { pinyin_len = strlen(pworditem->pinyin); if (firsttime) { fwrite(pworditem->pinyin, 1 , pinyin_len+1,dicfile); } else { fwrite(pworditem->pinyin, 1 , pinyin_len,dicfile); fwrite("\n", 1, 1, dicfile); } definition_len = strlen(pworditem->definition); fwrite(pworditem->definition, 1 ,definition_len,dicfile); thedatasize += pinyin_len+1+definition_len; previous_word = pworditem->word; i++; if (i<array->len) { pworditem = &g_array_index(array, struct _worditem, i); if (strcmp(previous_word,pworditem->word)==0) { //g_print("D! %s\n",previous_word); flag = true; firsttime=FALSE; wordcount--; fwrite(insert_word,sizeof(gchar),strlen(insert_word),dicfile); thedatasize += strlen(insert_word); } else { flag = false; } } else { flag = false; } } fwrite(previous_word,sizeof(gchar),strlen(previous_word)+1,idxfile); tmpglong = g_htonl(offset_old); fwrite(&(tmpglong),sizeof(glong),1,idxfile); tmpglong = g_htonl(thedatasize); fwrite(&(tmpglong),sizeof(glong),1,idxfile); } g_print("%s wordcount: %ld\n", basefilename, wordcount); g_free(buffer); g_array_free(array,TRUE); fclose(idxfile); fclose(dicfile); gchar command[256]; sprintf(command, "dictzip %s.dict", basefilename); int result; result = system(command); if (result == -1) { g_print("system() error!\n"); } g_free(basefilename); } int main(int argc,char * argv []) { if (argc<2) { printf("please type this:\n./edict edict.utf\n"); return FALSE; } setlocale(LC_ALL, ""); for (int i=1; i< argc; i++) convert (argv[i]); return FALSE; }
gpl-3.0
maruen/yowsup.jlguardi
yowsup/demos/receiveclient/run.py
2185
from layer import EchoLayer from yowsup.layers.auth import YowCryptLayer, YowAuthenticationProtocolLayer, AuthError from yowsup.layers.protocol_messages import YowMessagesProtocolLayer from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer from yowsup.layers.protocol_acks import YowAckProtocolLayer from yowsup.layers.protocol_presence import YowPresenceProtocolLayer from yowsup.layers.network import YowNetworkLayer from yowsup.layers.axolotl import YowAxolotlLayer from yowsup.layers.coder import YowCoderLayer from yowsup.common import YowConstants from yowsup.layers import YowLayerEvent from yowsup.stacks import YowStack, YOWSUP_CORE_LAYERS from yowsup import env import sys def receive_message(credentials): layers = ( EchoLayer, (YowAuthenticationProtocolLayer, YowMessagesProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer, YowPresenceProtocolLayer), YowAxolotlLayer ) + YOWSUP_CORE_LAYERS stack = YowStack(layers) # Setting credentials stack.setProp(YowAuthenticationProtocolLayer.PROP_CREDENTIALS, credentials) # WhatsApp server address stack.setProp(YowNetworkLayer.PROP_ENDPOINT, YowConstants.ENDPOINTS[0]) stack.setProp(YowCoderLayer.PROP_DOMAIN, YowConstants.DOMAIN) stack.setProp(YowCoderLayer.PROP_RESOURCE, env.CURRENT_ENV.getResource()) stack.setProp(EchoLayer.PROP_CREDENTIALS, credentials) # Sending connecting signal stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) try: # Program main loop stack.loop() except AuthError as e: print('Authentication error %s' % e.message) sys.exit(1) if __name__ == '__main__': if len(sys.argv) == 1: print('%s send number message\nrecv\n' % sys.argv[0]) sys.exit(1) if sys.argv[1] == 'send': try: send_message(sys.argv[2],sys.argv[3]) except KeyboardInterrupt: print('closing') sys.exit(0) if sys.argv[1] == 'recv': try: receive_message() except KeyboardInterrupt: print('closing') sys.exit(0)
gpl-3.0
ngot/nightly-test
fibjs/src/db/mongo/MongoCursor.cpp
6670
/* * MongoCursor.cpp * * Created on: Oct 31, 2012 * Author: lion */ #include "object.h" #include "MongoCursor.h" #include "encoding_bson.h" #include "ifs/util.h" #include "Fiber.h" namespace fibjs { result_t MongoCursor::_initCursor(MongoDB* db, AsyncEvent* ac) { if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); m_cursor = new cursor; m_cursor->m_db = db; mongo_cursor_init(m_cursor, (m_cursor->m_db)->m_conn, m_ns.c_str()); mongo_cursor_set_query(m_cursor, &m_bbq); mongo_cursor_set_fields(m_cursor, &m_bbp); return 0; } result_t MongoCursor::_nextCursor(int32_t& retVal, AsyncEvent* ac) { if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); retVal = mongo_cursor_next(m_cursor); return 0; } MongoCursor::MongoCursor(MongoDB* db, const exlib::string& ns, const exlib::string& name, v8::Local<v8::Object> query, v8::Local<v8::Object> projection) { Isolate* isolate = holder(); m_state = CUR_NONE; m_ns = ns; m_name = name; v8::Local<v8::Value> _query; util_base::clone(query, _query); m_query.Reset(isolate->m_isolate, v8::Local<v8::Object>::Cast(_query)->Clone()); encodeObject(isolate, &m_bbp, projection); ac__initCursor(db); m_bInit = false; m_bSpecial = false; } static result_t _close(MongoCursor::cursor* cur) { mongo_cursor_destroy(cur); delete cur; return 0; } MongoCursor::~MongoCursor() { m_query.Reset(); asyncCall(_close, m_cursor); if (m_bInit) bson_destroy(&m_bbq); bson_destroy(&m_bbp); } void MongoCursor::ensureSpecial() { if (!m_bSpecial) { Isolate* isolate = holder(); v8::Local<v8::Object> o = v8::Object::New(isolate->m_isolate); o->Set(isolate->NewFromUtf8("query"), v8::Local<v8::Object>::New(isolate->m_isolate, m_query)); m_query.Reset(); m_query.Reset(isolate->m_isolate, o); m_bSpecial = true; } } result_t MongoCursor::hint(v8::Local<v8::Object> opts, obj_ptr<MongoCursor_base>& retVal) { return _addSpecial("$hint", opts, retVal); } result_t MongoCursor::limit(int32_t size, obj_ptr<MongoCursor_base>& retVal, AsyncEvent* ac) { if (m_bInit) return CHECK_ERROR(CALL_E_INVALID_CALL); if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); mongo_cursor_set_limit(m_cursor, size); retVal = this; return 0; } result_t MongoCursor::count(bool applySkipLimit, int32_t& retVal) { bson bbq; bson_init(&bbq); bson_append_string(&bbq, "count", m_name.c_str()); Isolate* isolate = holder(); if (m_bSpecial) encodeValue(isolate, &bbq, "query", v8::Local<v8::Object>::New(isolate->m_isolate, m_query)->Get(isolate->NewFromUtf8("query"))); else encodeValue(isolate, &bbq, "query", v8::Local<v8::Object>::New(isolate->m_isolate, m_query)); if (applySkipLimit) { if (m_cursor->limit) bson_append_int(&bbq, "limit", m_cursor->limit); if (m_cursor->skip) bson_append_int(&bbq, "skip", m_cursor->skip); } bson_finish(&bbq); v8::Local<v8::Object> res; result_t hr = m_cursor->m_db->bsonHandler(&bbq, res); if (hr < 0) return hr; retVal = res->Get(isolate->NewFromUtf8("n"))->Int32Value(); return 0; } result_t MongoCursor::forEach(v8::Local<v8::Function> func) { result_t hr; v8::Local<v8::Object> o; Isolate* isolate = holder(); while ((hr = next(o)) != CALL_RETURN_NULL) { v8::Local<v8::Value> a = o; v8::Local<v8::Value> v = func->Call(v8::Undefined(isolate->m_isolate), 1, &a); if (v.IsEmpty()) return CALL_E_JAVASCRIPT; } return hr < 0 ? hr : 0; } result_t MongoCursor::map(v8::Local<v8::Function> func, v8::Local<v8::Array>& retVal) { result_t hr; Isolate* isolate = holder(); v8::Local<v8::Object> o; v8::Local<v8::Array> as = v8::Array::New(isolate->m_isolate); int32_t n = 0; while ((hr = next(o)) != CALL_RETURN_NULL) { v8::Local<v8::Value> a = o; v8::Local<v8::Value> v = func->Call(v8::Undefined(isolate->m_isolate), 1, &a); if (v.IsEmpty()) return CALL_E_JAVASCRIPT; as->Set(n, v); n++; } retVal = as; return hr < 0 ? hr : 0; } result_t MongoCursor::hasNext(bool& retVal) { if (!m_bInit) { result_t hr; Isolate* isolate = holder(); hr = encodeObject(isolate, &m_bbq, v8::Local<v8::Object>::New(isolate->m_isolate, m_query)); if (hr < 0) return hr; m_bInit = true; } if (m_state == CUR_NONE) { int32_t res; ac__nextCursor(res); m_state = (res == MONGO_OK) ? CUR_DATA : CUR_NODATA; } retVal = m_state == CUR_DATA; return CHECK_ERROR(m_cursor->m_db->error()); } result_t MongoCursor::next(v8::Local<v8::Object>& retVal) { bool has; result_t hr = hasNext(has); if (hr < 0) return hr; if (!has) return CALL_RETURN_NULL; retVal = decodeObject(holder(), mongo_cursor_bson(m_cursor)); m_state = CUR_NONE; return 0; } result_t MongoCursor::size(int32_t& retVal) { return count(true, retVal); } result_t MongoCursor::skip(int32_t num, obj_ptr<MongoCursor_base>& retVal, AsyncEvent* ac) { if (m_bInit) return CHECK_ERROR(CALL_E_INVALID_CALL); if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); mongo_cursor_set_skip(m_cursor, num); retVal = this; return 0; } result_t MongoCursor::sort(v8::Local<v8::Object> opts, obj_ptr<MongoCursor_base>& retVal) { return _addSpecial("orderby", opts, retVal); } result_t MongoCursor::_addSpecial(const char* name, v8::Local<v8::Value> opts, obj_ptr<MongoCursor_base>& retVal) { if (m_bInit) return CHECK_ERROR(CALL_E_INVALID_CALL); ensureSpecial(); Isolate* isolate = holder(); v8::Local<v8::Object>::New(isolate->m_isolate, m_query)->Set(isolate->NewFromUtf8(name), opts); retVal = this; return 0; } result_t MongoCursor::toArray(v8::Local<v8::Array>& retVal) { result_t hr; v8::Local<v8::Object> o; v8::Local<v8::Array> as = v8::Array::New(holder()->m_isolate); int32_t n = 0; while ((hr = next(o)) != CALL_RETURN_NULL) { as->Set(n, o); n++; } if (hr < 0) return hr; retVal = as; return 0; } result_t MongoCursor::toJSON(exlib::string key, v8::Local<v8::Value>& retVal) { result_t hr; v8::Local<v8::Array> as; hr = toArray(as); if (hr < 0) return hr; retVal = as; return 0; } } /* namespace fibjs */
gpl-3.0
smattis/BET-1
test/test_postProcess/test_plotP.py
8894
# Copyright (C) 2014-2019 The BET Development Team """ This module contains tests for :module:`bet.postProcess.plotP`. Tests for correct computation of marginals and plotting. """ import unittest import bet.calculateP.calculateP as calcP import bet.calculateP.simpleFunP as simpleFunP import bet.postProcess.plotP as plotP import numpy as np import scipy.spatial as spatial import numpy.testing as nptest import bet.util as util from bet.Comm import comm import os import bet.sample as sample class Test_calc_marg_1D(unittest.TestCase): """ Test :meth:`bet.postProcess.plotP.calculate_1D_marginal_probs` for a 1D parameter space. """ def setUp(self): """ Set up problem. """ emulated_input_samples = sample.sample_set(1) emulated_input_samples.set_domain(np.array([[0.0, 1.0]])) num_samples = 1000 emulated_input_samples.set_values_local( np.linspace(emulated_input_samples.get_domain()[0][0], emulated_input_samples.get_domain()[0][1], num_samples + 1)) emulated_input_samples.set_probabilities_local( 1.0 / float(comm.size) * (1.0 / float( emulated_input_samples.get_values_local().shape[0])) * np.ones((emulated_input_samples.get_values_local().shape[0],))) emulated_input_samples.check_num() self.samples = emulated_input_samples def test_1_bin(self): """ Test that marginals sum to 1 and have correct shape. """ (bins, marginals) = plotP.calculate_1D_marginal_probs(self.samples, nbins=1) nptest.assert_almost_equal(marginals[0][0], 1.0) nptest.assert_equal(marginals[0].shape, (1,)) def test_10_bins(self): """ Test that marginals sum to 1 and have correct shape. """ (bins, marginals) = plotP.calculate_1D_marginal_probs(self.samples, nbins=10) nptest.assert_almost_equal(np.sum(marginals[0]), 1.0) nptest.assert_equal(marginals[0].shape, (10,)) class Test_calc_marg_2D(unittest.TestCase): """ Test :meth:`bet.postProcess.plotP.calculate_1D_marginal_probs` and :meth:`bet.postProcess.plotP.calculate_2D_marginal_probs` for a 2D parameter space. """ def setUp(self): """ Set up problem. """ emulated_input_samples = sample.sample_set(2) emulated_input_samples.set_domain(np.array([[0.0, 1.0], [0.0, 1.0]])) emulated_input_samples.set_values_local( util.meshgrid_ndim((np.linspace( emulated_input_samples.get_domain()[0][0], emulated_input_samples.get_domain()[0][1], 10), np.linspace( emulated_input_samples.get_domain()[1][0], emulated_input_samples.get_domain()[1][1], 10) )) ) emulated_input_samples.set_probabilities_local(1.0 / float(comm.size) * ( 1.0 / float( emulated_input_samples.get_values_local().shape[0]) ) * np.ones( (emulated_input_samples.get_values_local().shape[0],) ) ) emulated_input_samples.check_num() self.samples = emulated_input_samples def test_1_bin_1D(self): """ Test that 1D marginals sum to 1 and have right shape. """ (bins, marginals) = plotP.calculate_1D_marginal_probs(self.samples, nbins=1) nptest.assert_almost_equal(marginals[0][0], 1.0) nptest.assert_almost_equal(marginals[1][0], 1.0) nptest.assert_equal(marginals[0].shape, (1,)) nptest.assert_equal(marginals[1].shape, (1,)) def test_10_bins_1D(self): """ Test that 1D marginals sum to 1 and have right shape. """ (bins, marginals) = plotP.calculate_1D_marginal_probs(self.samples, nbins=10) nptest.assert_almost_equal(np.sum(marginals[0]), 1.0) nptest.assert_almost_equal(np.sum(marginals[1]), 1.0) nptest.assert_equal(marginals[0].shape, (10,)) def test_1_bin_2D(self): """ Test that 2D marginals sum to 1 and have right shape. """ (bins, marginals) = plotP.calculate_2D_marginal_probs(self.samples, nbins=1) nptest.assert_almost_equal(marginals[(0, 1)][0], 1.0) nptest.assert_equal(marginals[(0, 1)].shape, (1, 1)) def test_10_bins_2D(self): """ Test that 2D marginals sum to 1 and have right shape. """ (bins, marginals) = plotP.calculate_2D_marginal_probs(self.samples, nbins=10) nptest.assert_almost_equal(np.sum(marginals[(0, 1)]), 1.0) nptest.assert_equal(marginals[(0, 1)].shape, (10, 10)) def test_5_10_bins_2D(self): """ Test that 1D marginals sum to 1 and have right shape. """ (bins, marginals) = plotP.calculate_2D_marginal_probs(self.samples, nbins=[5, 10]) nptest.assert_almost_equal(np.sum(marginals[(0, 1)]), 1.0) nptest.assert_equal(marginals[(0, 1)].shape, (5, 10)) def test_1D_smoothing(self): """ Test :meth:`bet.postProcess.plotP.smooth_marginals_1D`. """ (bins, marginals) = plotP.calculate_1D_marginal_probs(self.samples, nbins=10) marginals_smooth = plotP.smooth_marginals_1D(marginals, bins, sigma=10.0) nptest.assert_equal(marginals_smooth[0].shape, marginals[0].shape) nptest.assert_almost_equal(np.sum(marginals_smooth[0]), 1.0) def test_2D_smoothing(self): """ Test :meth:`bet.postProcess.plotP.smooth_marginals_2D`. """ (bins, marginals) = plotP.calculate_2D_marginal_probs(self.samples, nbins=10) marginals_smooth = plotP.smooth_marginals_2D(marginals, bins, sigma=10.0) nptest.assert_equal(marginals_smooth[(0, 1)].shape, marginals[(0, 1)].shape) nptest.assert_almost_equal(np.sum(marginals_smooth[(0, 1)]), 1.0) def test_plot_marginals_1D(self): """ Test :meth:`bet.postProcess.plotP.plot_1D_marginal_probs`. """ (bins, marginals) = plotP.calculate_1D_marginal_probs(self.samples, nbins=10) try: plotP.plot_1D_marginal_probs(marginals, bins, self.samples, filename="file", interactive=False) go = True except (RuntimeError, TypeError, NameError): go = False nptest.assert_equal(go, True) def test_plot_marginals_2D(self): """ Test :meth:`bet.postProcess.plotP.plot_2D_marginal_probs`. """ (bins, marginals) = plotP.calculate_2D_marginal_probs(self.samples, nbins=10) marginals[(0, 1)][0][0] = 0.0 marginals[(0, 1)][0][1] *= 2.0 try: plotP.plot_2D_marginal_probs(marginals, bins, self.samples, filename="file", interactive=False) go = True if os.path.exists("file_2D_0_1.png") and comm.rank == 0: os.remove("file_2D_0_1.png") except (RuntimeError, TypeError, NameError): go = False nptest.assert_equal(go, True) def test_plot_2D_marginal_contours(self): """ Test :meth:`bet.postProcess.plotP.plot_2D_marginal_contours`. """ (bins, marginals) = plotP.calculate_2D_marginal_probs(self.samples, nbins=10) marginals[(0, 1)][0][0] = 0.0 marginals[(0, 1)][0][1] *= 2.0 try: plotP.plot_2D_marginal_probs(marginals, bins, self.samples, filename="file", interactive=False) go = True if os.path.exists("file_2D_contours_0_1.png") and comm.rank == 0: os.remove("file_2D_contours_0_1.png") except (RuntimeError, TypeError, NameError): go = False nptest.assert_equal(go, True)
gpl-3.0
paulwilde/woocommerce
includes/admin/class-wc-admin-assets.php
25674
<?php /** * Load assets * * @author WooThemes * @category Admin * @package WooCommerce/Admin * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) { exit; } if ( ! class_exists( 'WC_Admin_Assets', false ) ) : /** * WC_Admin_Assets Class. */ class WC_Admin_Assets { /** * Hook in tabs. */ public function __construct() { add_action( 'admin_enqueue_scripts', array( $this, 'admin_styles' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) ); add_action( 'admin_head', array( $this, 'product_taxonomy_styles' ) ); } /** * Enqueue styles. */ public function admin_styles() { global $wp_scripts; $screen = get_current_screen(); $screen_id = $screen ? $screen->id : ''; $jquery_version = isset( $wp_scripts->registered['jquery-ui-core']->ver ) ? $wp_scripts->registered['jquery-ui-core']->ver : '1.11.4'; // Register admin styles wp_register_style( 'woocommerce_admin_menu_styles', WC()->plugin_url() . '/assets/css/menu.css', array(), WC_VERSION ); wp_register_style( 'woocommerce_admin_styles', WC()->plugin_url() . '/assets/css/admin.css', array(), WC_VERSION ); wp_register_style( 'jquery-ui-style', '//code.jquery.com/ui/' . $jquery_version . '/themes/smoothness/jquery-ui.min.css', array(), $jquery_version ); wp_register_style( 'woocommerce_admin_dashboard_styles', WC()->plugin_url() . '/assets/css/dashboard.css', array(), WC_VERSION ); wp_register_style( 'woocommerce_admin_print_reports_styles', WC()->plugin_url() . '/assets/css/reports-print.css', array(), WC_VERSION, 'print' ); // Add RTL support for admin styles wp_style_add_data( 'woocommerce_admin_menu_styles', 'rtl', 'replace' ); wp_style_add_data( 'woocommerce_admin_styles', 'rtl', 'replace' ); wp_style_add_data( 'woocommerce_admin_dashboard_styles', 'rtl', 'replace' ); wp_style_add_data( 'woocommerce_admin_print_reports_styles', 'rtl', 'replace' ); // Sitewide menu CSS wp_enqueue_style( 'woocommerce_admin_menu_styles' ); // Admin styles for WC pages only if ( in_array( $screen_id, wc_get_screen_ids() ) ) { wp_enqueue_style( 'woocommerce_admin_styles' ); wp_enqueue_style( 'jquery-ui-style' ); wp_enqueue_style( 'wp-color-picker' ); } if ( in_array( $screen_id, array( 'dashboard' ) ) ) { wp_enqueue_style( 'woocommerce_admin_dashboard_styles' ); } if ( in_array( $screen_id, array( 'woocommerce_page_wc-reports', 'toplevel_page_wc-reports' ) ) ) { wp_enqueue_style( 'woocommerce_admin_print_reports_styles' ); } /** * @deprecated 2.3 */ if ( has_action( 'woocommerce_admin_css' ) ) { do_action( 'woocommerce_admin_css' ); wc_deprecated_function( 'The woocommerce_admin_css action', '2.3', 'admin_enqueue_scripts' ); } } /** * Enqueue scripts. */ public function admin_scripts() { global $wp_query, $post; $screen = get_current_screen(); $screen_id = $screen ? $screen->id : ''; $wc_screen_id = sanitize_title( __( 'WooCommerce', 'woocommerce' ) ); $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; // Register scripts wp_register_script( 'woocommerce_admin', WC()->plugin_url() . '/assets/js/admin/woocommerce_admin' . $suffix . '.js', array( 'jquery', 'jquery-blockui', 'jquery-ui-sortable', 'jquery-ui-widget', 'jquery-ui-core', 'jquery-tiptip' ), WC_VERSION ); wp_register_script( 'jquery-blockui', WC()->plugin_url() . '/assets/js/jquery-blockui/jquery.blockUI' . $suffix . '.js', array( 'jquery' ), '2.70', true ); wp_register_script( 'jquery-tiptip', WC()->plugin_url() . '/assets/js/jquery-tiptip/jquery.tipTip' . $suffix . '.js', array( 'jquery' ), WC_VERSION, true ); wp_register_script( 'accounting', WC()->plugin_url() . '/assets/js/accounting/accounting' . $suffix . '.js', array( 'jquery' ), '0.4.2' ); wp_register_script( 'round', WC()->plugin_url() . '/assets/js/round/round' . $suffix . '.js', array( 'jquery' ), WC_VERSION ); wp_register_script( 'wc-admin-meta-boxes', WC()->plugin_url() . '/assets/js/admin/meta-boxes' . $suffix . '.js', array( 'jquery', 'jquery-ui-datepicker', 'jquery-ui-sortable', 'accounting', 'round', 'wc-enhanced-select', 'plupload-all', 'stupidtable', 'jquery-tiptip' ), WC_VERSION ); wp_register_script( 'zeroclipboard', WC()->plugin_url() . '/assets/js/zeroclipboard/jquery.zeroclipboard' . $suffix . '.js', array( 'jquery' ), WC_VERSION ); wp_register_script( 'qrcode', WC()->plugin_url() . '/assets/js/jquery-qrcode/jquery.qrcode' . $suffix . '.js', array( 'jquery' ), WC_VERSION ); wp_register_script( 'stupidtable', WC()->plugin_url() . '/assets/js/stupidtable/stupidtable' . $suffix . '.js', array( 'jquery' ), WC_VERSION ); wp_register_script( 'serializejson', WC()->plugin_url() . '/assets/js/jquery-serializejson/jquery.serializejson' . $suffix . '.js', array( 'jquery' ), '2.6.1' ); wp_register_script( 'flot', WC()->plugin_url() . '/assets/js/jquery-flot/jquery.flot' . $suffix . '.js', array( 'jquery' ), WC_VERSION ); wp_register_script( 'flot-resize', WC()->plugin_url() . '/assets/js/jquery-flot/jquery.flot.resize' . $suffix . '.js', array( 'jquery', 'flot' ), WC_VERSION ); wp_register_script( 'flot-time', WC()->plugin_url() . '/assets/js/jquery-flot/jquery.flot.time' . $suffix . '.js', array( 'jquery', 'flot' ), WC_VERSION ); wp_register_script( 'flot-pie', WC()->plugin_url() . '/assets/js/jquery-flot/jquery.flot.pie' . $suffix . '.js', array( 'jquery', 'flot' ), WC_VERSION ); wp_register_script( 'flot-stack', WC()->plugin_url() . '/assets/js/jquery-flot/jquery.flot.stack' . $suffix . '.js', array( 'jquery', 'flot' ), WC_VERSION ); wp_register_script( 'wc-settings-tax', WC()->plugin_url() . '/assets/js/admin/settings-views-html-settings-tax' . $suffix . '.js', array( 'jquery', 'wp-util', 'underscore', 'backbone', 'jquery-blockui' ), WC_VERSION ); wp_register_script( 'wc-backbone-modal', WC()->plugin_url() . '/assets/js/admin/backbone-modal' . $suffix . '.js', array( 'underscore', 'backbone', 'wp-util' ), WC_VERSION ); wp_register_script( 'wc-shipping-zones', WC()->plugin_url() . '/assets/js/admin/wc-shipping-zones' . $suffix . '.js', array( 'jquery', 'wp-util', 'underscore', 'backbone', 'jquery-ui-sortable', 'wc-enhanced-select', 'wc-backbone-modal' ), WC_VERSION ); wp_register_script( 'wc-shipping-zone-methods', WC()->plugin_url() . '/assets/js/admin/wc-shipping-zone-methods' . $suffix . '.js', array( 'jquery', 'wp-util', 'underscore', 'backbone', 'jquery-ui-sortable', 'wc-backbone-modal' ), WC_VERSION ); wp_register_script( 'wc-shipping-classes', WC()->plugin_url() . '/assets/js/admin/wc-shipping-classes' . $suffix . '.js', array( 'jquery', 'wp-util', 'underscore', 'backbone' ), WC_VERSION ); wp_register_script( 'select2', WC()->plugin_url() . '/assets/js/select2/select2.full' . $suffix . '.js', array( 'jquery' ), '4.0.3' ); wp_register_script( 'wc-enhanced-select', WC()->plugin_url() . '/assets/js/admin/wc-enhanced-select' . $suffix . '.js', array( 'jquery', 'select2' ), WC_VERSION ); wp_localize_script( 'wc-enhanced-select', 'wc_enhanced_select_params', array( 'i18n_no_matches' => _x( 'No matches found', 'enhanced select', 'woocommerce' ), 'i18n_ajax_error' => _x( 'Loading failed', 'enhanced select', 'woocommerce' ), 'i18n_input_too_short_1' => _x( 'Please enter 1 or more characters', 'enhanced select', 'woocommerce' ), 'i18n_input_too_short_n' => _x( 'Please enter %qty% or more characters', 'enhanced select', 'woocommerce' ), 'i18n_input_too_long_1' => _x( 'Please delete 1 character', 'enhanced select', 'woocommerce' ), 'i18n_input_too_long_n' => _x( 'Please delete %qty% characters', 'enhanced select', 'woocommerce' ), 'i18n_selection_too_long_1' => _x( 'You can only select 1 item', 'enhanced select', 'woocommerce' ), 'i18n_selection_too_long_n' => _x( 'You can only select %qty% items', 'enhanced select', 'woocommerce' ), 'i18n_load_more' => _x( 'Loading more results&hellip;', 'enhanced select', 'woocommerce' ), 'i18n_searching' => _x( 'Searching&hellip;', 'enhanced select', 'woocommerce' ), 'ajax_url' => admin_url( 'admin-ajax.php' ), 'search_products_nonce' => wp_create_nonce( 'search-products' ), 'search_customers_nonce' => wp_create_nonce( 'search-customers' ), ) ); // Accounting wp_localize_script( 'accounting', 'accounting_params', array( 'mon_decimal_point' => wc_get_price_decimal_separator(), ) ); // WooCommerce admin pages if ( in_array( $screen_id, wc_get_screen_ids() ) ) { wp_enqueue_script( 'iris' ); wp_enqueue_script( 'woocommerce_admin' ); wp_enqueue_script( 'wc-enhanced-select' ); wp_enqueue_script( 'jquery-ui-sortable' ); wp_enqueue_script( 'jquery-ui-autocomplete' ); $locale = localeconv(); $decimal = isset( $locale['decimal_point'] ) ? $locale['decimal_point'] : '.'; $params = array( /* translators: %s: decimal */ 'i18n_decimal_error' => sprintf( __( 'Please enter in decimal (%s) format without thousand separators.', 'woocommerce' ), $decimal ), /* translators: %s: price decimal separator */ 'i18n_mon_decimal_error' => sprintf( __( 'Please enter in monetary decimal (%s) format without thousand separators and currency symbols.', 'woocommerce' ), wc_get_price_decimal_separator() ), 'i18n_country_iso_error' => __( 'Please enter in country code with two capital letters.', 'woocommerce' ), 'i18_sale_less_than_regular_error' => __( 'Please enter in a value less than the regular price.', 'woocommerce' ), 'decimal_point' => $decimal, 'mon_decimal_point' => wc_get_price_decimal_separator(), ); wp_localize_script( 'woocommerce_admin', 'woocommerce_admin', $params ); } // Edit product category pages if ( in_array( $screen_id, array( 'edit-product_cat' ) ) ) { wp_enqueue_media(); } // Products if ( in_array( $screen_id, array( 'edit-product' ) ) ) { wp_register_script( 'woocommerce_quick-edit', WC()->plugin_url() . '/assets/js/admin/quick-edit' . $suffix . '.js', array( 'jquery', 'woocommerce_admin' ), WC_VERSION ); wp_enqueue_script( 'woocommerce_quick-edit' ); } // Meta boxes if ( in_array( $screen_id, array( 'product', 'edit-product' ) ) ) { wp_enqueue_media(); wp_register_script( 'wc-admin-product-meta-boxes', WC()->plugin_url() . '/assets/js/admin/meta-boxes-product' . $suffix . '.js', array( 'wc-admin-meta-boxes', 'media-models' ), WC_VERSION ); wp_register_script( 'wc-admin-variation-meta-boxes', WC()->plugin_url() . '/assets/js/admin/meta-boxes-product-variation' . $suffix . '.js', array( 'wc-admin-meta-boxes', 'serializejson', 'media-models' ), WC_VERSION ); wp_enqueue_script( 'wc-admin-product-meta-boxes' ); wp_enqueue_script( 'wc-admin-variation-meta-boxes' ); $params = array( 'post_id' => isset( $post->ID ) ? $post->ID : '', 'plugin_url' => WC()->plugin_url(), 'ajax_url' => admin_url( 'admin-ajax.php' ), 'woocommerce_placeholder_img_src' => wc_placeholder_img_src(), 'add_variation_nonce' => wp_create_nonce( 'add-variation' ), 'link_variation_nonce' => wp_create_nonce( 'link-variations' ), 'delete_variations_nonce' => wp_create_nonce( 'delete-variations' ), 'load_variations_nonce' => wp_create_nonce( 'load-variations' ), 'save_variations_nonce' => wp_create_nonce( 'save-variations' ), 'bulk_edit_variations_nonce' => wp_create_nonce( 'bulk-edit-variations' ), 'i18n_link_all_variations' => esc_js( sprintf( __( 'Are you sure you want to link all variations? This will create a new variation for each and every possible combination of variation attributes (max %d per run).', 'woocommerce' ), defined( 'WC_MAX_LINKED_VARIATIONS' ) ? WC_MAX_LINKED_VARIATIONS : 50 ) ), 'i18n_enter_a_value' => esc_js( __( 'Enter a value', 'woocommerce' ) ), 'i18n_enter_menu_order' => esc_js( __( 'Variation menu order (determines position in the list of variations)', 'woocommerce' ) ), 'i18n_enter_a_value_fixed_or_percent' => esc_js( __( 'Enter a value (fixed or %)', 'woocommerce' ) ), 'i18n_delete_all_variations' => esc_js( __( 'Are you sure you want to delete all variations? This cannot be undone.', 'woocommerce' ) ), 'i18n_last_warning' => esc_js( __( 'Last warning, are you sure?', 'woocommerce' ) ), 'i18n_choose_image' => esc_js( __( 'Choose an image', 'woocommerce' ) ), 'i18n_set_image' => esc_js( __( 'Set variation image', 'woocommerce' ) ), 'i18n_variation_added' => esc_js( __( "variation added", 'woocommerce' ) ), 'i18n_variations_added' => esc_js( __( "variations added", 'woocommerce' ) ), 'i18n_no_variations_added' => esc_js( __( "No variations added", 'woocommerce' ) ), 'i18n_remove_variation' => esc_js( __( 'Are you sure you want to remove this variation?', 'woocommerce' ) ), 'i18n_scheduled_sale_start' => esc_js( __( 'Sale start date (YYYY-MM-DD format or leave blank)', 'woocommerce' ) ), 'i18n_scheduled_sale_end' => esc_js( __( 'Sale end date (YYYY-MM-DD format or leave blank)', 'woocommerce' ) ), 'i18n_edited_variations' => esc_js( __( 'Save changes before changing page?', 'woocommerce' ) ), 'i18n_variation_count_single' => esc_js( __( '%qty% variation', 'woocommerce' ) ), 'i18n_variation_count_plural' => esc_js( __( '%qty% variations', 'woocommerce' ) ), 'variations_per_page' => absint( apply_filters( 'woocommerce_admin_meta_boxes_variations_per_page', 15 ) ), ); wp_localize_script( 'wc-admin-variation-meta-boxes', 'woocommerce_admin_meta_boxes_variations', $params ); } if ( in_array( str_replace( 'edit-', '', $screen_id ), wc_get_order_types( 'order-meta-boxes' ) ) ) { $default_location = wc_get_customer_default_location(); wp_enqueue_script( 'wc-admin-order-meta-boxes', WC()->plugin_url() . '/assets/js/admin/meta-boxes-order' . $suffix . '.js', array( 'wc-admin-meta-boxes', 'wc-backbone-modal' ), WC_VERSION ); wp_localize_script( 'wc-admin-order-meta-boxes', 'woocommerce_admin_meta_boxes_order', array( 'countries' => json_encode( array_merge( WC()->countries->get_allowed_country_states(), WC()->countries->get_shipping_country_states() ) ), 'i18n_select_state_text' => esc_attr__( 'Select an option&hellip;', 'woocommerce' ), 'default_country' => isset( $default_location['country'] ) ? $default_location['country'] : '', 'default_state' => isset( $default_location['state'] ) ? $default_location['state'] : '', 'placeholder_name' => esc_attr__( 'Name (required)', 'woocommerce' ), 'placeholder_value' => esc_attr__( 'Value (required)', 'woocommerce' ), ) ); } if ( in_array( $screen_id, array( 'shop_coupon', 'edit-shop_coupon' ) ) ) { wp_enqueue_script( 'wc-admin-coupon-meta-boxes', WC()->plugin_url() . '/assets/js/admin/meta-boxes-coupon' . $suffix . '.js', array( 'wc-admin-meta-boxes' ), WC_VERSION ); } if ( in_array( str_replace( 'edit-', '', $screen_id ), array_merge( array( 'shop_coupon', 'product' ), wc_get_order_types( 'order-meta-boxes' ) ) ) ) { $post_id = isset( $post->ID ) ? $post->ID : ''; $currency = ''; if ( $post_id && in_array( get_post_type( $post_id ), wc_get_order_types( 'order-meta-boxes' ) ) && ( $order = wc_get_order( $post_id ) ) ) { $currency = $order->get_currency(); } $params = array( 'remove_item_notice' => __( "Are you sure you want to remove the selected items? If you have previously reduced this item's stock, or this order was submitted by a customer, you will need to manually restore the item's stock.", 'woocommerce' ), 'i18n_select_items' => __( 'Please select some items.', 'woocommerce' ), 'i18n_do_refund' => __( 'Are you sure you wish to process this refund? This action cannot be undone.', 'woocommerce' ), 'i18n_delete_refund' => __( 'Are you sure you wish to delete this refund? This action cannot be undone.', 'woocommerce' ), 'i18n_delete_tax' => __( 'Are you sure you wish to delete this tax column? This action cannot be undone.', 'woocommerce' ), 'remove_item_meta' => __( 'Remove this item meta?', 'woocommerce' ), 'remove_attribute' => __( 'Remove this attribute?', 'woocommerce' ), 'name_label' => __( 'Name', 'woocommerce' ), 'remove_label' => __( 'Remove', 'woocommerce' ), 'click_to_toggle' => __( 'Click to toggle', 'woocommerce' ), 'values_label' => __( 'Value(s)', 'woocommerce' ), 'text_attribute_tip' => __( 'Enter some text, or some attributes by pipe (|) separating values.', 'woocommerce' ), 'visible_label' => __( 'Visible on the product page', 'woocommerce' ), 'used_for_variations_label' => __( 'Used for variations', 'woocommerce' ), 'new_attribute_prompt' => __( 'Enter a name for the new attribute term:', 'woocommerce' ), 'calc_totals' => __( 'Recalculate totals? This will calculate taxes based on the customers country (or the store base country) and update totals.', 'woocommerce' ), 'copy_billing' => __( 'Copy billing information to shipping information? This will remove any currently entered shipping information.', 'woocommerce' ), 'load_billing' => __( "Load the customer's billing information? This will remove any currently entered billing information.", 'woocommerce' ), 'load_shipping' => __( "Load the customer's shipping information? This will remove any currently entered shipping information.", 'woocommerce' ), 'featured_label' => __( 'Featured', 'woocommerce' ), 'prices_include_tax' => esc_attr( get_option( 'woocommerce_prices_include_tax' ) ), 'tax_based_on' => esc_attr( get_option( 'woocommerce_tax_based_on' ) ), 'round_at_subtotal' => esc_attr( get_option( 'woocommerce_tax_round_at_subtotal' ) ), 'no_customer_selected' => __( 'No customer selected', 'woocommerce' ), 'plugin_url' => WC()->plugin_url(), 'ajax_url' => admin_url( 'admin-ajax.php' ), 'order_item_nonce' => wp_create_nonce( 'order-item' ), 'add_attribute_nonce' => wp_create_nonce( 'add-attribute' ), 'save_attributes_nonce' => wp_create_nonce( 'save-attributes' ), 'calc_totals_nonce' => wp_create_nonce( 'calc-totals' ), 'get_customer_details_nonce' => wp_create_nonce( 'get-customer-details' ), 'search_products_nonce' => wp_create_nonce( 'search-products' ), 'grant_access_nonce' => wp_create_nonce( 'grant-access' ), 'revoke_access_nonce' => wp_create_nonce( 'revoke-access' ), 'add_order_note_nonce' => wp_create_nonce( 'add-order-note' ), 'delete_order_note_nonce' => wp_create_nonce( 'delete-order-note' ), 'calendar_image' => WC()->plugin_url() . '/assets/images/calendar.png', 'post_id' => isset( $post->ID ) ? $post->ID : '', 'base_country' => WC()->countries->get_base_country(), 'currency_format_num_decimals' => wc_get_price_decimals(), 'currency_format_symbol' => get_woocommerce_currency_symbol( $currency ), 'currency_format_decimal_sep' => esc_attr( wc_get_price_decimal_separator() ), 'currency_format_thousand_sep' => esc_attr( wc_get_price_thousand_separator() ), 'currency_format' => esc_attr( str_replace( array( '%1$s', '%2$s' ), array( '%s', '%v' ), get_woocommerce_price_format() ) ), // For accounting JS 'rounding_precision' => wc_get_rounding_precision(), 'tax_rounding_mode' => WC_TAX_ROUNDING_MODE, 'product_types' => array_unique( array_merge( array( 'simple', 'grouped', 'variable', 'external' ), array_keys( wc_get_product_types() ) ) ), 'i18n_download_permission_fail' => __( 'Could not grant access - the user may already have permission for this file or billing email is not set. Ensure the billing email is set, and the order has been saved.', 'woocommerce' ), 'i18n_permission_revoke' => __( 'Are you sure you want to revoke access to this download?', 'woocommerce' ), 'i18n_tax_rate_already_exists' => __( 'You cannot add the same tax rate twice!', 'woocommerce' ), 'i18n_delete_note' => __( 'Are you sure you wish to delete this note? This action cannot be undone.', 'woocommerce' ), ); wp_localize_script( 'wc-admin-meta-boxes', 'woocommerce_admin_meta_boxes', $params ); } // Term ordering - only when sorting by term_order if ( ( strstr( $screen_id, 'edit-pa_' ) || ( ! empty( $_GET['taxonomy'] ) && in_array( $_GET['taxonomy'], apply_filters( 'woocommerce_sortable_taxonomies', array( 'product_cat' ) ) ) ) ) && ! isset( $_GET['orderby'] ) ) { wp_register_script( 'woocommerce_term_ordering', WC()->plugin_url() . '/assets/js/admin/term-ordering' . $suffix . '.js', array( 'jquery-ui-sortable' ), WC_VERSION ); wp_enqueue_script( 'woocommerce_term_ordering' ); $taxonomy = isset( $_GET['taxonomy'] ) ? wc_clean( $_GET['taxonomy'] ) : ''; $woocommerce_term_order_params = array( 'taxonomy' => $taxonomy, ); wp_localize_script( 'woocommerce_term_ordering', 'woocommerce_term_ordering_params', $woocommerce_term_order_params ); } // Product sorting - only when sorting by menu order on the products page if ( current_user_can( 'edit_others_pages' ) && 'edit-product' === $screen_id && isset( $wp_query->query['orderby'] ) && 'menu_order title' === $wp_query->query['orderby'] ) { wp_register_script( 'woocommerce_product_ordering', WC()->plugin_url() . '/assets/js/admin/product-ordering' . $suffix . '.js', array( 'jquery-ui-sortable' ), WC_VERSION, true ); wp_enqueue_script( 'woocommerce_product_ordering' ); } // Reports Pages if ( in_array( $screen_id, apply_filters( 'woocommerce_reports_screen_ids', array( $wc_screen_id . '_page_wc-reports', 'toplevel_page_wc-reports', 'dashboard' ) ) ) ) { wp_register_script( 'wc-reports', WC()->plugin_url() . '/assets/js/admin/reports' . $suffix . '.js', array( 'jquery', 'jquery-ui-datepicker' ), WC_VERSION ); wp_enqueue_script( 'wc-reports' ); wp_enqueue_script( 'flot' ); wp_enqueue_script( 'flot-resize' ); wp_enqueue_script( 'flot-time' ); wp_enqueue_script( 'flot-pie' ); wp_enqueue_script( 'flot-stack' ); } // API settings if ( $wc_screen_id . '_page_wc-settings' === $screen_id && isset( $_GET['section'] ) && 'keys' == $_GET['section'] ) { wp_register_script( 'wc-api-keys', WC()->plugin_url() . '/assets/js/admin/api-keys' . $suffix . '.js', array( 'jquery', 'woocommerce_admin', 'underscore', 'backbone', 'wp-util', 'qrcode', 'zeroclipboard' ), WC_VERSION, true ); wp_enqueue_script( 'wc-api-keys' ); wp_localize_script( 'wc-api-keys', 'woocommerce_admin_api_keys', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'update_api_nonce' => wp_create_nonce( 'update-api-key' ), 'clipboard_failed' => esc_html__( 'Copying to clipboard failed. Please press Ctrl/Cmd+C to copy.', 'woocommerce' ), ) ); } // System status. if ( $wc_screen_id . '_page_wc-status' === $screen_id ) { wp_register_script( 'wc-admin-system-status', WC()->plugin_url() . '/assets/js/admin/system-status' . $suffix . '.js', array( 'zeroclipboard' ), WC_VERSION ); wp_enqueue_script( 'wc-admin-system-status' ); wp_localize_script( 'wc-admin-system-status', 'woocommerce_admin_system_status', array( 'delete_log_confirmation' => esc_js( __( 'Are you sure you want to delete this log?', 'woocommerce' ) ), ) ); } if ( in_array( $screen_id, array( 'user-edit', 'profile' ) ) ) { wp_register_script( 'wc-users', WC()->plugin_url() . '/assets/js/admin/users' . $suffix . '.js', array( 'jquery', 'wc-enhanced-select' ), WC_VERSION, true ); wp_enqueue_script( 'wc-users' ); wp_localize_script( 'wc-users', 'wc_users_params', array( 'countries' => json_encode( array_merge( WC()->countries->get_allowed_country_states(), WC()->countries->get_shipping_country_states() ) ), 'i18n_select_state_text' => esc_attr__( 'Select an option&hellip;', 'woocommerce' ), ) ); } } /** * Admin Head. * * Outputs some styles in the admin <head> to show icons on the woocommerce admin pages. */ public function product_taxonomy_styles() { if ( ! current_user_can( 'manage_woocommerce' ) ) { return; } ?> <style type="text/css"> <?php if ( isset( $_GET['taxonomy'] ) && 'product_cat' === $_GET['taxonomy'] ) : ?> .icon32-posts-product { background-position: -243px -5px !important; } <?php elseif ( isset( $_GET['taxonomy'] ) && 'product_tag' === $_GET['taxonomy'] ) : ?> .icon32-posts-product { background-position: -301px -5px !important; } <?php endif; ?> </style> <?php } } endif; return new WC_Admin_Assets();
gpl-3.0
evilsocket/Kerby_Surveillance
main.cpp
3553
/*************************************************************************** * @brief Kerby - Light weight video surveillance system * * @author Simone Margaritelli (aka evilsocket) <evilsocket@gmail.com> * * * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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. * ***************************************************************************/ #define DEBUG 1 #include "analyzer.h" #include "avi.h" #include "config.h" /* void usage( char *app ){ printf( "\nUsage %s -d <device> -t <threshold> -q <quadrantsize> -a <alarm percentage>\n\n", app ); } */ int main( int argc, char *argv[] ){ kb_video_driver_t *v4l = (kb_video_driver_t *)&kb_video_drivers[0]; kb_device_t device; kb_video_buffer_t frame; Analyzer *analyzer; char moviename[0xFF] = {0}; AVI *movie = NULL; Config config; double delta; if( v4l->open( config.get("DEVICE"), &device ) < 0 ){ exit(-1); } analyzer = new Analyzer( v4l, device.width, device.height, 3, config.get_int("QUADRANTSIZE"), config.get_double("THRESHOLD") ); #ifdef DEBUG config.dump(); printf( "Device :\n" "\tfile descriptor : %d\n" "\tmemory map : 0x%X\n" "\tdevice : %s\n" "\tname : %s\n" "\tmax width : %d\n" "\tmax height : %d\n" "\tdepth : %d\n", device.fd, device.mmap, device.device, device.name, device.width, device.height, device.depth ); #endif while( 1 ){ v4l->capture( &device, &frame ); delta = analyzer->update( &frame ); //if( delta > 0 ) printf( "DELTA : %f\n", delta ); if( delta > 0.0f ){ // create movie and start adding frames if( movie == NULL ){ sprintf( moviename, "%s/%d.avi", config.get("RECORDPATH"), time(NULL) ); #ifdef DEBUG printf( "@ Creating new movie %s .\n", moviename ); #endif movie = new AVI( moviename, device.width, device.height ); movie->start(); } // continue with previously created movie #ifdef DEBUG printf( "@ Adding frame to %s .\n", moviename ); #endif movie->addFrame(&frame); } else{ if( movie != NULL ){ #ifdef DEBUG printf( "@ Closing movie %s .\n", moviename ); #endif delete movie; } movie = NULL; } } v4l->close( &device ); delete analyzer; return 0; }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtlocation/src/3rdparty/mapbox-gl-native/platform/android/src/test/main.jni.cpp
3426
#include "../jni.hpp" #include <android/log.h> #include <jni/jni.hpp> #include <jni/jni.hpp> #include <mbgl/util/logging.hpp> #include <mbgl/test.hpp> #include <vector> #pragma clang diagnostic ignored "-Wunused-parameter" #define MAKE_NATIVE_METHOD(name, sig) jni::MakeNativeMethod<decltype(name), name>( #name, sig ) namespace { // Main class (entry point for tests from dalvikvm) struct Main { static constexpr auto Name() { return "Main"; } /** * JNI Bound to Main#runAllTests() */ static void runAllTests(jni::JNIEnv& env, jni::Object<Main>, jni::Array<jni::String> args) { mbgl::Log::Warning(mbgl::Event::JNI, "Starting tests"); // We need to create a copy of the argv data since Java-internals are stored in UTF-16. std::vector<std::string> data; // Add a fake first argument to align indices. Google Test expects the first argument to // start at index 1; index 0 is the name of the executable. data.push_back("main.jar"); const int argc = args.Length(env); for (auto i = 0; i < argc; i++) { data.emplace_back(jni::Make<std::string>(env, args.Get(env, i))); } // Create an array of char pointers that point back to the data array. std::vector<const char*> argv; for (const auto& arg : data) { argv.push_back(arg.data()); } mbgl::runTests(argv.size(), const_cast<char**>(argv.data())); } }; } // namespace // JNI Bindings to stub the android.util.Log implementation static jboolean isLoggable(JNIEnv* env, jni::jobject* clazz, jni::jstring* tag, jint level) { return true; } static jint println_native(JNIEnv* env, jni::jobject* clazz, jint bufID, jint priority, jni::jstring* jtag, jni::jstring* jmessage) { if (jtag == nullptr || jmessage == nullptr) { return false; } std::string tag = jni::Make<std::string>(*env, jni::String(jtag)); std::string message = jni::Make<std::string>(*env, jni::String(jmessage)); return __android_log_print(priority, tag.c_str(), "%s", message.c_str()); } static jint logger_entry_max_payload_native(JNIEnv* env, jni::jobject* clazz) { return static_cast<jint>(4068); } // Main entry point extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { // Load the main library jni bindings mbgl::Log::Info(mbgl::Event::JNI, "Registering main JNI Methods"); mbgl::android::registerNatives(vm); // Load the test library jni bindings mbgl::Log::Info(mbgl::Event::JNI, "Registering test JNI Methods"); jni::JNIEnv& env = jni::GetEnv(*vm, jni::jni_version_1_6); jni::RegisterNatives(env, jni::Class<Main>::Find(env), jni::MakeNativeMethod<decltype(Main::runAllTests), &Main::runAllTests>("runAllTests")); // Bindings for system classes struct Log { static constexpr auto Name() { return "android/util/Log"; } }; try { jni::RegisterNatives(env, jni::Class<Log>::Find(env), MAKE_NATIVE_METHOD(isLoggable, "(Ljava/lang/String;I)Z"), MAKE_NATIVE_METHOD(logger_entry_max_payload_native, "()I"), MAKE_NATIVE_METHOD(println_native, "(IILjava/lang/String;Ljava/lang/String;)I") ); } catch (jni::PendingJavaException ex) { env.ThrowNew(jni::JavaErrorClass(env), "Could not register Log mocks"); } return JNI_VERSION_1_6; }
gpl-3.0
jukkes/TulipProject
plugins/metric/Eccentricity.cpp
5296
/** * * This file is part of Tulip (www.tulip-software.org) * * Authors: David Auber and the Tulip development Team * from LaBRI, University of Bordeaux * * Tulip is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * Tulip 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. * */ #include <deque> #ifdef _OPENMP #include <omp.h> #endif #include <tulip/ConnectedTest.h> #include "Eccentricity.h" PLUGIN(EccentricityMetric) using namespace std; using namespace tlp; namespace { const char * paramHelp[] = { // property HTML_HELP_OPEN() \ HTML_HELP_DEF( "type", "bool" ) \ HTML_HELP_DEF( "values", "[true , false]" ) \ HTML_HELP_DEF( "default", "false" ) \ HTML_HELP_BODY() \ "If true, the closeness centrality is computed (i.e. the average distance from the node to all others)."\ HTML_HELP_CLOSE(), // norm HTML_HELP_OPEN() \ HTML_HELP_DEF( "type", "bool" ) \ HTML_HELP_DEF( "values", "[true , false]" ) \ HTML_HELP_DEF( "default", "false" ) \ HTML_HELP_BODY() \ "If true, the returned values are normalized. " \ "For the closeness centrality, the reciprocal of the sum of distances is returned. " \ "The eccentricity values are divided by the graph diameter. " \ "<b> Warning : </b> The normalized eccentricity values sould be computed on a (strongly) connected graph." HTML_HELP_CLOSE(), // directed HTML_HELP_OPEN() \ HTML_HELP_DEF( "type", "bool" ) \ HTML_HELP_DEF( "values", "[true , false]" ) \ HTML_HELP_DEF( "default", "false" ) \ HTML_HELP_BODY() \ "If true, the graph is considered directed."\ HTML_HELP_CLOSE(), }; } EccentricityMetric::EccentricityMetric(const tlp::PluginContext* context):DoubleAlgorithm(context), allPaths(false), norm(true), directed(false) { addInParameter<bool>("closeness centrality",paramHelp[0],"false"); addInParameter<bool>("norm",paramHelp[1],"true"); addInParameter<bool>("directed",paramHelp[2],"false"); } //==================================================================== EccentricityMetric::~EccentricityMetric() { } //==================================================================== double EccentricityMetric::compute(node n) { MutableContainer<unsigned int> distance; distance.setAll(0); double val; val = directed ? tlp::maxDistance(graph, n, distance, DIRECTED) : tlp::maxDistance(graph, n, distance, UNDIRECTED); if(!allPaths) return val; double nbAcc = 0.; node n2; val = 0.; forEach(n2, graph->getNodes()) { if (distance.get(n2.id) < graph->numberOfNodes()) { nbAcc += 1.; if(n2!=n) val += double(distance.get(n2.id)) ; } } if(nbAcc<2.0) return 0.0; if (norm) val=1.0/val; else val/=(nbAcc-1.0); return val; } //==================================================================== bool EccentricityMetric::run() { allPaths = false; norm = true; directed = false; if (dataSet!=NULL) { dataSet->get("closeness centrality", allPaths); dataSet->get("norm", norm); dataSet->get("directed", directed); } node n; size_t i = 0; vector<node> vecNodes(graph->numberOfNodes()); vector<double> res(graph->numberOfNodes()); forEach(n, graph->getNodes()) { vecNodes[i] = n; ++i; } // omp_set_num_threads(4); size_t nbElem = vecNodes.size(); #ifdef _OPENMP int nbThreads = omp_get_num_procs(); #else unsigned int nbThreads = 1; #endif // double t1 = omp_get_wtime(); double diameter = 1.0; bool stopfor = false; #ifdef _OPENMP #pragma omp parallel for #endif for (int ni = 0; ni < static_cast<int>(nbElem) ; ++ni) { if (stopfor) continue; #ifdef _OPENMP if (omp_get_thread_num() == 0) { #endif if (pluginProgress->progress(ni , graph->numberOfNodes() / nbThreads )!=TLP_CONTINUE) { #ifdef _OPENMP #pragma omp critical(STOPFOR) #endif stopfor = true; } #ifdef _OPENMP } #endif res[ni] = compute(vecNodes[ni]); if(!allPaths && norm) #ifdef _OPENMP #pragma omp critical(DIAMETER) #endif { if(diameter<res[ni]) diameter=res[ni]; } } for (size_t ni = 0; ni < nbElem; ++ni) { if(!allPaths && norm) result->setNodeValue(vecNodes[ni], res[ni]/diameter); else result->setNodeValue(vecNodes[ni], res[ni]); } /* double t2 = omp_get_wtime(); for (size_t ni = 0; ni < nbElem; ++ni) { double val = compute(vecNodes[ni]); result->setNodeValue(vecNodes[ni], val); } double t3 = omp_get_wtime(); tlp::debug() << "omp : " << t2 - t1 << "s" << endl << flush; tlp::debug() << "sng : " << t3 - t2 << "s" << endl << flush; */ /* Iterator<node> *itN = graph->getNodes(); for (unsigned int i=0; itN->hasNext(); ++i) { if (pluginProgress->progress(i, graph->numberOfNodes())!=TLP_CONTINUE) break; node n = itN->next(); result->setNodeValue(n, compute(n)); } */ return pluginProgress->state()!=TLP_CANCEL; }
gpl-3.0
futurable/futural
backend/protected/models/AccountCommonReport.php
5243
<?php /** * This is the model class for table "account_common_report". * * The followings are the available columns in table 'account_common_report': * @property integer $id * @property integer $create_uid * @property string $create_date * @property string $write_date * @property integer $write_uid * @property integer $chart_account_id * @property string $date_from * @property integer $period_to * @property string $filter * @property integer $period_from * @property integer $fiscalyear_id * @property string $date_to * @property string $target_move * * The followings are the available model relations: * @property AccountCommonReportAccountJournalRel[] $accountCommonReportAccountJournalRels * @property ResUsers $writeU * @property AccountPeriod $periodTo * @property AccountPeriod $periodFrom * @property AccountFiscalyear $fiscalyear * @property ResUsers $createU * @property AccountAccount $chartAccount */ class AccountCommonReport extends CActiveRecord { /** * @return string the associated database table name */ public function tableName() { return 'account_common_report'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('chart_account_id, filter, target_move', 'required'), array('create_uid, write_uid, chart_account_id, period_to, period_from, fiscalyear_id', 'numerical', 'integerOnly'=>true), array('create_date, write_date, date_from, date_to', 'safe'), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. array('id, create_uid, create_date, write_date, write_uid, chart_account_id, date_from, period_to, filter, period_from, fiscalyear_id, date_to, target_move', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'accountCommonReportAccountJournalRels' => array(self::HAS_MANY, 'AccountCommonReportAccountJournalRel', 'account_common_report_id'), 'writeU' => array(self::BELONGS_TO, 'ResUsers', 'write_uid'), 'periodTo' => array(self::BELONGS_TO, 'AccountPeriod', 'period_to'), 'periodFrom' => array(self::BELONGS_TO, 'AccountPeriod', 'period_from'), 'fiscalyear' => array(self::BELONGS_TO, 'AccountFiscalyear', 'fiscalyear_id'), 'createU' => array(self::BELONGS_TO, 'ResUsers', 'create_uid'), 'chartAccount' => array(self::BELONGS_TO, 'AccountAccount', 'chart_account_id'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'create_uid' => 'Create Uid', 'create_date' => 'Create Date', 'write_date' => 'Write Date', 'write_uid' => 'Write Uid', 'chart_account_id' => 'Chart Account', 'date_from' => 'Date From', 'period_to' => 'Period To', 'filter' => 'Filter', 'period_from' => 'Period From', 'fiscalyear_id' => 'Fiscalyear', 'date_to' => 'Date To', 'target_move' => 'Target Move', ); } /** * Retrieves a list of models based on the current search/filter conditions. * * Typical usecase: * - Initialize the model fields with values from filter form. * - Execute this method to get CActiveDataProvider instance which will filter * models according to data in model fields. * - Pass data provider to CGridView, CListView or any similar widget. * * @return CActiveDataProvider the data provider that can return the models * based on the search/filter conditions. */ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('create_uid',$this->create_uid); $criteria->compare('create_date',$this->create_date,true); $criteria->compare('write_date',$this->write_date,true); $criteria->compare('write_uid',$this->write_uid); $criteria->compare('chart_account_id',$this->chart_account_id); $criteria->compare('date_from',$this->date_from,true); $criteria->compare('period_to',$this->period_to); $criteria->compare('filter',$this->filter,true); $criteria->compare('period_from',$this->period_from); $criteria->compare('fiscalyear_id',$this->fiscalyear_id); $criteria->compare('date_to',$this->date_to,true); $criteria->compare('target_move',$this->target_move,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * @return CDbConnection the database connection used for this class */ public function getDbConnection() { return Yii::app()->dbopenerp; } /** * Returns the static model of the specified AR class. * Please note that you should have this exact method in all your CActiveRecord descendants! * @param string $className active record class name. * @return AccountCommonReport the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } }
gpl-3.0
xEssentials/xEssentials
src/tv/mineinthebox/essentials/commands/CmdTpa.java
3483
package tv.mineinthebox.essentials.commands; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import tv.mineinthebox.essentials.xEssentials; import tv.mineinthebox.essentials.enums.PermissionKey; import tv.mineinthebox.essentials.interfaces.CommandTemplate; import tv.mineinthebox.essentials.interfaces.XPlayer; public class CmdTpa extends CommandTemplate { private final xEssentials pl; public CmdTpa(xEssentials pl, Command cmd, CommandSender sender) { super(pl, cmd, sender); this.pl = pl; } public boolean execute(final CommandSender sender, Command cmd, String[] args) { if(cmd.getName().equalsIgnoreCase("tpa")) { if(sender instanceof Player) { if(sender.hasPermission(PermissionKey.CMD_TPA.getPermission())) { if(args.length == 0) { showHelp(); } else if(args.length == 1) { if(args[0].equalsIgnoreCase("help")) { showHelp(); } else { final Player victem = pl.getManagers().getPlayerManager().getOfflinePlayer(args[0]).getBukkitPlayer(); final String victemName = victem.getName(); final String senderName = sender.getName(); if(victem instanceof Player) { XPlayer xpp = pl.getManagers().getPlayerManager().getPlayer(victem.getName()); if(xpp.isVanished()) { sendMessage("this player is offline!"); return false; } if(!(pl.getManagers().getTpaManager().containsKey(victem.getName()) || pl.getManagers().getTpaManager().containsValue(victem.getName()))) { pl.getManagers().getTpaManager().put(victem.getName(), sender.getName()); Bukkit.getScheduler().scheduleSyncDelayedTask(pl, new Runnable() { @Override public void run() { if(pl.getManagers().getTpaManager().containsKey(victemName)) { pl.getManagers().getTpaManager().remove(victemName); if(sender instanceof Player) { sendMessage("the tpa request to player " + victemName + " has been over time!"); } if(victem instanceof Player) { sendMessageTo(victem, "the tpa request from " + senderName + " been canceled out"); } } } }, 5000); sendMessage("tpa request sent to player " + victem.getName()); sendMessageTo(victem, sender.getName() + " wants to teleport to you"); sendMessageTo(victem, "type: " + ChatColor.GRAY + "/tpaccept - so the player can teleport to you"); sendMessageTo(victem, "type: " + ChatColor.GRAY + "/tpdeny - so the player cannot teleport to you"); } else { sendMessage("this player has to many tpa requests open!"); } } else { sendMessage("this player is offline!"); } } } } else { getWarning(WarningType.NO_PERMISSION); } } else { getWarning(WarningType.PLAYER_ONLY); } } return false; } @Override public void showHelp() { sender.sendMessage(ChatColor.GOLD + ".oO___[tpa help]___Oo."); sender.sendMessage(ChatColor.DARK_GRAY + "Default: " + ChatColor.GRAY + "/tpa help " + ChatColor.WHITE + ": shows help"); sender.sendMessage(ChatColor.DARK_GRAY + "Default: " + ChatColor.GRAY + "/tpa <player> " + ChatColor.WHITE + ": sent a tpa request to a player"); } }
gpl-3.0
joseortega/finance
apps/backend/modules/category/actions/actions.class.php
406
<?php require_once dirname(__FILE__).'/../lib/categoryGeneratorConfiguration.class.php'; require_once dirname(__FILE__).'/../lib/categoryGeneratorHelper.class.php'; /** * category actions. * * @package finance * @subpackage category * @author Jose Ortega * @version SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $ */ class categoryActions extends autoCategoryActions { }
gpl-3.0
ManifoldScholar/manifold
api/app/services/importer/helpers/list.rb
3594
# This class is used in place of the GoogleDrive gem's list class, which provides an # enumerable interface to Google worksheets. The reason we override it is because our # current implementation assumes that the data in the worksheet begins on row 4, and that # the column headers begin on row 2. This is per the structure laid out by the University # of Minnesota press. # rubocop:disable Style/For module Importer module Helpers class List include(Enumerable) # @api private def initialize(worksheet) @worksheet = worksheet end # Number of non-empty rows in the worksheet excluding the three rows. def size @worksheet.num_rows - 3 end # Returns Hash-like object (GoogleDrive::ListRow) for the row with the # index. Keys of the object are colum names (the first row). # The second row has index 0. # # Note that updates to the returned object are not sent to the server until # you call GoogleDrive::Worksheet#save(). def [](index) GoogleDrive::ListRow.new(self, index) end # Updates the row with the index with the given Hash object. # Keys of +hash+ are colum names (the first row). # The second row has index 0. # # Note that update is not sent to the server until # you call GoogleDrive::Worksheet#save(). def []=(index, hash) self[index].replace(hash) end # Iterates over Hash-like object (GoogleDrive::ListRow) for each row # (except for the first row). # Keys of the object are colum names (the first row). def each(&_block) for i in 0...size yield(self[i]) end end # Column names i.e. the contents of the first row. # Duplicates are removed. def keys (1..@worksheet.num_cols).map { |i| @worksheet[2, i] }.uniq end # Updates column names i.e. the contents of the first row. # # Note that update is not sent to the server until # you call GoogleDrive::Worksheet#save(). def keys=(ary) for i in 1..ary.size @worksheet[2, i] = ary[i - 1] end for i in (ary.size + 1)..@worksheet.num_cols @worksheet[2, i] = "" end end # Adds a new row to the bottom. # Keys of +hash+ are colum names (the first row). # Returns GoogleDrive::ListRow for the new row. # # Note that update is not sent to the server until # you call GoogleDrive::Worksheet#save(). def push(hash) row = self[size] row.update(hash) row end # Returns all rows (except for the first row) as Array of Hash. # Keys of Hash objects are colum names (the first row). def to_hash_array map(&:to_hash) end # @api private def get(index, key) @worksheet[index + 4, key_to_col(key)] end # @api private def numeric_value(index, key) @worksheet.numeric_value(index + 4, key_to_col(key)) end # @api private def input_value(index, key) @worksheet.input_value(index + 4, key_to_col(key)) end # @api private def set(index, key, value) @worksheet[index + 2, key_to_col(key)] = value end private def key_to_col(key) key = key.to_s col = (1..@worksheet.num_cols).find { |c| @worksheet[2, c] == key } raise(GoogleDrive::Error, "Column doesn't exist: %p" % key) unless col col end end end end # rubocop:enable Style/For
gpl-3.0
Apretaste/Core
classes/Response.php
4020
<?php class Response { public $email; public $subject; public $template; public $content; public $json; // NULL unless the return is an email API public $images; public $attachments; public $internal; // false if the user provides the template public $render; // false if the response should not be email to the user public $layout; public $cache = 0; public $service = false; /** * Create default template * * @author salvipascual */ public function __construct() { $this->template = "message.tpl"; $this->content = ["text"=>"Empty response"]; $this->images = []; $this->attachments = []; $this->json = null; $this->internal = true; $this->render = false; // get the service that is calling me, if the object was created from inside a service $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $file = isset($trace[0]['file']) ? $trace[0]['file'] : ""; if(php::endsWith($file, "service.php")) $this->service = basename(dirname($file)); // select the default layout $this->layout = "email_default.tpl"; } /** * Set the cache in minutes. If no time is passed, default will be 1 year * * @author salvipascual * @param String $cache | year, month, day, number of hours */ public function setCache($cache = "year") { if($cache == "year") $cache = 512640; if($cache == "month") $cache = 43200; if($cache == "week") $cache = 10080; if($cache == "day") $cache = 1440; $this->cache = $cache; } /** * Set the subject for the response * * @author salvipascual * @param String $subject */ public function setResponseSubject($subject) { $this->subject = $subject; } /** * Set the email of the response in the cases where is not the same as the requestor * Useful for confirmations or for programmers to track actions/errors on their services * * @author salvipascual * @param String $email */ public function setResponseEmail($email) { $this->email = $email; } /** * Set the layout of the response * * @author salvipascual * @param String $layout, empty to set default layout */ public function setEmailLayout($layout) { $di = \Phalcon\DI\FactoryDefault::getDefault(); $wwwroot = $di->get('path')['root']; // check if a public layout is passed $file = "$wwwroot/app/layouts/$layout"; if(file_exists($file)) $this->layout = $file; // else, check if is a service layout else { $file = Utils::getPathToService($this->service) . "/layouts/$layout"; if(file_exists($file)) $this->layout = $file; } } /** * Build an HTML template response based on a text passed by the user * * @author salvipascual * @param String, $text * @param String, $code, error code if exist * @param String, $message, error message if exist */ public function createFromText($text, $code="OK", $message="") { $this->template = "message.tpl"; $this->content = ["code"=>$code, "message"=>$message, "text"=>$text]; $this->internal = true; $this->render = true; return $this; } /** * Receives a JSON text to be sent back by email. Used for email APIs * * @author salvipascual * @param String, $json */ public function createFromJSON($json) { $this->json = $json; $this->internal = true; $this->render = true; return $this; } /** * Build an HTML template from a set of variables and a template name passed by the user * * @author salvipascual * @param String $template, name of the file in the template folder * @param String[] $content, in the way ["key"=>"var"] * @param String[] $images, paths to the images to embeb * @param String[] $attachments, paths to the files to attach */ public function createFromTemplate($template, $content, $images=[], $attachments=[]) { if(empty($content['code'])) $content['code'] = "ok"; // for the API $this->template = $template; $this->content = $content; $this->images = $images; $this->attachments = $attachments; $this->internal = false; $this->render = true; return $this; } }
gpl-3.0
NLeSC/eEcology-Classification
src/main/java/nl/esciencecenter/eecology/classification/segmentloading/GpsRecord.java
5209
package nl.esciencecenter.eecology.classification.segmentloading; import java.util.ArrayList; import java.util.List; import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonIgnore; public class GpsRecord { private int deviceId; private DateTime timeStamp; private int firstIndex; private boolean hasFirstIndex; private double longitude; private double latitude; private double altitude; private double gpsSpeed; private List<Measurement> measurements; private boolean isLabeled; private int label; private double pressure; private double temperature; private int satellitesUsed; private double gpsFixTime; private double speed2d; private double speed3d; private double direction; private double altitudeAboveGround; /** * Constructor only used for deserialization. */ @SuppressWarnings("unused") private GpsRecord() { } public GpsRecord(List<IndependentMeasurement> measurements) { this.measurements = new ArrayList<Measurement>(); if (measurements.size() > 0 && measurements.get(0).hasIndex()) { setFirstIndex(measurements.get(0).getIndex()); } for (IndependentMeasurement independentMeasurement : measurements) { this.measurements.add(new Measurement(independentMeasurement)); } } public GpsRecord(int deviceId, DateTime timeStamp) { this.deviceId = deviceId; this.timeStamp = timeStamp; } public GpsRecord(GpsRecordDto gpsRecordDto) { setDeviceId(gpsRecordDto.getDeviceId()); setTimeStamp(new DateTime(gpsRecordDto.getTimeStamp())); setLatitude(gpsRecordDto.getLatitude()); setLongitude(gpsRecordDto.getLongitude()); setAltitude(gpsRecordDto.getAltitude()); setPressure(gpsRecordDto.getPressure()); setTemperature(gpsRecordDto.getTemperature()); setSatellitesUsed(gpsRecordDto.getSatellitesUsed()); setGpsFixTime(gpsRecordDto.getGpsFixTime()); setSpeed2d(gpsRecordDto.getSpeed2d()); setSpeed3d(gpsRecordDto.getSpeed3d()); setAltitudeAboveGround(gpsRecordDto.getAltitudeAboveGround()); } public boolean hasFirstIndex() { return hasFirstIndex; } public int getFirstIndex() { return firstIndex; } public void setFirstIndex(int firstIndex) { this.firstIndex = firstIndex; hasFirstIndex = true; } public int getDeviceId() { return deviceId; } public void setDeviceId(int deviceId) { this.deviceId = deviceId; } public DateTime getTimeStamp() { return timeStamp; } public void setTimeStamp(DateTime timeStamp) { this.timeStamp = timeStamp; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getAltitude() { return altitude; } public void setAltitude(double altitude) { this.altitude = altitude; } public double getGpsSpeed() { return gpsSpeed; } public void setGpsSpeed(double gpsSpeed) { this.gpsSpeed = gpsSpeed; } public double getPressure() { return pressure; } public void setPressure(double pressure) { this.pressure = pressure; } public double getTemperature() { return temperature; } public void setTemperature(double temperature) { this.temperature = temperature; } public int getSatellitesUsed() { return satellitesUsed; } public void setSatellitesUsed(int satellitesUsed) { this.satellitesUsed = satellitesUsed; } public double getGpsFixTime() { return gpsFixTime; } public void setGpsFixTime(double gpsFixTime) { this.gpsFixTime = gpsFixTime; } public double getSpeed2d() { return speed2d; } public void setSpeed2d(double speed2d) { this.speed2d = speed2d; } public double getSpeed3d() { return speed3d; } public void setSpeed3d(double speed3d) { this.speed3d = speed3d; } public double getDirection() { return direction; } public void setDirection(double direction) { this.direction = direction; } public double getAltitudeAboveGround() { return altitudeAboveGround; } public void setAltitudeAboveGround(double altitudeAboveGround) { this.altitudeAboveGround = altitudeAboveGround; } public List<Measurement> getMeasurements() { return measurements; } public void setMeasurements(List<Measurement> measurements) { this.measurements = measurements; } @JsonIgnore public boolean isLabeled() { return isLabeled; } public int getLabel() { return label; } public void setLabel(int label) { this.label = label; isLabeled = true; } }
gpl-3.0
Kloudtek/kloudmake
core/src/main/java/com/kloudtek/kloudmake/resource/intellij/Idea.java
350
/* * Copyright (c) 2015. Kelewan Technologies Ltd */ package com.kloudtek.kloudmake.resource.intellij; import com.kloudtek.kloudmake.annotation.KMResource; /** * Created with IntelliJ IDEA. * User: yannick * Date: 19/07/13 * Time: 18:24 * To change this template use File | Settings | File Templates. */ @KMResource public class Idea { }
gpl-3.0
jonasfj/PeTe
PetriEngine/Reachability/BreadthFirstReachabilitySearch.cpp
3172
/* PeTe - Petri Engine exTremE * Copyright (C) 2011 Jonas Finnemann Jensen <jopsen@gmail.com>, * Thomas Søndersø Nielsen <primogens@gmail.com>, * Lars Kærlund Østergaard <larsko@gmail.com>, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "BreadthFirstReachabilitySearch.h" #include "../PQL/PQL.h" #include "../PQL/Contexts.h" #include "../Structures/StateSet.h" #include "../Structures/StateAllocator.h" #include <list> #include <string.h> using namespace PetriEngine::PQL; using namespace PetriEngine::Structures; namespace PetriEngine{ namespace Reachability { ReachabilityResult BreadthFirstReachabilitySearch::reachable(const PetriNet &net, const MarkVal *m0, const VarVal *v0, PQL::Condition *query){ //Do we initially satisfy query? if(query->evaluate(PQL::EvaluationContext(m0, v0))) return ReachabilityResult(ReachabilityResult::Satisfied, "A state satisfying the query was found"); //Create StateSet StateSet states(net); std::list<State*> queue; StateAllocator<1000000> allocator(net); State* s0 = allocator.createState(); memcpy(s0->marking(), m0, sizeof(MarkVal)*net.numberOfPlaces()); memcpy(s0->valuation(), v0, sizeof(VarVal)*net.numberOfVariables()); queue.push_back(s0); unsigned int max = 0; int count = 0; BigInt expandedStates = 0; BigInt exploredStates = 0; State* ns = allocator.createState(); while(!queue.empty()){ // Progress reporting and abort checking if(count++ & 1<<17){ if(queue.size() > max) max = queue.size(); count = 0; // Report progress reportProgress((double)(max - queue.size())/(double)max); // Check abort if(abortRequested()) return ReachabilityResult(ReachabilityResult::Unknown, "Search was aborted."); } State* s = queue.front(); queue.pop_front(); for(unsigned int t = 0; t < net.numberOfTransitions(); t++){ if(net.fire(t, s, ns)){ if(states.add(ns)){ exploredStates++; ns->setParent(s); ns->setTransition(t); if(query->evaluate(*ns)){ //ns->dumpTrace(net); return ReachabilityResult(ReachabilityResult::Satisfied, "A state satisfying the query was found", expandedStates, exploredStates, ns->pathLength(), ns->trace()); } queue.push_back(ns); ns = allocator.createState(); } } } expandedStates++; } return ReachabilityResult(ReachabilityResult::NotSatisfied, "No state satisfying the query exists.", expandedStates, exploredStates); } }}
gpl-3.0
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/SceneEvents.cs
226
using CP77.CR2W.Reflection; namespace CP77.CR2W.Types { [REDMeta] public class SceneEvents : VehicleEventsTransition { public SceneEvents(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
gpl-3.0
andrewngu/sound-redux
client/src/utils/NumberUtils.js
448
export const addCommas = (i) => { if (i === null || i === undefined) { return ''; } return i.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); }; const padZero = (num, size) => { let s = String(num); while (s.length < size) { s = `0${s}`; } return s; }; export const formatSeconds = (num) => { const minutes = padZero(Math.floor(num / 60), 2); const seconds = padZero(num % 60, 2); return `${minutes}:${seconds}`; };
gpl-3.0
fisty256/Yoko
build.py
3735
from build_config import BUILD_FILES, FORCED_FILES, COMPILER_COMMANDS, LINKER_COMMAND, LINKER_OUT, BEGIN_COMMANDS, FINISH_COMMANDS, SMART_DETECT from pyout import raw_print, color_print, colors from file_change_checker import has_file_changed, update_file_cache from dep_tree import DEPENDENCY_TREE import glob, os, os.path, filecmp, shutil, sys, time start_time = time.time() files = [] requested_files = [] checked_files = [] #Run begin commands for command in BEGIN_COMMANDS: if os.system(command) != 0: color_print("Cannot run begin commands.", colors['red']) sys.exit(-1) #Discover the files raw_print("Discovering files...", color=colors['yellow']) for file_type in BUILD_FILES: for file in glob.glob(file_type): files.append(file) for file in BUILD_FILES: if not '*' in file: files.append(file) if len(files) < 1: color_print("No files found.", colors['blue']) color_print("Done.", colors['green']) #Check file dependencies raw_print("Checking dependencies...", color=colors['yellow']) def get_file_deps(file): if file in DEPENDENCY_TREE: return DEPENDENCY_TREE[file] for file in files: old_size = 0 deps = [ file ] new_deps = [] while len(deps) > 0: if not deps[0] in checked_files: checked_files.append(deps[0]) add_deps = get_file_deps(deps[0]) deps += add_deps new_deps += add_deps deps.pop(0) should_rebuild = False for dep in new_deps: if has_file_changed(dep): should_rebuild = True if should_rebuild: requested_files.append(file) color_print("Done.", color=colors['green']) #Build the files compiled_files = [] def compile(file, simple_message = True): if simple_message: raw_print("Compiling...", color=colors['yellow']) else: raw_print("Compiling " + file + "...", color=colors['yellow']) exit = os.system(COMPILER_COMMANDS[extension.replace('.', '')].replace('%FILE%', file)) if exit == 0: color_print("Done.", colors['green']) else: color_print("Failed!", colors['red']) sys.exit(-1) compiled_files.append(file) for file in files: name, extension = os.path.splitext(file) if not extension.replace('.', '') in COMPILER_COMMANDS: color_print("Can't compile " + file + ". Compiler command not found.", colors['red']) break if SMART_DETECT: raw_print("Checking '" + file + "'...", color=colors['yellow']) checked_files.append(file) if file in FORCED_FILES: raw_print("Forced.", color=colors['yellow']) compile(file) elif file in requested_files: raw_print("Requested.", color=colors['yellow']) compile(file) else: if has_file_changed(file): raw_print("Changed.", color=colors['yellow']) compile(file) else: color_print("Ignored.", colors['green']) else: compile(file, False) #Update the file cache update_file_cache(checked_files) #Link the output files if len(files) > 0: if len(compiled_files) > 0 or not os.path.isfile(LINKER_OUT): raw_print("Linking...", color=colors['yellow']) os.system(LINKER_COMMAND) color_print("Done.", colors['green']) else: color_print("Linking not required.", colors['blue']) #Run finish commands for command in FINISH_COMMANDS: if os.system(command) != 0: color_print("Cannot run finish commands.", colors['red']) sys.exit(-1) #Print the execution time color_print("Finished in " + str(round(time.time() - start_time, 2)) + " seconds.", colors['blue'])
gpl-3.0
UniCEUB-Web-Development-2016/Pedro-Henrique-Folador
Location/control/ResourceController.php
1182
<?php include_once "model/Request.php"; include_once "control/UserController.php"; include_once "control/AcademicController.php"; include_once "control/ExperienceController.php"; include_once "control/EnderecoController.php"; include_once "control/ExperienceChartController.php"; class ResourceController { private $controlMap = [ "experience" => "ExperienceController", "experienceChart" => "ExperienceChartController", "user" => "UserController", "academic" => "AcademicController", "endereco" => "EnderecoController", ]; public function createResource($request) { return (new $this->controlMap[$request->get_resource()]())->register($request); } public function searchResource($request) { return (new $this->controlMap[$request->get_resource()]())->search($request); } public function updateResource($request) { return (new $this->controlMap[$request->get_resource()]())->update($request); } public function deleteResource($request) { return (new $this->controlMap[$request->get_resource()]())->delete($request); } }
gpl-3.0
pwizard2/robojournal
ui/exportmulti.cpp
7516
/* This file is part of RoboJournal. Copyright (c) 2013 by Will Kraft <pwizard@gmail.com>. RoboJournal 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. RoboJournal 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 RoboJournal. If not, see <http://www.gnu.org/licenses/>. Class description / purpose: The ExportMulti class creates the "Export entire journal" page in the EntryExporter class window and is responsible for passing all necessary form data back to the ExtryExporter container class. --Will Kraft (8/3/13). */ #include "exportmulti.h" #include "ui_exportmulti.h" #include <QDir> #include <QFileDialog> #include <QPushButton> #include <QIcon> #include <QMessageBox> #include <QDateTime> #include "core/buffer.h" #ifdef _WIN32 #include <windows.h> #endif //QString ExportMulti::folder_name; QString ExportMulti::path; QString ExportMulti::filename; bool ExportMulti::use_html; bool ExportMulti::sort_asc; bool ExportMulti::no_merge; //################################################################################################ ExportMulti::ExportMulti(QWidget *parent) : QWidget(parent), ui(new Ui::ExportMulti) { ui->setupUi(this); PrimaryConfig(); } //################################################################################################ ExportMulti::~ExportMulti() { delete ui; } //################################################################################################ // Load current form data into class buffer. --Will Kraft (8/3/13). void ExportMulti::HarvestValues(){ ExportMulti::path=ui->ExportLocation->text(); ExportMulti::filename=ui->FileName->text(); ExportMulti::use_html=ui->HTML->isChecked(); ExportMulti::sort_asc=ui->SortAscending->isChecked(); if(ui->ExportLooseFiles->isChecked()){ ExportMulti::no_merge=true; } else{ ExportMulti::no_merge=false; } } //################################################################################################ // setup form when PrimaryConfigis called void ExportMulti::PrimaryConfig(){ using namespace std; // mass export tab ui->HTML->click(); ui->SortDescending->click(); ui->IncludeExportDate->click(); // add filename and journal name QString homepath=QDir::homePath(); // check for the presence of a ~/Documents folder on Unix. If we find one, use it. #ifdef unix QString documents=homepath+"/Documents"; QDir docs(documents); if(docs.exists()){ homepath=documents; } #endif // add special Windows pathname instructions for Documents folder. Get windows version b/c XP doesn't have a Documents folder. #ifdef _WIN32 DWORD dwVersion = GetVersion(); DWORD dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); homepath=homepath.replace("/","\\"); //Windows XP and older if(dwMajorVersion < 6){ homepath=homepath+QDir::separator()+"My Documents"; } // Windows Vista & newer else{ homepath=homepath+QDir::separator()+"Documents"; } #endif ui->ExportLocation->setText(homepath); ui->ExportLocation->setReadOnly(true); // set filename SetMassName(); } //################################################################################################ // Show folder selection dialog when user chooses output directory void ExportMulti::Browse(){ QString outputdir=QFileDialog::getExistingDirectory(this, "Select Directory",ui->ExportLocation->text(),QFileDialog::ShowDirsOnly); // only copy the directory to the ExportLocation field if the size is greater than 0. // if the user cancels the QFileDialog, the size WILL be 0 and we don't want this to be blank. if(outputdir.length() != 0){ QFileInfo p(outputdir); if(p.isWritable()){ ui->ExportLocation->clear(); ui->ExportLocation->setText(outputdir); } else{ QMessageBox m; m.critical(this,"RoboJournal","You are not allowed to save files in <b>" + outputdir +"</b>! Please select a different location and try again."); // Browse for another directory outputdir.clear(); Browse(); } } } //################################################################################################ // Set filename for Mass export void ExportMulti::SetMassName(){ if(!ui->ExportLooseFiles->isChecked()){ QString extension; if(ui->HTML->isChecked()){ extension=".html"; } else{ extension=".txt"; } QDateTime t=QDateTime::currentDateTime(); QString datestamp; switch(Buffer::date_format){ case 0: datestamp=t.toString("dd-MM-yyyy"); break; case 1: datestamp=t.toString("MM-dd-yyyy"); break; case 2: datestamp=t.toString("yyyy-MM-dd"); break; } QString filename; if(ui->IncludeExportDate->isChecked()){ filename=Buffer::database_name + "_" + datestamp + extension; } else{ filename=Buffer::database_name + extension; } ui->FileName->setText(filename); } } //################################################################################################ void ExportMulti::on_BrowseButton_clicked() { Browse(); } //################################################################################################ void ExportMulti::on_HTML_clicked() { SetMassName(); } //################################################################################################ void ExportMulti::on_PlainText_clicked() { SetMassName(); } //################################################################################################ void ExportMulti::on_IncludeExportDate_clicked() { SetMassName(); } //################################################################################################ void ExportMulti::on_ExportLooseFiles_toggled(bool checked) { if(checked){ ui->FileName->setDisabled(true); ui->SortAscending->setDisabled(true); ui->SortDescending->setDisabled(true); ui->PermitName->setDisabled(true); ui->IncludeExportDate->setDisabled(true); } else{ ui->FileName->setDisabled(false); ui->SortAscending->setDisabled(false); ui->SortDescending->setDisabled(false); ui->PermitName->setDisabled(false); ui->IncludeExportDate->setDisabled(false); } } //################################################################################################ void ExportMulti::on_PermitName_toggled(bool checked) { if(checked){ ui->FileName->setReadOnly(false); ui->FileName->setFocus(); } else{ ui->FileName->setReadOnly(true); ui->FileName->clearFocus(); SetMassName(); } }
gpl-3.0
solar3s/goregen
regenbox/regenbox_test.go
1065
package regenbox import ( "sync" "testing" "time" ) var rb *RegenBox var once sync.Once func testAutoConnect(tb testing.TB) *RegenBox { if rb != nil { return rb } var err error rb, err = NewRegenBox(nil, nil) if err != nil { tb.Skip(err) } return rb } func TestRegenBox_LedToggle(t *testing.T) { rbx := testAutoConnect(t) defer rbx.Stop() t.Log("blinking led...") b0, err := rbx.LedToggle() if err != nil { t.Fatal(err) } for i := 0; i < 5; i++ { b, err := rbx.LedToggle() if err != nil { t.Fatal(err) } if b == b0 { t.Error("wrong return value for LedToggle()") } b0 = b time.Sleep(time.Millisecond * 500) } } func BenchmarkReadVoltage(b *testing.B) { rbx := testAutoConnect(b) defer rbx.Stop() once.Do(func() { b.Logf("using firmware: %s", rbx.FirmwareVersion()) }) var total int for n := 0; n < b.N; n++ { i, err := rbx.ReadVoltage() time.Sleep(time.Millisecond * 2) if err != nil { b.Error(b.N, err) } total += i } b.Logf("b.N: %d", b.N) b.Logf("average voltage: %d", total/b.N) }
gpl-3.0
SuperMap-iDesktop/SuperMap-iDesktop-Cross
WorkflowView/src/main/java/com/supermap/desktop/WorkflowView/graphics/storage/IConnectionManager.java
1794
package com.supermap.desktop.WorkflowView.graphics.storage; import com.supermap.desktop.WorkflowView.graphics.GraphCanvas; import com.supermap.desktop.WorkflowView.graphics.connection.IConnectable; import com.supermap.desktop.WorkflowView.graphics.connection.IGraphConnection; import com.supermap.desktop.WorkflowView.graphics.events.ConnectionAddedListener; import com.supermap.desktop.WorkflowView.graphics.events.ConnectionRemovedListener; import com.supermap.desktop.WorkflowView.graphics.events.ConnectionRemovingListener; import com.supermap.desktop.WorkflowView.graphics.graphs.IGraph; /** * Created by highsad on 2017/4/5. */ public interface IConnectionManager { GraphCanvas getCanvas(); IGraphConnection[] getConnections(); void connect(IConnectable start, IConnectable end); void connect(IConnectable start, IConnectable end, String message); void connect(IGraphConnection connection); void removeConnection(IConnectable connectable); void removeConnection(IGraph connector); void removeConnection(IGraphConnection connection); IGraph[] getPreGraphs(IGraph end); IGraph[] getNextGraphs(IGraph start); boolean isConnectedAsStart(IGraph start); boolean isConnectedAsEnd(IGraph end); boolean isConnected(IConnectable connectable1, IConnectable connectable2); boolean isConnected(IGraph graph1, IGraph graph2); void addConnectionAddedListener(ConnectionAddedListener listener); void removeConnectionAddedListener(ConnectionAddedListener listener); void addConnectionRemovingListener(ConnectionRemovingListener listener); void removeConnectionRemovingListener(ConnectionRemovingListener listener); void addConnectionRemovedListener(ConnectionRemovedListener listener); void removeConnectionRemovedListener(ConnectionRemovedListener listener); }
gpl-3.0
apruden/opal
opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/magma/importdata/view/JdbcStepView.java
1657
/******************************************************************************* * Copyright (c) 2012 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.web.gwt.app.client.magma.importdata.view; import org.obiba.opal.web.gwt.app.client.js.JsArrays; import org.obiba.opal.web.gwt.app.client.magma.importdata.presenter.JdbcStepPresenter; import org.obiba.opal.web.model.client.database.DatabaseDto; import com.google.gwt.core.client.JsArray; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.gwtplatform.mvp.client.ViewImpl; public class JdbcStepView extends ViewImpl implements JdbcStepPresenter.Display { @UiField ListBox database; interface Binder extends UiBinder<Widget, JdbcStepView> {} @Override public void setDatabases(JsArray<DatabaseDto> resource) { database.clear(); for(DatabaseDto dto : JsArrays.toIterable(resource)) { database.addItem(dto.getName()); } } @Override public String getSelectedDatabase() { return database.getItemText(database.getSelectedIndex()); } @Inject public JdbcStepView(Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); } }
gpl-3.0
XSquareOrg/XS-core
src/vec/vec3.hpp
3618
/* ------------------------------------------------------------------------ * * XSquare 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 version 3 of the Licence, or * * (at your option) any later version. * * * * XSquare is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * General Public License for more details. * * * * You should have received copies of the GNU General Public License and * * the GNU Lesser General Public License along with this program. If * * not, see http://www.gnu.org/licenses/. * * ------------------------------------------------------------------------- */ #ifndef XS_CORE_VEC3__ #define XS_CORE_VEC3__ #include "../simd/mm3.hpp" namespace xs_core { class Vec3i; class Vec3f; template <class NUM, class T> class _V3Base { // Mixin to provide funcs common to Vec3f and Vec3i public: }; class Vec3f: public _V3Base<Vec3f, float>, public mm3f<Vec3f> { public: operator Vec3i(); operator const Vec3i(); Vec3f abs(void); Vec3f operator-() { // negation this->u.data.a[0] = -this->u.data.a[0]; this->u.data.a[1] = -this->u.data.a[1]; this->u.data.a[2] = -this->u.data.a[2]; return *this; } float distance(const Vec3f v) { float3u u; __m128 m = _mm_sub_ps(this->u.data.v, v.u.data.v); m = _mm_mul_ps(m, m); u.data.v = m; return sqrt(u.hadd()); // return sqrt(_hadd4f(m)); } Vec3f operator+=(const Vec3f v) { __m128 m = _mm_add_ps(this->u.data.v, v.u.data.v); u.data.v = m; return *this; } Vec3f operator-=(const Vec3f v) { __m128 m = _mm_sub_ps(this->u.data.v, v.u.data.v); u.data.v = m; return *this; } Vec3f operator*=(const Vec3f v) { __m128 m = _mm_mul_ps(this->u.data.v, v.u.data.v); u.data.v = m; return *this; } }; class Vec3i: public _V3Base<Vec3i, int>, public mm3i<Vec3i> { public: operator Vec3i(); operator const Vec3i(); Vec3i abs(void); Vec3i operator-() { // negation this->u.data.a[0] = -this->u.data.a[0]; this->u.data.a[1] = -this->u.data.a[1]; this->u.data.a[2] = -this->u.data.a[2]; return *this; } int distance(const Vec3i v) { int3u u; __m128i m = _mm_sub_epi32(this->u.data.v, v.u.data.v); // m = _mm_mul_epi32(m, m); // FIXME error _mm_mul_epi32 was not declared in this scope u.data.v = m; // workaround for _mm_mul_epi32 -- multiply each axis individually u.data.a[0] *= u.data.a[0]; u.data.a[1] *= u.data.a[1]; u.data.a[2] *= u.data.a[2]; return sqrt(u.hadd()); // return sqrt(_hadd4i(m)); } Vec3i operator+=(const Vec3i v) { __m128i m = _mm_add_epi32(this->u.data.v, v.u.data.v); u.data.v = m; return *this; } Vec3i operator-=(const Vec3i v) { __m128i m = _mm_sub_epi32(this->u.data.v, v.u.data.v); u.data.v = m; return *this; } }; } // xs_core #endif // XS_CORE_Vec3__
gpl-3.0
DRE2N/FactionsXL
src/main/java/de/erethon/factionsxl/command/TagCommand.java
2408
/* * Copyright (c) 2017-2019 Daniel Saukel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.erethon.factionsxl.command; import de.erethon.factionsxl.FactionsXL; import de.erethon.factionsxl.config.FMessage; import de.erethon.factionsxl.faction.Faction; import de.erethon.factionsxl.player.FPermission; import de.erethon.factionsxl.util.ParsingUtil; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * @author Daniel Saukel */ public class TagCommand extends FCommand { FactionsXL plugin = FactionsXL.getInstance(); public TagCommand() { setCommand("tag"); setAliases("setTag", "name", "setName"); setMinArgs(1); setMaxArgs(2); setHelp(FMessage.HELP_TAG.getMessage()); setPermission(FPermission.TAG.getNode()); setPlayerCommand(true); setConsoleCommand(true); } @Override public void onExecute(String[] args, CommandSender sender) { i = 1; Faction faction = null; if (args.length == 3) { faction = getSenderFactionOrFromArg(sender, args, 1, true); if (faction == null) { return; } } else { faction = getSenderFaction(sender); if (faction == null) { ParsingUtil.sendMessage(sender, FMessage.ERROR_SPECIFY_FACTION.getMessage()); return; } } if (sender instanceof Player && !faction.isAdmin(sender)) { ParsingUtil.sendMessage(sender, FMessage.ERROR_NO_PERMISSION.getMessage()); return; } String tag = args[i].replace("&", new String()); ParsingUtil.broadcastMessage(FMessage.CMD_TAG_SUCCESS.getMessage(), faction, tag); faction.setName(tag); } }
gpl-3.0
AuScope/ABIN-Portal
src/main/webapp/js/cswthemefilter/components/BaseComponent.js
1697
Ext.namespace("CSWThemeFilter"); /** * The 'abstract' base component for all CSWThemeFilterForm components to extend from */ CSWThemeFilter.BaseComponent = Ext.extend(Ext.form.FieldSet, { /** * An instance of GMap2 */ map : null, /** * Constructor for this class, accepts all configuration options that can * be specified for a Ext.form.FieldSet as well as the following extensions * { * map : [Required] A google map GMap2 instance * } */ constructor : function(cfg) { this.map = cfg.map; Ext.apply(cfg, { autoDestroy : true, //Ensure that as components get removed they are also destroyed isBaseComponent : true //how we identify base components }, { collapsed : true, style:'padding:5px 10px 0px 10px' }); CSWThemeFilter.BaseComponent.superclass.constructor.call(this, cfg); }, /** * Gets the filterValues configured by this component as a plain * old javascript object/dictionary * * Should be overriden by subclasses. */ getFilterValues : function() { return {}; }, /** * Gets whether this component supports the specified theme. Returns a boolean value * * If true is returned this component will be displayed whilst the theme is selected. * If false is returned this component will be hidden whilst the them is selected. * * Should be overriden by subclasses. */ supportsTheme : function(urn) { if (!urn) { return false; } return true; } });
gpl-3.0
lsaffre/commondata-be
commondata/be/places.py
1718
# -*- coding: UTF-8 -*- # Copyright 2014 Luc Saffre # License: BSD (see file COPYING for details) from __future__ import unicode_literals from __future__ import print_function from commondata.utils import Place, PlaceGenerator class PlaceInBelgium(Place): def __unicode__(self): return self.fr class Country(PlaceInBelgium): value = 0 class Region(PlaceInBelgium): value = 1 class Province(PlaceInBelgium): value = 2 class City(PlaceInBelgium): value = 3 class Village(City): value = 4 class Township(City): # "Section" d'une commune, "Stadtteil" value = 4 def root(): pg = PlaceGenerator() pg.install(Country, Region, Province, City, Village, Township) pg.set_args('fr nl de en') belgium = pg.country("Belgique", "België", "Belgien", "Belgium") pg.region("Bruxelles", "Brussel", "Brüssel", "Brussels") from .brussels import populate ; populate(pg) pg.set_args('fr nl de en') pg.region( "Région flamande", "Vlaams Gewest", "Flandern", "Flemish Region") from .antwerpen import populate ; populate(pg) from .luxembourg import populate ; populate(pg) from .oostvlaanderen import populate ; populate(pg) from .westvlaanderen import populate ; populate(pg) from .vlaamsbrabant import populate ; populate(pg) pg.set_args('fr nl de en') pg.region( "Région wallonne", "Wallonië", "Wallonische Region", "Wallonia") from .namur import populate ; populate(pg) from .liege import populate ; populate(pg) from .hainaut import populate ; populate(pg) from .limburg import populate ; populate(pg) from .brabantwallon import populate ; populate(pg) return belgium
gpl-3.0
uhoreg/moodle
lib/yui/3.4.1pr1/build/attribute-base/attribute-base.js
45509
/* YUI 3.4.1pr1 (build 4097) Copyright 2011 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('attribute-base', function(Y) { /** * The State class maintains state for a collection of named items, with * a varying number of properties defined. * * It avoids the need to create a separate class for the item, and separate instances * of these classes for each item, by storing the state in a 2 level hash table, * improving performance when the number of items is likely to be large. * * @constructor * @class State */ Y.State = function() { /** * Hash of attributes * @property data */ this.data = {}; }; Y.State.prototype = { /** * Adds a property to an item. * * @method add * @param name {String} The name of the item. * @param key {String} The name of the property. * @param val {Any} The value of the property. */ add : function(name, key, val) { var d = this.data; d[key] = d[key] || {}; d[key][name] = val; }, /** * Adds multiple properties to an item. * * @method addAll * @param name {String} The name of the item. * @param o {Object} A hash of property/value pairs. */ addAll: function(name, o) { var key; for (key in o) { if (o.hasOwnProperty(key)) { this.add(name, key, o[key]); } } }, /** * Removes a property from an item. * * @method remove * @param name {String} The name of the item. * @param key {String} The property to remove. */ remove: function(name, key) { var d = this.data; if (d[key] && (name in d[key])) { delete d[key][name]; } }, /** * Removes multiple properties from an item, or remove the item completely. * * @method removeAll * @param name {String} The name of the item. * @param o {Object|Array} Collection of properties to delete. If not provided, the entire item is removed. */ removeAll: function(name, o) { var d = this.data; Y.each(o || d, function(v, k) { if(Y.Lang.isString(k)) { this.remove(name, k); } else { this.remove(name, v); } }, this); }, /** * For a given item, returns the value of the property requested, or undefined if not found. * * @method get * @param name {String} The name of the item * @param key {String} Optional. The property value to retrieve. * @return {Any} The value of the supplied property. */ get: function(name, key) { var d = this.data; return (d[key] && name in d[key]) ? d[key][name] : undefined; }, /** * For the given item, returns a disposable object with all of the * item's property/value pairs. * * @method getAll * @param name {String} The name of the item * @return {Object} An object with property/value pairs for the item. */ getAll : function(name) { var d = this.data, o; Y.each(d, function(v, k) { if (name in d[k]) { o = o || {}; o[k] = v[name]; } }, this); return o; } }; /** * The attribute module provides an augmentable Attribute implementation, which * adds configurable attributes and attribute change events to the class being * augmented. It also provides a State class, which is used internally by Attribute, * but can also be used independently to provide a name/property/value data structure to * store state. * * @module attribute */ /** * The attribute-base submodule provides core attribute handling support, with everything * aside from complex attribute handling in the provider's constructor. * * @module attribute * @submodule attribute-base */ var O = Y.Object, Lang = Y.Lang, EventTarget = Y.EventTarget, DOT = ".", CHANGE = "Change", // Externally configurable props GETTER = "getter", SETTER = "setter", READ_ONLY = "readOnly", WRITE_ONCE = "writeOnce", INIT_ONLY = "initOnly", VALIDATOR = "validator", VALUE = "value", VALUE_FN = "valueFn", BROADCAST = "broadcast", LAZY_ADD = "lazyAdd", BYPASS_PROXY = "_bypassProxy", // Used for internal state management ADDED = "added", INITIALIZING = "initializing", INIT_VALUE = "initValue", PUBLISHED = "published", DEF_VALUE = "defaultValue", LAZY = "lazy", IS_LAZY_ADD = "isLazyAdd", INVALID_VALUE, MODIFIABLE = {}; // Properties which can be changed after the attribute has been added. MODIFIABLE[READ_ONLY] = 1; MODIFIABLE[WRITE_ONCE] = 1; MODIFIABLE[GETTER] = 1; MODIFIABLE[BROADCAST] = 1; /** * <p> * Attribute provides configurable attribute support along with attribute change events. It is designed to be * augmented on to a host class, and provides the host with the ability to configure attributes to store and retrieve state, * along with attribute change events. * </p> * <p>For example, attributes added to the host can be configured:</p> * <ul> * <li>As read only.</li> * <li>As write once.</li> * <li>With a setter function, which can be used to manipulate * values passed to Attribute's <a href="#method_set">set</a> method, before they are stored.</li> * <li>With a getter function, which can be used to manipulate stored values, * before they are returned by Attribute's <a href="#method_get">get</a> method.</li> * <li>With a validator function, to validate values before they are stored.</li> * </ul> * * <p>See the <a href="#method_addAttr">addAttr</a> method, for the complete set of configuration * options available for attributes</p>. * * <p><strong>NOTE:</strong> Most implementations will be better off extending the <a href="Base.html">Base</a> class, * instead of augmenting Attribute directly. Base augments Attribute and will handle the initial configuration * of attributes for derived classes, accounting for values passed into the constructor.</p> * * @class Attribute * @param attrs {Object} The attributes to add during construction (passed through to <a href="#method_addAttrs">addAttrs</a>). These can also be defined on the constructor being augmented with Attribute by defining the ATTRS property on the constructor. * @param values {Object} The initial attribute values to apply (passed through to <a href="#method_addAttrs">addAttrs</a>). These are not merged/cloned. The caller is responsible for isolating user provided values if required. * @param lazy {boolean} Whether or not to add attributes lazily (passed through to <a href="#method_addAttrs">addAttrs</a>). * @uses EventTarget */ function Attribute(attrs, values, lazy) { var host = this; // help compression // Perf tweak - avoid creating event literals if not required. host._ATTR_E_FACADE = {}; EventTarget.call(host, {emitFacade:true}); // _conf maintained for backwards compat host._conf = host._state = new Y.State(); host._stateProxy = host._stateProxy || null; host._requireAddAttr = host._requireAddAttr || false; this._initAttrs(attrs, values, lazy); } /** * <p>The value to return from an attribute setter in order to prevent the set from going through.</p> * * <p>You can return this value from your setter if you wish to combine validator and setter * functionality into a single setter function, which either returns the massaged value to be stored or * Attribute.INVALID_VALUE to prevent invalid values from being stored.</p> * * @property INVALID_VALUE * @type Object * @static * @final */ Attribute.INVALID_VALUE = {}; INVALID_VALUE = Attribute.INVALID_VALUE; /** * The list of properties which can be configured for * each attribute (e.g. setter, getter, writeOnce etc.). * * This property is used internally as a whitelist for faster * Y.mix operations. * * @property _ATTR_CFG * @type Array * @static * @protected */ Attribute._ATTR_CFG = [SETTER, GETTER, VALIDATOR, VALUE, VALUE_FN, WRITE_ONCE, READ_ONLY, LAZY_ADD, BROADCAST, BYPASS_PROXY]; Attribute.prototype = { /** * <p> * Adds an attribute with the provided configuration to the host object. * </p> * <p> * The config argument object supports the following properties: * </p> * * <dl> * <dt>value &#60;Any&#62;</dt> * <dd>The initial value to set on the attribute</dd> * * <dt>valueFn &#60;Function | String&#62;</dt> * <dd> * <p>A function, which will return the initial value to set on the attribute. This is useful * for cases where the attribute configuration is defined statically, but needs to * reference the host instance ("this") to obtain an initial value. If both the value and valueFn properties are defined, * the value returned by the valueFn has precedence over the value property, unless it returns undefined, in which * case the value property is used.</p> * * <p>valueFn can also be set to a string, representing the name of the instance method to be used to retrieve the value.</p> * </dd> * * <dt>readOnly &#60;boolean&#62;</dt> * <dd>Whether or not the attribute is read only. Attributes having readOnly set to true * cannot be modified by invoking the set method.</dd> * * <dt>writeOnce &#60;boolean&#62; or &#60;string&#62;</dt> * <dd> * Whether or not the attribute is "write once". Attributes having writeOnce set to true, * can only have their values set once, be it through the default configuration, * constructor configuration arguments, or by invoking set. * <p>The writeOnce attribute can also be set to the string "initOnly", in which case the attribute can only be set during initialization * (when used with Base, this means it can only be set during construction)</p> * </dd> * * <dt>setter &#60;Function | String&#62;</dt> * <dd> * <p>The setter function used to massage or normalize the value passed to the set method for the attribute. * The value returned by the setter will be the final stored value. Returning * <a href="#property_Attribute.INVALID_VALUE">Attribute.INVALID_VALUE</a>, from the setter will prevent * the value from being stored. * </p> * * <p>setter can also be set to a string, representing the name of the instance method to be used as the setter function.</p> * </dd> * * <dt>getter &#60;Function | String&#62;</dt> * <dd> * <p> * The getter function used to massage or normalize the value returned by the get method for the attribute. * The value returned by the getter function is the value which will be returned to the user when they * invoke get. * </p> * * <p>getter can also be set to a string, representing the name of the instance method to be used as the getter function.</p> * </dd> * * <dt>validator &#60;Function | String&#62;</dt> * <dd> * <p> * The validator function invoked prior to setting the stored value. Returning * false from the validator function will prevent the value from being stored. * </p> * * <p>validator can also be set to a string, representing the name of the instance method to be used as the validator function.</p> * </dd> * * <dt>broadcast &#60;int&#62;</dt> * <dd>If and how attribute change events for this attribute should be broadcast. See CustomEvent's <a href="CustomEvent.html#property_broadcast">broadcast</a> property for * valid values. By default attribute change events are not broadcast.</dd> * * <dt>lazyAdd &#60;boolean&#62;</dt> * <dd>Whether or not to delay initialization of the attribute until the first call to get/set it. * This flag can be used to over-ride lazy initialization on a per attribute basis, when adding multiple attributes through * the <a href="#method_addAttrs">addAttrs</a> method.</dd> * * </dl> * * <p>The setter, getter and validator are invoked with the value and name passed in as the first and second arguments, and with * the context ("this") set to the host object.</p> * * <p>Configuration properties outside of the list mentioned above are considered private properties used internally by attribute, and are not intended for public use.</p> * * @method addAttr * * @param {String} name The name of the attribute. * @param {Object} config An object with attribute configuration property/value pairs, specifying the configuration for the attribute. * * <p> * <strong>NOTE:</strong> The configuration object is modified when adding an attribute, so if you need * to protect the original values, you will need to merge the object. * </p> * * @param {boolean} lazy (optional) Whether or not to add this attribute lazily (on the first call to get/set). * * @return {Object} A reference to the host object. * * @chainable */ addAttr: function(name, config, lazy) { var host = this, // help compression state = host._state, value, hasValue; lazy = (LAZY_ADD in config) ? config[LAZY_ADD] : lazy; if (lazy && !host.attrAdded(name)) { state.add(name, LAZY, config || {}); state.add(name, ADDED, true); } else { if (!host.attrAdded(name) || state.get(name, IS_LAZY_ADD)) { config = config || {}; hasValue = (VALUE in config); if(hasValue) { // We'll go through set, don't want to set value in config directly value = config.value; delete config.value; } config.added = true; config.initializing = true; state.addAll(name, config); if (hasValue) { // Go through set, so that raw values get normalized/validated host.set(name, value); } state.remove(name, INITIALIZING); } } return host; }, /** * Checks if the given attribute has been added to the host * * @method attrAdded * @param {String} name The name of the attribute to check. * @return {boolean} true if an attribute with the given name has been added, false if it hasn't. This method will return true for lazily added attributes. */ attrAdded: function(name) { return !!this._state.get(name, ADDED); }, /** * Updates the configuration of an attribute which has already been added. * <p> * The properties which can be modified through this interface are limited * to the following subset of attributes, which can be safely modified * after a value has already been set on the attribute: readOnly, writeOnce, * broadcast and getter. * </p> * @method modifyAttr * @param {String} name The name of the attribute whose configuration is to be updated. * @param {Object} config An object with configuration property/value pairs, specifying the configuration properties to modify. */ modifyAttr: function(name, config) { var host = this, // help compression prop, state; if (host.attrAdded(name)) { if (host._isLazyAttr(name)) { host._addLazyAttr(name); } state = host._state; for (prop in config) { if (MODIFIABLE[prop] && config.hasOwnProperty(prop)) { state.add(name, prop, config[prop]); // If we reconfigured broadcast, need to republish if (prop === BROADCAST) { state.remove(name, PUBLISHED); } } } } }, /** * Removes an attribute from the host object * * @method removeAttr * @param {String} name The name of the attribute to be removed. */ removeAttr: function(name) { this._state.removeAll(name); }, /** * Returns the current value of the attribute. If the attribute * has been configured with a 'getter' function, this method will delegate * to the 'getter' to obtain the value of the attribute. * * @method get * * @param {String} name The name of the attribute. If the value of the attribute is an Object, * dot notation can be used to obtain the value of a property of the object (e.g. <code>get("x.y.z")</code>) * * @return {Any} The value of the attribute */ get : function(name) { return this._getAttr(name); }, /** * Checks whether or not the attribute is one which has been * added lazily and still requires initialization. * * @method _isLazyAttr * @private * @param {String} name The name of the attribute * @return {boolean} true if it's a lazily added attribute, false otherwise. */ _isLazyAttr: function(name) { return this._state.get(name, LAZY); }, /** * Finishes initializing an attribute which has been lazily added. * * @method _addLazyAttr * @private * @param {Object} name The name of the attribute */ _addLazyAttr: function(name) { var state = this._state, lazyCfg = state.get(name, LAZY); state.add(name, IS_LAZY_ADD, true); state.remove(name, LAZY); this.addAttr(name, lazyCfg); }, /** * Sets the value of an attribute. * * @method set * @chainable * * @param {String} name The name of the attribute. If the * current value of the attribute is an Object, dot notation can be used * to set the value of a property within the object (e.g. <code>set("x.y.z", 5)</code>). * * @param {Any} value The value to set the attribute to. * * @param {Object} opts (Optional) Optional event data to be mixed into * the event facade passed to subscribers of the attribute's change event. This * can be used as a flexible way to identify the source of a call to set, allowing * the developer to distinguish between set called internally by the host, vs. * set called externally by the application developer. * * @return {Object} A reference to the host object. */ set : function(name, val, opts) { return this._setAttr(name, val, opts); }, /** * Resets the attribute (or all attributes) to its initial value, as long as * the attribute is not readOnly, or writeOnce. * * @method reset * @param {String} name Optional. The name of the attribute to reset. If omitted, all attributes are reset. * @return {Object} A reference to the host object. * @chainable */ reset : function(name) { var host = this, // help compression added; if (name) { if (host._isLazyAttr(name)) { host._addLazyAttr(name); } host.set(name, host._state.get(name, INIT_VALUE)); } else { added = host._state.data.added; Y.each(added, function(v, n) { host.reset(n); }, host); } return host; }, /** * Allows setting of readOnly/writeOnce attributes. See <a href="#method_set">set</a> for argument details. * * @method _set * @protected * @chainable * * @param {String} name The name of the attribute. * @param {Any} val The value to set the attribute to. * @param {Object} opts (Optional) Optional event data to be mixed into * the event facade passed to subscribers of the attribute's change event. * @return {Object} A reference to the host object. */ _set : function(name, val, opts) { return this._setAttr(name, val, opts, true); }, /** * Provides the common implementation for the public get method, * allowing Attribute hosts to over-ride either method. * * See <a href="#method_get">get</a> for argument details. * * @method _getAttr * @protected * @chainable * * @param {String} name The name of the attribute. * @return {Any} The value of the attribute. */ _getAttr : function(name) { var host = this, // help compression fullName = name, state = host._state, path, getter, val, cfg; if (name.indexOf(DOT) !== -1) { path = name.split(DOT); name = path.shift(); } // On Demand - Should be rare - handles out of order valueFn references if (host._tCfgs && host._tCfgs[name]) { cfg = {}; cfg[name] = host._tCfgs[name]; delete host._tCfgs[name]; host._addAttrs(cfg, host._tVals); } // Lazy Init if (host._isLazyAttr(name)) { host._addLazyAttr(name); } val = host._getStateVal(name); getter = state.get(name, GETTER); if (getter && !getter.call) { getter = this[getter]; } val = (getter) ? getter.call(host, val, fullName) : val; val = (path) ? O.getValue(val, path) : val; return val; }, /** * Provides the common implementation for the public set and protected _set methods. * * See <a href="#method_set">set</a> for argument details. * * @method _setAttr * @protected * @chainable * * @param {String} name The name of the attribute. * @param {Any} value The value to set the attribute to. * @param {Object} opts (Optional) Optional event data to be mixed into * the event facade passed to subscribers of the attribute's change event. * @param {boolean} force If true, allows the caller to set values for * readOnly or writeOnce attributes which have already been set. * * @return {Object} A reference to the host object. */ _setAttr : function(name, val, opts, force) { var allowSet = true, state = this._state, stateProxy = this._stateProxy, data = state.data, initialSet, strPath, path, currVal, writeOnce, initializing; if (name.indexOf(DOT) !== -1) { strPath = name; path = name.split(DOT); name = path.shift(); } if (this._isLazyAttr(name)) { this._addLazyAttr(name); } initialSet = (!data.value || !(name in data.value)); if (stateProxy && name in stateProxy && !this._state.get(name, BYPASS_PROXY)) { // TODO: Value is always set for proxy. Can we do any better? Maybe take a snapshot as the initial value for the first call to set? initialSet = false; } if (this._requireAddAttr && !this.attrAdded(name)) { } else { writeOnce = state.get(name, WRITE_ONCE); initializing = state.get(name, INITIALIZING); if (!initialSet && !force) { if (writeOnce) { allowSet = false; } if (state.get(name, READ_ONLY)) { allowSet = false; } } if (!initializing && !force && writeOnce === INIT_ONLY) { allowSet = false; } if (allowSet) { // Don't need currVal if initialSet (might fail in custom getter if it always expects a non-undefined/non-null value) if (!initialSet) { currVal = this.get(name); } if (path) { val = O.setValue(Y.clone(currVal), path, val); if (val === undefined) { allowSet = false; } } if (allowSet) { if (initializing) { this._setAttrVal(name, strPath, currVal, val); } else { this._fireAttrChange(name, strPath, currVal, val, opts); } } } } return this; }, /** * Utility method to help setup the event payload and fire the attribute change event. * * @method _fireAttrChange * @private * @param {String} attrName The name of the attribute * @param {String} subAttrName The full path of the property being changed, * if this is a sub-attribute value being change. Otherwise null. * @param {Any} currVal The current value of the attribute * @param {Any} newVal The new value of the attribute * @param {Object} opts Any additional event data to mix into the attribute change event's event facade. */ _fireAttrChange : function(attrName, subAttrName, currVal, newVal, opts) { var host = this, eventName = attrName + CHANGE, state = host._state, facade; if (!state.get(attrName, PUBLISHED)) { host.publish(eventName, { queuable:false, defaultTargetOnly: true, defaultFn:host._defAttrChangeFn, silent:true, broadcast : state.get(attrName, BROADCAST) }); state.add(attrName, PUBLISHED, true); } facade = (opts) ? Y.merge(opts) : host._ATTR_E_FACADE; // Not using the single object signature for fire({type:..., newVal:...}), since // we don't want to override type. Changed to the fire(type, {newVal:...}) signature. // facade.type = eventName; facade.attrName = attrName; facade.subAttrName = subAttrName; facade.prevVal = currVal; facade.newVal = newVal; // host.fire(facade); host.fire(eventName, facade); }, /** * Default function for attribute change events. * * @private * @method _defAttrChangeFn * @param {EventFacade} e The event object for attribute change events. */ _defAttrChangeFn : function(e) { if (!this._setAttrVal(e.attrName, e.subAttrName, e.prevVal, e.newVal)) { // Prevent "after" listeners from being invoked since nothing changed. e.stopImmediatePropagation(); } else { e.newVal = this.get(e.attrName); } }, /** * Gets the stored value for the attribute, from either the * internal state object, or the state proxy if it exits * * @method _getStateVal * @private * @param {String} name The name of the attribute * @return {Any} The stored value of the attribute */ _getStateVal : function(name) { var stateProxy = this._stateProxy; return stateProxy && (name in stateProxy) && !this._state.get(name, BYPASS_PROXY) ? stateProxy[name] : this._state.get(name, VALUE); }, /** * Sets the stored value for the attribute, in either the * internal state object, or the state proxy if it exits * * @method _setStateVal * @private * @param {String} name The name of the attribute * @param {Any} value The value of the attribute */ _setStateVal : function(name, value) { var stateProxy = this._stateProxy; if (stateProxy && (name in stateProxy) && !this._state.get(name, BYPASS_PROXY)) { stateProxy[name] = value; } else { this._state.add(name, VALUE, value); } }, /** * Updates the stored value of the attribute in the privately held State object, * if validation and setter passes. * * @method _setAttrVal * @private * @param {String} attrName The attribute name. * @param {String} subAttrName The sub-attribute name, if setting a sub-attribute property ("x.y.z"). * @param {Any} prevVal The currently stored value of the attribute. * @param {Any} newVal The value which is going to be stored. * * @return {booolean} true if the new attribute value was stored, false if not. */ _setAttrVal : function(attrName, subAttrName, prevVal, newVal) { var host = this, allowSet = true, state = host._state, validator = state.get(attrName, VALIDATOR), setter = state.get(attrName, SETTER), initializing = state.get(attrName, INITIALIZING), prevValRaw = this._getStateVal(attrName), name = subAttrName || attrName, retVal, valid; if (validator) { if (!validator.call) { // Assume string - trying to keep critical path tight, so avoiding Lang check validator = this[validator]; } if (validator) { valid = validator.call(host, newVal, name); if (!valid && initializing) { newVal = state.get(attrName, DEF_VALUE); valid = true; // Assume it's valid, for perf. } } } if (!validator || valid) { if (setter) { if (!setter.call) { // Assume string - trying to keep critical path tight, so avoiding Lang check setter = this[setter]; } if (setter) { retVal = setter.call(host, newVal, name); if (retVal === INVALID_VALUE) { allowSet = false; } else if (retVal !== undefined){ newVal = retVal; } } } if (allowSet) { if(!subAttrName && (newVal === prevValRaw) && !Lang.isObject(newVal)) { allowSet = false; } else { // Store value if (state.get(attrName, INIT_VALUE) === undefined) { state.add(attrName, INIT_VALUE, newVal); } host._setStateVal(attrName, newVal); } } } else { allowSet = false; } return allowSet; }, /** * Sets multiple attribute values. * * @method setAttrs * @param {Object} attrs An object with attributes name/value pairs. * @return {Object} A reference to the host object. * @chainable */ setAttrs : function(attrs, opts) { return this._setAttrs(attrs, opts); }, /** * Implementation behind the public setAttrs method, to set multiple attribute values. * * @method _setAttrs * @protected * @param {Object} attrs An object with attributes name/value pairs. * @return {Object} A reference to the host object. * @chainable */ _setAttrs : function(attrs, opts) { for (var attr in attrs) { if ( attrs.hasOwnProperty(attr) ) { this.set(attr, attrs[attr]); } } return this; }, /** * Gets multiple attribute values. * * @method getAttrs * @param {Array | boolean} attrs Optional. An array of attribute names. If omitted, all attribute values are * returned. If set to true, all attributes modified from their initial values are returned. * @return {Object} An object with attribute name/value pairs. */ getAttrs : function(attrs) { return this._getAttrs(attrs); }, /** * Implementation behind the public getAttrs method, to get multiple attribute values. * * @method _getAttrs * @protected * @param {Array | boolean} attrs Optional. An array of attribute names. If omitted, all attribute values are * returned. If set to true, all attributes modified from their initial values are returned. * @return {Object} An object with attribute name/value pairs. */ _getAttrs : function(attrs) { var host = this, o = {}, i, l, attr, val, modifiedOnly = (attrs === true); attrs = (attrs && !modifiedOnly) ? attrs : O.keys(host._state.data.added); for (i = 0, l = attrs.length; i < l; i++) { // Go through get, to honor cloning/normalization attr = attrs[i]; val = host.get(attr); if (!modifiedOnly || host._getStateVal(attr) != host._state.get(attr, INIT_VALUE)) { o[attr] = host.get(attr); } } return o; }, /** * Configures a group of attributes, and sets initial values. * * <p> * <strong>NOTE:</strong> This method does not isolate the configuration object by merging/cloning. * The caller is responsible for merging/cloning the configuration object if required. * </p> * * @method addAttrs * @chainable * * @param {Object} cfgs An object with attribute name/configuration pairs. * @param {Object} values An object with attribute name/value pairs, defining the initial values to apply. * Values defined in the cfgs argument will be over-written by values in this argument unless defined as read only. * @param {boolean} lazy Whether or not to delay the intialization of these attributes until the first call to get/set. * Individual attributes can over-ride this behavior by defining a lazyAdd configuration property in their configuration. * See <a href="#method_addAttr">addAttr</a>. * * @return {Object} A reference to the host object. */ addAttrs : function(cfgs, values, lazy) { var host = this; // help compression if (cfgs) { host._tCfgs = cfgs; host._tVals = host._normAttrVals(values); host._addAttrs(cfgs, host._tVals, lazy); host._tCfgs = host._tVals = null; } return host; }, /** * Implementation behind the public addAttrs method. * * This method is invoked directly by get if it encounters a scenario * in which an attribute's valueFn attempts to obtain the * value an attribute in the same group of attributes, which has not yet * been added (on demand initialization). * * @method _addAttrs * @private * @param {Object} cfgs An object with attribute name/configuration pairs. * @param {Object} values An object with attribute name/value pairs, defining the initial values to apply. * Values defined in the cfgs argument will be over-written by values in this argument unless defined as read only. * @param {boolean} lazy Whether or not to delay the intialization of these attributes until the first call to get/set. * Individual attributes can over-ride this behavior by defining a lazyAdd configuration property in their configuration. * See <a href="#method_addAttr">addAttr</a>. */ _addAttrs : function(cfgs, values, lazy) { var host = this, // help compression attr, attrCfg, value; for (attr in cfgs) { if (cfgs.hasOwnProperty(attr)) { // Not Merging. Caller is responsible for isolating configs attrCfg = cfgs[attr]; attrCfg.defaultValue = attrCfg.value; // Handle simple, complex and user values, accounting for read-only value = host._getAttrInitVal(attr, attrCfg, host._tVals); if (value !== undefined) { attrCfg.value = value; } if (host._tCfgs[attr]) { delete host._tCfgs[attr]; } host.addAttr(attr, attrCfg, lazy); } } }, /** * Utility method to protect an attribute configuration * hash, by merging the entire object and the individual * attr config objects. * * @method _protectAttrs * @protected * @param {Object} attrs A hash of attribute to configuration object pairs. * @return {Object} A protected version of the attrs argument. */ _protectAttrs : function(attrs) { if (attrs) { attrs = Y.merge(attrs); for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { attrs[attr] = Y.merge(attrs[attr]); } } } return attrs; }, /** * Utility method to normalize attribute values. The base implementation * simply merges the hash to protect the original. * * @method _normAttrVals * @param {Object} valueHash An object with attribute name/value pairs * * @return {Object} * * @private */ _normAttrVals : function(valueHash) { return (valueHash) ? Y.merge(valueHash) : null; }, /** * Returns the initial value of the given attribute from * either the default configuration provided, or the * over-ridden value if it exists in the set of initValues * provided and the attribute is not read-only. * * @param {String} attr The name of the attribute * @param {Object} cfg The attribute configuration object * @param {Object} initValues The object with simple and complex attribute name/value pairs returned from _normAttrVals * * @return {Any} The initial value of the attribute. * * @method _getAttrInitVal * @private */ _getAttrInitVal : function(attr, cfg, initValues) { var val, valFn; // init value is provided by the user if it exists, else, provided by the config if (!cfg[READ_ONLY] && initValues && initValues.hasOwnProperty(attr)) { val = initValues[attr]; } else { val = cfg[VALUE]; valFn = cfg[VALUE_FN]; if (valFn) { if (!valFn.call) { valFn = this[valFn]; } if (valFn) { val = valFn.call(this); } } } return val; }, /** * Returns an object with the configuration properties (and value) * for the given attrubute. If attrName is not provided, returns the * configuration properties for all attributes. * * @method _getAttrCfg * @protected * @param {String} name Optional. The attribute name. If not provided, the method will return the configuration for all attributes. * @return {Object} The configuration properties for the given attribute, or all attributes. */ _getAttrCfg : function(name) { var o, data = this._state.data; if (data) { o = {}; Y.each(data, function(cfg, cfgProp) { if (name) { if(name in cfg) { o[cfgProp] = cfg[name]; } } else { Y.each(cfg, function(attrCfg, attr) { o[attr] = o[attr] || {}; o[attr][cfgProp] = attrCfg; }); } }); } return o; }, /** * Utility method to set up initial attributes defined during construction, either through the constructor.ATTRS property, or explicitly passed in. * * @method _initAttrs * @protected * @param attrs {Object} The attributes to add during construction (passed through to <a href="#method_addAttrs">addAttrs</a>). These can also be defined on the constructor being augmented with Attribute by defining the ATTRS property on the constructor. * @param values {Object} The initial attribute values to apply (passed through to <a href="#method_addAttrs">addAttrs</a>). These are not merged/cloned. The caller is responsible for isolating user provided values if required. * @param lazy {boolean} Whether or not to add attributes lazily (passed through to <a href="#method_addAttrs">addAttrs</a>). */ _initAttrs : function(attrs, values, lazy) { // ATTRS support for Node, which is not Base based attrs = attrs || this.constructor.ATTRS; var Base = Y.Base; if ( attrs && !(Base && Y.instanceOf(this, Base))) { this.addAttrs(this._protectAttrs(attrs), values, lazy); } } }; // Basic prototype augment - no lazy constructor invocation. Y.mix(Attribute, EventTarget, false, null, 1); Y.Attribute = Attribute; }, '3.4.1pr1' ,{requires:['event-custom']});
gpl-3.0
cjbaz/AppCont
app/src/main/java/com/sample/drawer/SuperGlobalVariable.java
134
package com.sample.drawer; import java.util.ArrayList; import java.util.Objects; /** * Created by Slava-laptop on 28.07.2015. */
gpl-3.0
webshub/rtwithoutrtd
ExcelLogin/ExcelLogin/Properties/AssemblyInfo.cs
2233
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ExcelLogin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("mk")] [assembly: AssemblyProduct("ExcelLogin")] [assembly: AssemblyCopyright("Copyright © mk 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-3.0
apuex/akka-model-gen
src/main/scala/com/github/apuex/akka/gen/util/Type.scala
1824
package com.github.apuex.akka.gen.util import scala.xml.{Node, Text} object Type { def apply(xml: Node): Type = new Type(xml) } class Type(xml: Node) { def isValidType(typeName: String): Boolean = { if (isBasicType(typeName)) true else { val entities = xml.child.filter(x => x.label == "entity" && x.attribute("name") == Some(Text(typeName))) val aggregates = entities.map(x => { x.child.filter(x => (x.label == "aggregation" || x.label == "message") && x.attribute("name") == Some(Text(typeName))).nonEmpty }) entities.nonEmpty || (if(aggregates.nonEmpty) aggregates.reduce(_ || _) else false) } } def toScalaType(typeName: String): String = { if (isBasicType(typeName)) return toBasicType(typeName) else if (isEnumType(typeName)) return toEnumType(typeName) else return toValueType(typeName) } def isEnumType(typeName: String): Boolean = { xml.child .filter(x => x.label == "entity" & (x.attribute("name") == Some(Text(typeName))) & (x.attribute("enum") == Some(Text("true"))) ).nonEmpty } def isBasicType(typeName: String): Boolean = typeName match { case "bool" => true case "int" => true case "long" => true case "string" => true case "text" => true case "timestamp" => true case _ => false } def toBasicType(typeName: String): String = typeName match { case "bool" => "Boolean" case "int" => "Int" case "long" => "Long" case "string" => "String" case "text" => "String" case "timestamp" => "Timestamp" case _ => "<Unknown>" } def toEnumType(typeName: String): String = s"${Identifier.toPascal(typeName)}" def toValueType(typeName: String): String = s"${Identifier.toPascal(typeName)}Vo" }
gpl-3.0
gurusharma/StoreHelpLine
helpline/src/main/java/com/s3solutions/helpline/Welcome.java
6366
package com.s3solutions.helpline; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; //Scubesolutions public class Welcome extends AppCompatActivity { private ViewPager viewPager; private MyViewPagerAdapter myViewPagerAdapter; private LinearLayout dotsLayout; private TextView[] dots; private int[] layouts; private Button btnSkip, btnNext; private PreferenceManager prefManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // getSupportActionBar().setDisplayHomeAsUpEnabled(false); // Checking for first time launch - before calling setContentView() prefManager = new PreferenceManager(this); if (!prefManager.isFirstTimeLaunch()) { launchHomeScreen(); finish(); } // Making notification bar transparent if (Build.VERSION.SDK_INT >= 21) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } setContentView(R.layout.activity_welcome); viewPager = (ViewPager) findViewById(R.id.view_pager); dotsLayout = (LinearLayout) findViewById(R.id.layoutDots); btnSkip = (Button) findViewById(R.id.btn_skip); btnNext = (Button) findViewById(R.id.btn_next); // layouts of all welcome sliders // add few more layouts if you want layouts = new int[]{ R.layout.slide_screen1, R.layout.slide_screen2, R.layout.slide_screen3}; // adding bottom dots addBottomDots(0); // making notification bar transparent changeStatusBarColor(); myViewPagerAdapter = new MyViewPagerAdapter(); viewPager.setAdapter(myViewPagerAdapter); viewPager.addOnPageChangeListener(viewPagerPageChangeListener); btnSkip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchHomeScreen(); } }); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking for last page // if last page home screen will be launched int current = getItem(+1); if (current < layouts.length) { // move to next screen viewPager.setCurrentItem(current); } else { launchHomeScreen(); } } }); } private void addBottomDots(int currentPage) { dots = new TextView[layouts.length]; int[] colorsActive = getResources().getIntArray(R.array.array_dot_active); int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive); dotsLayout.removeAllViews(); for (int i = 0; i < dots.length; i++) { dots[i] = new TextView(this); dots[i].setText(Html.fromHtml("&#8226;")); dots[i].setTextSize(35); dots[i].setTextColor(colorsInactive[currentPage]); dotsLayout.addView(dots[i]); } if (dots.length > 0) dots[currentPage].setTextColor(colorsActive[currentPage]); } private int getItem(int i) { return viewPager.getCurrentItem() + i; } private void launchHomeScreen() { prefManager.setFirstTimeLaunch(false); startActivity(new Intent(Welcome.this, SignIn.class)); finish(); } // viewpager change listener ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { addBottomDots(position); // changing the next button text 'NEXT' / 'GOT IT' if (position == layouts.length - 1) { // last page. make button text to GOT IT btnNext.setText("Got It"); btnSkip.setVisibility(View.GONE); } else { // still pages are left btnNext.setText(getString(R.string.next)); btnSkip.setVisibility(View.VISIBLE); } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }; /** * Making notification bar transparent */ private void changeStatusBarColor() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); } } /** * View pager adapter */ public class MyViewPagerAdapter extends PagerAdapter { private LayoutInflater layoutInflater; public MyViewPagerAdapter() { } @Override public Object instantiateItem(ViewGroup container, int position) { layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(layouts[position], container, false); container.addView(view); return view; } @Override public int getCount() { return layouts.length; } @Override public boolean isViewFromObject(View view, Object obj) { return view == obj; } @Override public void destroyItem(ViewGroup container, int position, Object object) { View view = (View) object; container.removeView(view); } } }
gpl-3.0
Drxmo/imaginarium
vendor/swiftmailer/swiftmailer/tests/unit/Swift/Encoder/QpEncoderTest.php
13133
<?php class Swift_Encoder_QpEncoderTest extends \SwiftMailerTestCase { /* -- RFC 2045, 6.7 -- (1) (General 8bit representation) Any octet, except a CR or LF that is part of a CRLF line break of the canonical (standard) form of the data being encoded, may be represented by an "=" followed by a two digit hexadecimal representation of the octet's value. The digits of the hexadecimal alphabet, for this purpose, are "0123456789ABCDEF". Uppercase letters must be used; lowercase letters are not allowed. Thus, for example, the decimal value 12 (US-ASCII form feed) can be represented by "=0C", and the decimal value 61 (US- ASCII EQUAL SIGN) can be represented by "=3D". This rule must be followed except when the following rules allow an alternative encoding. */ public function testPermittedCharactersAreNotEncoded() { /* -- RFC 2045, 6.7 -- (2) (Literal representation) Octets with decimal values of 33 through 60 inclusive, and 62 through 126, inclusive, MAY be represented as the US-ASCII characters which correspond to those octets (EXCLAMATION POINT through LESS THAN, and GREATER THAN through TILDE, respectively). */ foreach (array_merge(range(33, 60), range(62, 126)) as $ordinal) { $char = chr($ordinal); $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($char); $charStream->shouldReceive('readBytes') ->once() ->andReturn(array($ordinal)); $charStream->shouldReceive('readBytes') ->atLeast()->times(1) ->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertIdenticalBinary($char, $encoder->encodeString($char)); } } public function testWhiteSpaceAtLineEndingIsEncoded() { /* -- RFC 2045, 6.7 -- (3) (White Space) Octets with values of 9 and 32 MAY be represented as US-ASCII TAB (HT) and SPACE characters, respectively, but MUST NOT be so represented at the end of an encoded line. Any TAB (HT) or SPACE characters on an encoded line MUST thus be followed on that line by a printable character. In particular, an "=" at the end of an encoded line, indicating a soft line break (see rule #5) may follow one or more TAB (HT) or SPACE characters. It follows that an octet with decimal value 9 or 32 appearing at the end of an encoded line must be represented according to Rule #1. This rule is necessary because some MTAs (Message Transport Agents, programs which transport messages from one user to another, or perform a portion of such transfers) are known to pad lines of text with SPACEs, and others are known to remove "white space" characters from the end of a line. Therefore, when decoding a Quoted-Printable body, any trailing white space on a line must be deleted, as it will necessarily have been added by intermediate transport agents. */ $HT = chr(0x09); //9 $SPACE = chr(0x20); //32 //HT $string = 'a' . $HT . $HT . "\r\n" . 'b'; $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($string); $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('a'))); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x09)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x09)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('b'))); $charStream->shouldReceive('readBytes')->once()->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals( 'a' . $HT . '=09' . "\r\n" . 'b', $encoder->encodeString($string) ); //SPACE $string = 'a' . $SPACE . $SPACE . "\r\n" . 'b'; $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($string); $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('a'))); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x20)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x20)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('b'))); $charStream->shouldReceive('readBytes')->once()->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals( 'a' . $SPACE . '=20' . "\r\n" . 'b', $encoder->encodeString($string) ); } public function testCRLFIsLeftAlone() { /* (4) (Line Breaks) A line break in a text body, represented as a CRLF sequence in the text canonical form, must be represented by a (RFC 822) line break, which is also a CRLF sequence, in the Quoted-Printable encoding. Since the canonical representation of media types other than text do not generally include the representation of line breaks as CRLF sequences, no hard line breaks (i.e. line breaks that are intended to be meaningful and to be displayed to the user) can occur in the quoted-printable encoding of such types. Sequences like "=0D", "=0A", "=0A=0D" and "=0D=0A" will routinely appear in non-text data represented in quoted- printable, of course. Note that many implementations may elect to encode the local representation of various content types directly rather than converting to canonical form first, encoding, and then converting back to local representation. In particular, this may apply to plain text material on systems that use newline conventions other than a CRLF terminator sequence. Such an implementation optimization is permissible, but only when the combined canonicalization-encoding step is equivalent to performing the three steps separately. */ $string = 'a' . "\r\n" . 'b' . "\r\n" . 'c' . "\r\n"; $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($string); $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('a'))); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('b'))); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(ord('c'))); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0D)); $charStream->shouldReceive('readBytes')->once()->andReturn(array(0x0A)); $charStream->shouldReceive('readBytes')->once()->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals($string, $encoder->encodeString($string)); } public function testLinesLongerThan76CharactersAreSoftBroken() { /* (5) (Soft Line Breaks) The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long. If longer lines are to be encoded with the Quoted-Printable encoding, "soft" line breaks must be used. An equal sign as the last character on a encoded line indicates such a non-significant ("soft") line break in the encoded text. */ $input = str_repeat('a', 140); $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($input); $output = ''; for ($i = 0; $i < 140; ++$i) { $charStream->shouldReceive('readBytes') ->once() ->andReturn(array(ord('a'))); if (75 == $i) { $output .= "=\r\n"; } $output .= 'a'; } $charStream->shouldReceive('readBytes') ->once() ->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals($output, $encoder->encodeString($input)); } public function testMaxLineLengthCanBeSpecified() { $input = str_repeat('a', 100); $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($input); $output = ''; for ($i = 0; $i < 100; ++$i) { $charStream->shouldReceive('readBytes') ->once() ->andReturn(array(ord('a'))); if (53 == $i) { $output .= "=\r\n"; } $output .= 'a'; } $charStream->shouldReceive('readBytes') ->once() ->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals($output, $encoder->encodeString($input, 0, 54)); } public function testBytesBelowPermittedRangeAreEncoded() { /* According to Rule (1 & 2) */ foreach (range(0, 32) as $ordinal) { $char = chr($ordinal); $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($char); $charStream->shouldReceive('readBytes') ->once() ->andReturn(array($ordinal)); $charStream->shouldReceive('readBytes') ->atLeast()->times(1) ->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals( sprintf('=%02X', $ordinal), $encoder->encodeString($char) ); } } public function testDecimalByte61IsEncoded() { /* According to Rule (1 & 2) */ $char = '='; $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($char); $charStream->shouldReceive('readBytes') ->once() ->andReturn(array(61)); $charStream->shouldReceive('readBytes') ->atLeast()->times(1) ->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals('=3D', $encoder->encodeString('=')); } public function testBytesAbovePermittedRangeAreEncoded() { /* According to Rule (1 & 2) */ foreach (range(127, 255) as $ordinal) { $char = chr($ordinal); $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($char); $charStream->shouldReceive('readBytes') ->once() ->andReturn(array($ordinal)); $charStream->shouldReceive('readBytes') ->atLeast()->times(1) ->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals( sprintf('=%02X', $ordinal), $encoder->encodeString($char) ); } } public function testFirstLineLengthCanBeDifferent() { $input = str_repeat('a', 140); $charStream = $this->_createCharStream(); $charStream->shouldReceive('flushContents') ->once(); $charStream->shouldReceive('importString') ->once() ->with($input); $output = ''; for ($i = 0; $i < 140; ++$i) { $charStream->shouldReceive('readBytes') ->once() ->andReturn(array(ord('a'))); if (53 == $i || 53 + 75 == $i) { $output .= "=\r\n"; } $output .= 'a'; } $charStream->shouldReceive('readBytes') ->once() ->andReturn(false); $encoder = new Swift_Encoder_QpEncoder($charStream); $this->assertEquals( $output, $encoder->encodeString($input, 22), '%s: First line should start at offset 22 so can only have max length 54' ); } // -- Creation methods private function _createCharStream() { return $this->getMockery('Swift_CharacterStream')->shouldIgnoreMissing(); } }
gpl-3.0
jeffersonmolleri/sesra
lib/form/base/BaseStudyUserCriteriaForm.class.php
1492
<?php /** * StudyUserCriteria form base class. * * @method StudyUserCriteria getObject() Returns the current form's model object * * @package mestrado * @subpackage form * @author Jefferson Seide Molléri */ abstract class BaseStudyUserCriteriaForm extends BaseFormPropel { public function setup() { $this->setWidgets(array( 'study_id' => new sfWidgetFormPropelChoice(array('model' => 'Study', 'add_empty' => false)), 'user_id' => new sfWidgetFormPropelChoice(array('model' => 'sfGuardUser', 'add_empty' => false)), 'criteria_id' => new sfWidgetFormPropelChoice(array('model' => 'RslCriteria', 'add_empty' => false)), 'id' => new sfWidgetFormInputHidden(), )); $this->setValidators(array( 'study_id' => new sfValidatorPropelChoice(array('model' => 'Study', 'column' => 'id')), 'user_id' => new sfValidatorPropelChoice(array('model' => 'sfGuardUser', 'column' => 'id')), 'criteria_id' => new sfValidatorPropelChoice(array('model' => 'RslCriteria', 'column' => 'id')), 'id' => new sfValidatorChoice(array('choices' => array($this->getObject()->getId()), 'empty_value' => $this->getObject()->getId(), 'required' => false)), )); $this->widgetSchema->setNameFormat('study_user_criteria[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); parent::setup(); } public function getModelName() { return 'StudyUserCriteria'; } }
gpl-3.0
sgdc3/AuthMeReloaded
src/main/java/fr/xephi/authme/command/CommandHandler.java
9722
package fr.xephi.authme.command; import fr.xephi.authme.AuthMe; import fr.xephi.authme.command.help.HelpProvider; import fr.xephi.authme.util.CollectionUtils; import fr.xephi.authme.util.StringUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * The AuthMe command handler, responsible for mapping incoming commands to the correct {@link CommandDescription} * or to display help messages for unknown invocations. */ public class CommandHandler { /** * The threshold for assuming an existing command. If the difference is below this value, we assume * that the user meant the similar command and we will run it. */ private static final double ASSUME_COMMAND_THRESHOLD = 0.12; /** * The threshold for suggesting a similar command. If the difference is below this value, we will * ask the player whether he meant the similar command. */ private static final double SUGGEST_COMMAND_THRESHOLD = 0.75; private final Set<CommandDescription> commands; /** * Create a command handler. * * @param commands The collection of available AuthMe commands */ public CommandHandler(Set<CommandDescription> commands) { this.commands = commands; } /** * Map a command that was invoked to the proper {@link CommandDescription} or return a useful error * message upon failure. * * @param sender The command sender (Bukkit). * @param bukkitCommandLabel The command label (Bukkit). * @param bukkitArgs The command arguments (Bukkit). * * @return True if the command was executed, false otherwise. */ public boolean processCommand(CommandSender sender, String bukkitCommandLabel, String[] bukkitArgs) { List<String> commandArgs = skipEmptyArguments(bukkitArgs); // Add the Bukkit command label to the front so we get a list like [authme, register, pass, passConfirm] commandArgs.add(0, bukkitCommandLabel); // TODO: remove commandParts CommandParts commandReference = new CommandParts(commandArgs); // Get a suitable command for this reference, and make sure it isn't null FoundCommandResult result = findCommand(commandReference); if (result == null) { // TODO ljacqu 20151204: Log more information to the console (bukkitCommandLabel) sender.sendMessage(ChatColor.DARK_RED + "Failed to parse " + AuthMe.getPluginName() + " command!"); return false; } String baseCommand = commandArgs.get(0); // Make sure the difference between the command reference and the actual command isn't too big final double commandDifference = result.getDifference(); if (commandDifference <= ASSUME_COMMAND_THRESHOLD) { // Show a message when the command handler is assuming a command if (commandDifference > 0) { sendCommandAssumptionMessage(sender, result, commandReference); } if (!result.hasPermission(sender)) { sender.sendMessage(ChatColor.DARK_RED + "You don't have permission to use this command!"); } else if (!result.hasProperArguments()) { sendImproperArgumentsMessage(sender, result, commandReference, baseCommand); } else { return result.executeCommand(sender); } } else { sendUnknownCommandMessage(sender, commandDifference, result, baseCommand); } return true; } /** * Skip all entries of the given array that are simply whitespace. * * @param args The array to process * @return List of the items that are not empty */ private static List<String> skipEmptyArguments(String[] args) { List<String> cleanArguments = new ArrayList<>(args.length); for (String argument : args) { if (!StringUtils.isEmpty(argument)) { cleanArguments.add(argument); } } return cleanArguments; } private static CommandDescription mapToBase(String commandLabel) { for (CommandDescription command : CommandInitializer.getBaseCommands()) { if (command.getLabels().contains(commandLabel)) { return command; } } return null; } /** * Find the best suitable command for the specified reference. * * @param queryReference The query reference to find a command for. * * @return The command found, or null. */ public FoundCommandResult findCommand(CommandParts queryReference) { // Make sure the command reference is valid if (queryReference.getCount() <= 0) return null; for (CommandDescription commandDescription : commands) { // Check whether there's a command description available for the // current command if (!commandDescription.isSuitableLabel(queryReference)) continue; // Find the command reference, return the result return commandDescription.findCommand(queryReference); } // No applicable command description found, return false return null; } /** * Find the best suitable command for the specified reference. * * @param commandParts The query reference to find a command for. * * @return The command found, or null. */ private CommandDescription findCommand(List<String> commandParts) { // Make sure the command reference is valid if (commandParts.isEmpty()) { return null; } // TODO ljacqu 20151129: Since we only use .contains() on the CommandDescription#labels after init, change // the type to set for faster lookup Iterable<CommandDescription> commandsToScan = CommandInitializer.getBaseCommands(); CommandDescription result = null; for (String label : commandParts) { result = findLabel(label, commandsToScan); if (result == null) { return null; } commandsToScan = result.getChildren(); } return result; } private static CommandDescription findLabel(String label, Iterable<CommandDescription> commands) { if (commands == null) { return null; } for (CommandDescription command : commands) { if (command.getLabels().contains(label)) { // TODO ljacqu should be case-insensitive return command; } } return null; } /** * Show an "unknown command" to the user and suggests an existing command if its similarity is within * the defined threshold. * * @param sender The command sender * @param commandDifference The difference between the invoked command and the existing one * @param result The command that was found during the mapping process * @param baseCommand The base command (TODO: This is probably already in FoundCommandResult) */ private static void sendUnknownCommandMessage(CommandSender sender, double commandDifference, FoundCommandResult result, String baseCommand) { CommandParts commandReference = result.getCommandReference(); sender.sendMessage(ChatColor.DARK_RED + "Unknown command!"); // Show a command suggestion if available and the difference isn't too big if (commandDifference < SUGGEST_COMMAND_THRESHOLD && result.getCommandDescription() != null) { sender.sendMessage(ChatColor.YELLOW + "Did you mean " + ChatColor.GOLD + "/" + result.getCommandDescription().getCommandReference(commandReference) + ChatColor.YELLOW + "?"); } sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + baseCommand + " help" + ChatColor.YELLOW + " to view help."); } private static void sendImproperArgumentsMessage(CommandSender sender, FoundCommandResult result, CommandParts commandReference, String baseCommand) { // Get the command and the suggested command reference List<String> suggestedCommandReference = result.getCommandDescription().getCommandReference(commandReference).getList(); List<String> helpCommandReference = CollectionUtils.getRange(suggestedCommandReference, 1); // Show the invalid arguments warning sender.sendMessage(ChatColor.DARK_RED + "Incorrect command arguments!"); // Show the command argument help HelpProvider.showHelp(sender, commandReference, new CommandParts(suggestedCommandReference), true, false, true, false, false, false); // Show the command to use for detailed help sender.sendMessage(ChatColor.GOLD + "Detailed help: " + ChatColor.WHITE + "/" + baseCommand + " help " + CommandUtils.labelsToString(helpCommandReference)); } private static void sendCommandAssumptionMessage(CommandSender sender, FoundCommandResult result, CommandParts commandReference) { List<String> assumedCommandParts = result.getCommandDescription().getCommandReference(commandReference).getList(); sender.sendMessage(ChatColor.DARK_RED + "Unknown command, assuming " + ChatColor.GOLD + "/" + CommandUtils.labelsToString(assumedCommandParts) + ChatColor.DARK_RED + "!"); } }
gpl-3.0
cfelton/minnesota
mn/cores/sdram/__init__.py
110
from _intf import SDRAM from _sdram_sdr import m_sdram # specific memory definitions from _memories import *
gpl-3.0
MatiasNAmendola/gnome-web
lib/ctrl/api/CmdController.class.php
2474
<?php namespace lib\ctrl\api; /** * Execute commands. * @author $imon */ class CmdController extends \lib\ApiBackController { protected $terminal, $cmd; /** * Execute a command. * @param string $cmdText The command. * @param int $terminalId The terminal ID. */ public function executeExecute($cmdText, $terminalId) { $fileManager = $this->managers()->getManagerOf('file'); $terminalManager = $this->managers()->getManagerOf('terminal'); $authManager = $this->managers()->getManagerOf('authorization'); $processManager = $this->managers()->getManagerOf('process'); $user = $this->app()->user(); if (!$terminalManager->isTerminal($terminalId)) { $terminal = $terminalManager->buildTerminal($terminalId); $terminal->setDir(($user->isLogged()) ? '~' : '/'); $terminalManager->updateTerminal($terminal); } else { $terminal = $terminalManager->getTerminal($terminalId); } $cmd = $terminalManager->buildCmd($cmdText, $terminal); $executablePath = $terminalManager->findExecutable($cmd, $terminal); $auths = array(); if ($user->isLogged()) { $auths = $authManager->getByUserId($user->id()); } $authManager->setByPid($cmd->id(), $auths); $executableScript = $fileManager->read($executablePath); switch ($fileManager->pathinfo($executablePath, PATHINFO_EXTENSION)) { case 'php': $this->terminal = $terminal; $this->cmd = $cmd; $_cmd_errMsg = null; //Complicated name because cmd script must not overwrite it ob_start(); try { require($fileManager->toInternalPath($executablePath)); } catch(\Exception $e) { $_cmd_errMsg = $e->getMessage(); } $out = ob_get_contents(); ob_end_clean(); if (!empty($_cmd_errMsg)) { $this->responseContent->setSuccess(false); $this->responseContent->setChannel(2, $_cmd_errMsg); $this->responseContent->setValue($out."\n".$_cmd_errMsg); } else { $this->responseContent->setValue($out); } $authManager = $this->managers()->getManagerOf('authorization'); $authManager->unsetByPid($this->cmd->id()); break; case 'js': $authsNames = array(); foreach($auths as $auth) { $authsNames[] = $auth['name']; } $processManager->run($cmd); $this->responseContent()->setData(array( 'pid' => $cmd->id(), 'key' => $cmd->key(), 'authorizations' => $authsNames, 'path' => $executablePath, 'script' => $executableScript )); break; } } }
gpl-3.0
csf-dept-info/stagio
Stagio.Web.Automation/PageObjects/LoginPage.cs
1281
using System; using Stagio.Domain.Entities; using Stagio.Web.Automation.Selenium; using Stagio.Web.Automation.Navigation; using OpenQA.Selenium; namespace Stagio.Web.Automation.PageObjects { public class LoginPage { public const string PAGE_ID = "login-page"; public static bool IsDisplayed { get { try { Driver.Instance.FindElement(By.Id(PAGE_ID)); return true; } catch (Exception) { return false; } } } public static bool HasContent(string textToFind) { var body = Driver.Instance.FindElement(By.Id(PAGE_ID)); return body.Text.Contains(textToFind); } public static void GoTo() { PageNavigator.AllUsers.Login.Select(); } public static void LoginAs(ApplicationUser user) { Driver.Instance.FindElement(By.Id("Identifier")).SendKeys(user.Identifier); Driver.Instance.FindElement(By.Id("Password")).SendKeys(user.Password); Driver.Instance.FindElement(By.Id("login-submit")).Click(); } } }
gpl-3.0
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/finiteVolume/finiteVolume/ddtSchemes/EulerDdtScheme/EulerDdtScheme.H
5348
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend 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. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. Class Foam::fv::EulerDdtScheme Description Basic first-order Euler implicit/explicit ddt using only the current and previous time-step values. SourceFiles EulerDdtScheme.C \*---------------------------------------------------------------------------*/ #ifndef EulerDdtScheme_H #define EulerDdtScheme_H #include "ddtScheme.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace fv { /*---------------------------------------------------------------------------*\ Class EulerDdtScheme Declaration \*---------------------------------------------------------------------------*/ template<class Type> class EulerDdtScheme : public ddtScheme<Type> { // Private Member Functions //- Disallow default bitwise copy construct EulerDdtScheme(const EulerDdtScheme&); //- Disallow default bitwise assignment void operator=(const EulerDdtScheme&); public: //- Runtime type information TypeName("Euler"); // Constructors //- Construct from mesh EulerDdtScheme(const fvMesh& mesh) : ddtScheme<Type>(mesh) {} //- Construct from mesh and Istream EulerDdtScheme(const fvMesh& mesh, Istream& is) : ddtScheme<Type>(mesh, is) {} // Member Functions //- Return mesh reference const fvMesh& mesh() const { return fv::ddtScheme<Type>::mesh(); } tmp<GeometricField<Type, fvPatchField, volMesh> > fvcDdt ( const dimensioned<Type>& ); tmp<GeometricField<Type, fvPatchField, volMesh> > fvcDdt ( const GeometricField<Type, fvPatchField, volMesh>& ); tmp<GeometricField<Type, fvPatchField, volMesh> > fvcDdt ( const dimensionedScalar&, const GeometricField<Type, fvPatchField, volMesh>& ); tmp<GeometricField<Type, fvPatchField, volMesh> > fvcDdt ( const volScalarField&, const GeometricField<Type, fvPatchField, volMesh>& ); tmp<fvMatrix<Type> > fvmDdt ( GeometricField<Type, fvPatchField, volMesh>& ); tmp<fvMatrix<Type> > fvmDdt ( const dimensionedScalar&, GeometricField<Type, fvPatchField, volMesh>& ); tmp<fvMatrix<Type> > fvmDdt ( const volScalarField&, GeometricField<Type, fvPatchField, volMesh>& ); typedef typename ddtScheme<Type>::fluxFieldType fluxFieldType; tmp<fluxFieldType> fvcDdtPhiCorr ( const volScalarField& rA, const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi ); tmp<fluxFieldType> fvcDdtPhiCorr ( const volScalarField& rA, const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi ); tmp<surfaceScalarField> meshPhi ( const GeometricField<Type, fvPatchField, volMesh>& ); }; template<> tmp<surfaceScalarField> EulerDdtScheme<scalar>::fvcDdtPhiCorr ( const volScalarField& rA, const volScalarField& U, const surfaceScalarField& phi ); template<> tmp<surfaceScalarField> EulerDdtScheme<scalar>::fvcDdtPhiCorr ( const volScalarField& rA, const volScalarField& rho, const volScalarField& U, const surfaceScalarField& phi ); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace fv // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "EulerDdtScheme.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
gpl-3.0
ermirbeqiraj/board-time
MvcToDo/Core/Repository/IRepository.cs
769
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace MvcToDo.Core.Repository { public interface IRepository<T> where T : class { /// <summary> /// Get element by id /// </summary> /// <param name="id">Id of element</param> /// <returns></returns> T Get(int id); T GetSingle(Expression<Func<T, bool>> predicate); IEnumerable<T> GetAll(); IEnumerable<T> Find(Expression<Func<T, bool>> predicate); void Add(T item); void AddRange(IEnumerable<T> items); void Remove(T item); void RemoveRange(IEnumerable<T> items); void Update(T item); } }
gpl-3.0
cliftonmcintosh/openstates
openstates/ia/votes.py
9924
# -*- coding: utf8 -*- from datetime import datetime import re import collections import lxml.etree from billy.scrape.utils import convert_pdf from billy.scrape.votes import VoteScraper, Vote from .scraper import InvalidHTTPSScraper class IAVoteScraper(InvalidHTTPSScraper, VoteScraper): jurisdiction = 'ia' def scrape(self, chamber, session): # Each PDF index page contains just one year, not a whole session # Therefore, we need to iterate over both years in the session session_years = [int(year) for year in session.split("-")] for year in session_years: if year <= datetime.today().year: chamber_name = self.metadata["chambers"][chamber]["name"].lower() url = 'https://www.legis.iowa.gov/chambers/journals/index/{}'.\ format(chamber_name) params = {"year": year} html = self.get(url, params=params).content doc = lxml.html.fromstring(html) doc.make_links_absolute(url) urls = [x for x in doc.xpath('//a[@href]/@href') if x.endswith(".pdf")][::-1] for url in urls: _, filename = url.rsplit('/', 1) journal_template = '%Y%m%d_{}.pdf' try: if chamber == 'upper': journal_format = journal_template.format('SJNL') elif chamber == 'lower': journal_format = journal_template.format('HJNL') else: raise ValueError('Unknown chamber: {}'.format( chamber)) date = datetime.strptime(filename, journal_format) self.scrape_journal(url, chamber, session, date) except ValueError: journal_format = '%m-%d-%Y.pdf' try: date = datetime.strptime(filename, journal_format) except: msg = '{} doesn\'t smell like a date. Skipping.' self.logger.info(msg.format(filename)) def scrape_journal(self, url, chamber, session, date): filename, response = self.urlretrieve(url) self.logger.info('Saved journal to %r' % filename) all_text = convert_pdf(filename, type="text") lines = all_text.split("\n") lines = [line. strip(). replace("–", "-"). replace("―", '"'). replace("‖", '"'). replace('“', '"'). replace('”', '"') for line in lines] # Do not process headers or completely empty lines header_date_re = r"\d+\w{2} Day\s+\w+DAY, \w+ \d{1,2}, \d{4}\s+\d+" header_journal_re = r"\d+\s+JOURNAL OF THE \w+\s+\d+\w{2} Day" lines = iter([line for line in lines if not( line == "" or re.match(header_date_re, line) or re.match(header_journal_re, line))]) for line in lines: # Go through with vote parse if any of # these conditions match. if not line.startswith("On the question") or \ "shall" not in line.lower(): continue # Get the bill_id bill_id = None bill_re = r'\(\s*([A-Z\.]+\s\d+)\s*\)' # The Senate ends its motion text with a vote announcement if chamber == "upper": end_of_motion_re = r'.* the vote was:\s*' # The House may or may not end motion text with a bill name elif chamber == "lower": end_of_motion_re = r'.*Shall.*\?"?(\s{})?\s*'.format(bill_re) while not re.match(end_of_motion_re, line, re.IGNORECASE): line += " " + lines.next() try: bill_id = re.search(bill_re, line).group(1) except AttributeError: self.warning("This motion did not pertain to legislation: {}". format(line)) continue # Get the motion text motion_re = r''' ^On\sthe\squestion\s # Precedes any motion "+ # Motion is preceded by a quote mark (or two) (Shall\s.+?\??) # The motion text begins with "Shall" \s*"\s+ # Motion is followed by a quote mark (?:{})? # If the vote regards a bill, its number is listed {} # Senate has trailing text \s*$ '''.format( bill_re, r',?.*?the\svote\swas:' if chamber == 'upper' else '' ) print(line) motion = re.search(motion_re, line, re.VERBOSE | re.IGNORECASE).group(1) for word, letter in (('Senate', 'S'), ('House', 'H'), ('File', 'F')): if bill_id is None: return bill_id = bill_id.replace(word, letter) bill_chamber = dict(h='lower', s='upper')[bill_id.lower()[0]] self.current_id = bill_id votes, passed = self.parse_votes(lines) #at the very least, there should be a majority #for the bill to have passed, so check that, #but if the bill didn't pass, it could still be OK if it got a majority #eg constitutional amendments if not ((passed == (votes['yes_count'] > votes['no_count'])) or (not passed)): self.error("The bill passed without a majority?") raise ValueError('invalid vote') #also throw a warning if the bill failed but got a majority #it could be OK, but is probably something we'd want to check if not passed and votes['yes_count'] > votes['no_count']: self.logger.warning("The bill got a majority but did not pass. Could be worth confirming.") vote = Vote(motion=re.sub('\xad', '-', motion), passed=passed, chamber=chamber, date=date, session=session, bill_id=bill_id, bill_chamber=bill_chamber, **votes) vote.update(votes) vote.add_source(url) self.save_vote(vote) def parse_votes(self, lines): counts = collections.defaultdict(list) DONE = 1 boundaries = [ # Senate journal. ('Yeas', 'yes'), ('Nays', 'no'), ('Absent', 'other'), ('Present', 'skip'), ('Amendment', DONE), ('Resolution', DONE), ('The senate joint resolution', DONE), ('Bill', DONE), # House journal. ('The ayes were', 'yes'), ('The yeas were', 'yes'), ('The nays were', 'no'), ('Absent or not voting', 'other'), ('The bill', DONE), ('The committee', DONE), ('The resolution', DONE), ('The motion', DONE), ('Division', DONE), ('The joint resolution', DONE), ('Under the', DONE) ] passage_strings = ["passed","adopted","prevailed"] def is_boundary(text, patterns={}): for blurb, key in boundaries: if text.strip().startswith(blurb): return key while True: text = next(lines) if is_boundary(text): break while True: key = is_boundary(text) if key is DONE: passage_line = text+" "+next(lines) passed = False if any(p in passage_line for p in passage_strings): passed = True break # Get the vote count. m = re.search(r'\d+', text) if not m: if 'none' in text: votecount = 0 else: votecount = int(m.group()) if key != 'skip': counts['%s_count' % key] = votecount # Get the voter names. while True: text = next(lines) if is_boundary(text): break elif not text.strip() or text.strip().isdigit(): continue else: for name in self.split_names(text): counts['%s_votes' % key].append(name.strip()) return counts, passed def split_names(self, text): junk = ['Presiding', 'Mr. Speaker', 'Spkr.', '.'] text = text.strip() chunks = text.split()[::-1] name = [chunks.pop()] names = [] while chunks: chunk = chunks.pop() if len(chunk) < 3: name.append(chunk) elif name[-1] in ('Mr.', 'Van', 'De', 'Vander'): name.append(chunk) else: name = ' '.join(name).strip(',') if name and (name not in names) and (name not in junk): names.append(name) # Seed the next loop. name = [chunk] # Similar changes to the final name in the sequence. name = ' '.join(name).strip(',') if names and len(name) < 3: names[-1] += ' %s' % name elif name and (name not in names) and (name not in junk): names.append(name) return names
gpl-3.0
zpxocivuby/freetong_mobile
ItafMobileApp/src/itaf/mobile/app/ui/MerchantStockOrder.java
8866
package itaf.mobile.app.ui; import itaf.framework.base.dto.WsPageResult; import itaf.framework.merchant.dto.BzStockOrderDto; import itaf.framework.merchant.dto.BzStockOrderItemDto; import itaf.framework.product.dto.BzProductDto; import itaf.mobile.app.R; import itaf.mobile.app.services.TaskService; import itaf.mobile.app.task.netreader.StockOrderFinishedTask; import itaf.mobile.app.task.netreader.StockOrderListTask; import itaf.mobile.app.third.pull.PullToRefreshBase; import itaf.mobile.app.third.pull.PullToRefreshBase.OnRefreshListener; import itaf.mobile.app.third.pull.PullToRefreshExpandableListView; import itaf.mobile.app.ui.base.BaseUIActivity; import itaf.mobile.app.ui.base.UIRefresh; import itaf.mobile.app.ui.widget.AsyncImageView; import itaf.mobile.app.util.DownLoadHelper; import itaf.mobile.app.util.OnClickListenerHelper; import itaf.mobile.app.util.ToastHelper; import itaf.mobile.core.app.AppApplication; import itaf.mobile.core.constant.AppConstants; import itaf.mobile.core.utils.DateUtil; import itaf.mobile.core.utils.StringHelper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.TextView; /** * 备货 * * @author XINXIN * * @UpdateDate 2014年12月4日 */ public class MerchantStockOrder extends BaseUIActivity implements UIRefresh { // 返回 private Button btn_mso_back; private PullToRefreshExpandableListView elv_mso_content; private StockOrderAdapter adapter; private List<BzStockOrderDto> adapterContent = new ArrayList<BzStockOrderDto>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.merchant_stock_order); initPageAttribute(); initListView(); addStockOrderListTask(); } private void initPageAttribute() { btn_mso_back = (Button) this.findViewById(R.id.btn_mso_back); btn_mso_back.setOnClickListener(OnClickListenerHelper .finishActivity(MerchantStockOrder.this)); } private void initListView() { // 增加那个 更多按钮,必须放在Adapter之前 elv_mso_content = (PullToRefreshExpandableListView) this .findViewById(R.id.elv_mso_content); elv_mso_content.setShowIndicator(false); adapter = new StockOrderAdapter(MerchantStockOrder.this, adapterContent); elv_mso_content.getRefreshableView().setAdapter(adapter); // 设置拖动列表的时候防止出现黑色背景 elv_mso_content.getRefreshableView().setCacheColorHint(0); elv_mso_content .setOnRefreshListener(new OnRefreshListener<ExpandableListView>() { @Override public void onRefresh( PullToRefreshBase<ExpandableListView> refreshView) { addStockOrderListTask(); } }); } private void addStockOrderListTask() { Map<String, Object> params = new HashMap<String, Object>(); params.put(StockOrderListTask.TP_BZ_MERCHANT_ID, AppApplication .getInstance().getSessionUser().getId()); TaskService.addTask(new StockOrderListTask(MerchantStockOrder.this, params)); showProgressDialog(PD_LOADING); } private void addStockOrderFinishedTask(Long bzStockOrderId) { Map<String, Object> params = new HashMap<String, Object>(); params.put(StockOrderFinishedTask.TP_BZ_STOCK_ORDER_ID, bzStockOrderId); TaskService.addTask(new StockOrderFinishedTask(MerchantStockOrder.this, params)); showProgressDialog(PD_LOADING); } @SuppressWarnings("unchecked") @Override public void refresh(Object... args) { dismissProgressDialog(); int taskId = (Integer) args[0]; if (StockOrderListTask.getTaskId() == taskId) { if (args[1] == null) { elv_mso_content.onRefreshComplete(); return; } WsPageResult<BzStockOrderDto> result = (WsPageResult<BzStockOrderDto>) args[1]; if (WsPageResult.STATUS_ERROR.equals(result.getStatus())) { if (StringHelper.isEmpty(result.getErrorMsg())) { ToastHelper.showToast(MerchantStockOrder.this, "发货失败"); } else { ToastHelper.showToast(MerchantStockOrder.this, result.getErrorMsg()); } elv_mso_content.onRefreshComplete(); return; } adapterContent.clear(); adapterContent.addAll(result.getContent()); for (int i = 0; i < adapterContent.size(); i++) { elv_mso_content.getRefreshableView().expandGroup(i); } adapter.notifyDataSetChanged(); elv_mso_content.onRefreshComplete(); } else if (StockOrderFinishedTask.getTaskId() == taskId) { if (args[1] == null) { return; } WsPageResult<BzStockOrderDto> result = (WsPageResult<BzStockOrderDto>) args[1]; if (WsPageResult.STATUS_ERROR.equals(result.getStatus())) { if (StringHelper.isEmpty(result.getErrorMsg())) { ToastHelper.showToast(MerchantStockOrder.this, "设置完成失败"); } else { ToastHelper.showToast(MerchantStockOrder.this, result.getErrorMsg()); } elv_mso_content.onRefreshComplete(); return; } ToastHelper.showToast(MerchantStockOrder.this, "设置完成备货成功!"); addStockOrderListTask(); } } class StockOrderAdapter extends BaseExpandableListAdapter { private List<BzStockOrderDto> listItems;// 数据集合 private LayoutInflater listContainer; public StockOrderAdapter(Context context, List<BzStockOrderDto> data) { this.listContainer = LayoutInflater.from(context); // 创建视图容器并设置上下文 this.listItems = data; } @Override public int getGroupCount() { return listItems.size(); } @Override public int getChildrenCount(int groupPosition) { return listItems.get(groupPosition).getBzStockOrderItemDtos() .size(); } @Override public Object getGroup(int groupPosition) { return listItems.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return listItems.get(groupPosition).getBzStockOrderItemDtos() .get(childPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { final BzStockOrderDto target = (BzStockOrderDto) getGroup(groupPosition); convertView = listContainer.inflate( R.layout.merchant_stock_order_adapter_group, parent, false); TextView tv_msoag_serial_no = (TextView) convertView .findViewById(R.id.tv_msoag_serial_no); tv_msoag_serial_no.setText(StringHelper.trimToEmpty(target .getOrderSerialNo())); TextView tv_msoag_edc = (TextView) convertView .findViewById(R.id.tv_msoag_edc); tv_msoag_edc.setText(DateUtil.formatDate(target.getOrderEdc())); Button btn_msoag_finished = (Button) convertView .findViewById(R.id.btn_msoag_finished); btn_msoag_finished.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addStockOrderFinishedTask(target.getId()); } }); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final BzStockOrderItemDto target = (BzStockOrderItemDto) getChild( groupPosition, childPosition); convertView = listContainer.inflate( R.layout.merchant_stock_order_adapter_group_item, parent, false); AsyncImageView aiv_msoagi_product_ico = (AsyncImageView) convertView .findViewById(R.id.aiv_msoagi_product_ico); BzProductDto bzProductDto = target.getBzProductDto(); if (bzProductDto.getBzProductAttachmentIds() != null && bzProductDto.getBzProductAttachmentIds().size() > 0) { aiv_msoagi_product_ico .setDefaultImageResource(R.drawable.async_loader); aiv_msoagi_product_ico.setPath(DownLoadHelper .getDownloadProductPath(bzProductDto .getBzProductAttachmentIds().get(0), AppConstants.IMAGE_SIZE_64X64)); } TextView tv_msoagi_product_name = (TextView) convertView .findViewById(R.id.tv_msoagi_product_name); tv_msoagi_product_name.setText(StringHelper.trimToEmpty(target .getBzProductDto().getProductName())); TextView tv_msoagi_buy_num = (TextView) convertView .findViewById(R.id.tv_msoagi_buy_num); tv_msoagi_buy_num.setText(StringHelper.longToString(target .getItemNum())); return convertView; } } }
gpl-3.0
oswetto/LoboEvolution
LoboJTattoo/src/main/java/com/jtattoo/plaf/acryl/AcrylComboBoxUI.java
2470
/* * Copyright (c) 2002 and later by MH Software-Entwicklung. All Rights Reserved. * * JTattoo is multiple licensed. If your are an open source developer you can use * it under the terms and conditions of the GNU General Public License version 2.0 * or later as published by the Free Software Foundation. * * see: gpl-2.0.txt * * If you pay for a license you will become a registered user who could use the * software under the terms and conditions of the GNU Lesser General Public License * version 2.0 or later with classpath exception as published by the Free Software * Foundation. * * see: lgpl-2.0.txt * see: classpath-exception.txt * * Registered users could also use JTattoo under the terms and conditions of the * Apache License, Version 2.0 as published by the Apache Software Foundation. * * see: APACHE-LICENSE-2.0.txt */ package com.jtattoo.plaf.acryl; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.border.Border; import javax.swing.plaf.ComponentUI; import com.jtattoo.plaf.AbstractLookAndFeel; import com.jtattoo.plaf.BaseComboBoxUI; import com.jtattoo.plaf.ColorHelper; import com.jtattoo.plaf.JTattooUtilities; /** * <p>AcrylComboBoxUI class.</p> * * Author Michael Hagen * */ public class AcrylComboBoxUI extends BaseComboBoxUI { /** {@inheritDoc} */ public static ComponentUI createUI(JComponent c) { return new AcrylComboBoxUI(); } /** {@inheritDoc} */ @Override public JButton createArrowButton() { ArrowButton button = new BaseComboBoxUI.ArrowButton(); Color borderColor = ColorHelper.brighter(AbstractLookAndFeel.getTheme().getFrameColor(), 50); if (JTattooUtilities.isLeftToRight(comboBox)) { Border border = BorderFactory.createMatteBorder(0, 1, 0, 0, borderColor); button.setBorder(border); } else { Border border = BorderFactory.createMatteBorder(0, 0, 0, 1, borderColor); button.setBorder(border); } return button; } /** {@inheritDoc} */ @Override protected void setButtonBorder() { Color borderColor = ColorHelper.brighter(AbstractLookAndFeel.getTheme().getFrameColor(), 50); if (JTattooUtilities.isLeftToRight(comboBox)) { Border border = BorderFactory.createMatteBorder(0, 1, 0, 0, borderColor); arrowButton.setBorder(border); } else { Border border = BorderFactory.createMatteBorder(0, 0, 0, 1, borderColor); arrowButton.setBorder(border); } } } // end of class AcrylComboBoxUI
gpl-3.0
ProjectAlphaES/AdVenture-Capitalist
src/es/projectalpha/ac/jobs/list/Oil.java
334
package es.projectalpha.ac.jobs.list; import es.projectalpha.ac.jobs.Job; public class Oil extends Job { public Oil(){ super("Oil Company", 25798901760D); setProductionReward(29668737024D); setProductionTime(36864); //10:14:24 setCoefficient(1.07); setUpgradeBase(getCost()); } }
gpl-3.0
zfedoran/bubble-physics
bubblephysics/bubblephysics/physics/spring.cs
3281
/* * Copyright (C) 2009-2012 - Zelimir Fedoran * * This file is part of Bubble Physics. * * Bubble Physics 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. * * Bubble Physics 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 Bubble Physics. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace bubblephysics.physics { public class Spring { public float damping; public float k; public float d; public PointMass pointmass_a; public PointMass pointmass_b; public Spring(PointMass pointmass_a, PointMass pointmass_b, float k, float damping) : this(pointmass_a, pointmass_b, k, damping, 0) { Reset(); } public Spring(PointMass pointmass_a, PointMass pointmass_b, float k, float damping, float length) { this.pointmass_a = pointmass_a; this.pointmass_b = pointmass_b; this.d = length; this.k = k; this.damping = damping; } public override string ToString() { return string.Format("{{a:[{0}] b:[{1}] length:{2}}}", pointmass_a, pointmass_b, d); } public void Reset() { d = (pointmass_a.position - pointmass_b.position).Length(); } public static void SpringForce(ref Spring spring, out Vector2 forceOut) { SpringForce(ref spring.pointmass_a.position, ref spring.pointmass_a.velocity, ref spring.pointmass_b.position, ref spring.pointmass_b.velocity, spring.d, spring.k, spring.damping, out forceOut); } public static void SpringForce(ref Vector2 posA, ref Vector2 velA, ref Vector2 posB, ref Vector2 velB, float springD, float springK, float damping, out Vector2 forceOut) { #if XBOX360 forceOut = new Vector2(); #endif float BtoAX = (posA.X - posB.X); float BtoAY = (posA.Y - posB.Y); float dist = (float)Math.Sqrt((BtoAX * BtoAX) + (BtoAY * BtoAY)); if (dist > 0.0001f) { BtoAX /= dist; BtoAY /= dist; } else { forceOut.X = 0; forceOut.Y = 0; return; } dist = springD - dist; float relVelX = velA.X - velB.X; float relVelY = velA.Y - velB.Y; float totalRelVel = (relVelX * BtoAX) + (relVelY * BtoAY); forceOut.X = BtoAX * ((dist * springK) - (totalRelVel * damping)); forceOut.Y = BtoAY * ((dist * springK) - (totalRelVel * damping)); } } }
gpl-3.0
zeminlu/comitaco
unittest/pldi/StrykerBinomialHeapInsertBug50x33x48Test.java
2070
/* * TACO: Translation of Annotated COde * Copyright (c) 2010 Universidad de Buenos Aires * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, * 02110-1301, USA */ package pldi; import ar.edu.taco.regresion.CollectionTestBase; import ar.uba.dc.rfm.dynalloy.visualization.VizException; public class StrykerBinomialHeapInsertBug50x33x48Test extends CollectionTestBase { @Override protected String getClassToCheck() { return "roops.core.objects.BinomialHeap"; } public void test_insertTest() throws VizException { setConfigKeyRelevantClasses("roops.core.objects.BinomialHeap,roops.core.objects.BinomialHeapNode"); setConfigKeyRelevancyAnalysis(true); setConfigKeyCheckNullDereference(true); setConfigKeyUseJavaArithmetic(false); setConfigKeyInferScope(true); setConfigKeyObjectScope(0); setConfigKeyIntBithwidth(4); setConfigKeyLoopUnroll(4); setConfigKeySkolemizeInstanceInvariant(true); setConfigKeySkolemizeInstanceAbstraction(false); setConfigKeyGenerateUnitTestCase(true); setConfigKeyAttemptToCorrectBug(true); setConfigKeyMaxStrykerMethodsPerFile(1); setConfigKeyRemoveQuantifiers(true); setConfigKeyUseJavaSBP(true); setConfigKeyUseTightUpperBounds(true); setConfigKeyTypeScopes("roops.core.objects.BinomialHeap:1,roops.core.objects.BinomialHeapNode:7"); check(GENERIC_PROPERTIES, "insert_0", true); } }
gpl-3.0
barnex/bruteray
tracer/lights/doc.go
155
/* Package lights provides implementations of the tracer.Light interface. - general transform (either orthonormal or scales intensity) */ package lights
gpl-3.0
munshkr/ripple
src/Workspace.cpp
2840
#include "Workspace.h" #define SPLIT_SCREEN Workspace::Workspace() { // create log viewers for each REPL replLog = new ReplLog(repl); screplLog = new ReplLog(screpl); createEditor(repl); createEditor(screpl); #ifdef SPLIT_SCREEN // 3rd editor for split screen Editor* ed = createEditor(); subThread.setEditor(ed); subThread.startThread(true); #endif repl.start("data/tidalStartup.hss"); screpl.start("data/scStartup.scd"); currentEditor = 0; showReplBuffer = true; // force resize to position editors int w = (ofGetWindowMode() == OF_WINDOW) ? ofGetViewportWidth() : ofGetScreenWidth(); int h = (ofGetWindowMode() == OF_WINDOW) ? ofGetViewportHeight() : ofGetScreenHeight(); resize(w, h); } Workspace::~Workspace() { editors.clear(); delete replLog; delete screplLog; } void Workspace::draw() { if (showReplBuffer) { if (editors[currentEditor]->getRepl() == &repl) { replLog->draw(); } else { screplLog->draw(); } } #ifdef SPLIT_SCREEN // Render both editors editors[currentEditor]->draw(); editors[2]->draw(); #else editors[currentEditor]->draw(); #endif } void Workspace::update() { for (auto it = editors.begin(); it < editors.end(); it++) { Repl* repl = (*it)->getRepl(); if (repl) repl->readAsync(); } } void Workspace::keyPressed(int key) { bool modifierPressed = ofxEditor::getSuperAsModifier() ? ofGetKeyPressed(OF_KEY_SUPER) : ofGetKeyPressed(OF_KEY_CONTROL); if (modifierPressed) { switch (key) { case '1': currentEditor = 0; return; case '2': currentEditor = 1; return; case 'o': setReplBuffer(!getReplBuffer()); return; } } editors[currentEditor]->keyPressed(key); } void Workspace::resize(int w, int h) { #ifdef SPLIT_SCREEN editors[0]->setViewportX(0); editors[0]->setViewportY(h / 2); editors[1]->setViewportX(0); editors[1]->setViewportY(h / 2); editors[2]->setViewportX(w / 2); editors[2]->setViewportY(h / 2); #endif for (auto it = editors.begin(); it < editors.end(); it++) { (*it)->resize(w, h); } } void Workspace::quit() { this->screpl.eval("Server.killAll()"); #ifdef SPLIT_SCREEN subThread.stopThread(); #endif } void Workspace::setReplBuffer(bool value) { showReplBuffer = value; } bool Workspace::getReplBuffer() const { return showReplBuffer; } Editor* Workspace::createEditor(Repl& repl) { Editor* e = new Editor(); editors.push_back(e); e->setRepl(&repl); return e; } Editor* Workspace::createEditor() { Editor* e = new Editor(); editors.push_back(e); return e; }
gpl-3.0
Team-Olga/Olga-Verkkokauppa
imports/plugins/custom/olga/server/methods/supplyContracts.app-test.js
10741
import { Meteor } from "meteor/meteor"; import { chai } from "meteor/practicalmeteor:chai"; import { Factory } from "meteor/dburles:factory"; import { Random } from "meteor/random"; import StubCollections from "meteor/hwillson:stub-collections"; import { sinon } from "meteor/practicalmeteor:sinon"; import { resetDatabase } from 'meteor/xolvio:cleaner'; import { $ } from 'meteor/jquery'; import { Reaction } from "/server/api"; import { Roles } from "meteor/alanning:roles"; import { UserChecks } from "../helpers/userChecks"; import { addProduct } from "/server/imports/fixtures/products"; import Fixtures from "/server/imports/fixtures"; import { Products, Orders } from "/lib/collections"; import { SupplyContracts } from "../../lib/collections"; Fixtures(); describe.skip("SupplyContracts methods test", function() { this.timeout(5000); let methods; let sandbox; let testProducts; let testOrders; let testSupplyContracts; before(function(){ methods = { "createSupplyContract": Meteor.server.method_handlers["supplyContracts.create"], "supplyContracts/delete": Meteor.server.method_handlers["supplyContracts/delete"] }; }); beforeEach(function(done) { this.timeout(5000); sandbox = sinon.sandbox.create(); sandbox.stub(Orders._hookAspects.insert.before[0], "aspect"); sandbox.stub(Orders._hookAspects.update.before[0], "aspect"); sandbox.stub(Meteor.server.method_handlers, "inventory/register", function () { check(arguments, [Match.Any]); }); sandbox.stub(Meteor.server.method_handlers, "inventory/sold", function () { check(arguments, [Match.Any]); }); let order = Factory.create("order"); sandbox.stub(Reaction, "getShopId", () => order.shopId); testProducts = []; testOrders = []; testSupplyContracts = []; _.times(4, function(index) { testProducts.push(addProduct()); }); let productSupplies = []; productSupplies.push([ { productId: testProducts[0]._id, supplyContracts: [], openQuantity: 3 }, { productId: testProducts[2]._id, supplyContracts: [], openQuantity: 3 } ]); productSupplies.push([ { productId: testProducts[2]._id, supplyContracts: [], openQuantity: 3 }, { productId: testProducts[1]._id, supplyContracts: [], openQuantity: 3 } ]); productSupplies.push([ { productId: testProducts[2]._id, supplyContracts: [], openQuantity: 2 }, { productId: testProducts[0]._id, supplyContracts: [], openQuantity: 2 } ]); productSupplies.push([ { productId: testProducts[2]._id, supplyContracts: [], openQuantity: 9 }, { productId: testProducts[1]._id, supplyContracts: [], openQuantity: 9 } ]); productSupplies.push([ { productId: testProducts[2]._id, supplyContracts: [], openQuantity: 1 }, { productId: testProducts[1]._id, supplyContracts: [], openQuantity: 1 } ]); _.times(5, function(index) { let order = Factory.create("order"); Orders.update(order._id, { $set: { productSupplies: productSupplies[index] } }); testOrders.push(Orders.find({ _id: order._id })); }); return done(); }); afterEach(function () { Products.direct.remove({}); Orders.direct.remove({}); SupplyContracts.direct.remove({}); sandbox.restore(); }); it("should throw error if non-admin/non-supplier tries to create a supplyContract", function(done) { sandbox.stub(Reaction, "hasAdminAccess", () => false); sandbox.stub(Roles, "userIsInRole", () => false); const insertContractSpy = sandbox.spy(SupplyContracts, "insert"); chai.expect(() => Meteor.call("supplyContracts/create", testProducts[0]._id, 3)).to.throw(Meteor.Error, /Access Denied/); chai.expect(insertContractSpy).to.not.have.been.called; return done(); }); it("should not create a supplyContract if no orders are waiting for supply", function(done) { sandbox.stub(Reaction, "hasAdminAccess", () => true); sandbox.stub(Roles, "userIsInRole", () => true); const insertContractSpy = sandbox.spy(SupplyContracts, "insert"); Meteor.call("supplyContracts/create", testProducts[3]._id, 1); chai.expect(insertContractSpy).to.not.have.been.called; return done(); }); it("should create a supplyContract when one order exactly covers the quantity", function(done) { sandbox.stub(Reaction, "hasAdminAccess", () => true); sandbox.stub(Roles, "userIsInRole", () => true); sandbox.stub(Meteor, "userId", () => Random.id()); const insertContractSpy = sandbox.spy(SupplyContracts, "insert"); const updateContractSpy = sandbox.spy(SupplyContracts, "update"); const updateOrderSpy = sandbox.spy(Orders, "update"); let contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(0); Meteor.call("supplyContracts/create", testProducts[2]._id, 3); chai.expect(insertContractSpy).to.have.been.called.once; chai.expect(updateContractSpy).to.have.been.called.once; chai.expect(updateOrderSpy).to.have.been.called.once contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(1); chai.expect(contracts[0].productId).to.equal(testProducts[2]._id); chai.expect(contracts[0].quantity).to.equal(3); chai.expect(contracts[0].orders.length).to.equal(1); return done(); }); it("should create a supplyContract when one order more than covers the quantity", function(done) { sandbox.stub(Reaction, "hasAdminAccess", () => true); sandbox.stub(Roles, "userIsInRole", () => true); sandbox.stub(Meteor, "userId", () => Random.id()); const insertContractSpy = sandbox.spy(SupplyContracts, "insert"); const updateContractSpy = sandbox.spy(SupplyContracts, "update"); const updateOrderSpy = sandbox.spy(Orders, "update"); let contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(0); Meteor.call("supplyContracts/create", testProducts[1]._id, 1); chai.expect(insertContractSpy).to.have.been.called.once; chai.expect(updateContractSpy).to.have.been.called.once; chai.expect(updateOrderSpy).to.have.been.called.once contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(1); chai.expect(contracts[0].productId).to.equal(testProducts[1]._id); chai.expect(contracts[0].quantity).to.equal(1); chai.expect(contracts[0].orders.length).to.equal(1); return done(); }); it("should create a supplyContract when multiple orders cover the quantity", function(done) { sandbox.stub(Reaction, "hasAdminAccess", () => true); sandbox.stub(Roles, "userIsInRole", () => true); sandbox.stub(Meteor, "userId", () => Random.id()); const insertContractSpy = sandbox.spy(SupplyContracts, "insert"); const updateContractSpy = sandbox.spy(SupplyContracts, "update"); const updateOrderSpy = sandbox.spy(Orders, "update"); let contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(0); Meteor.call("supplyContracts/create", testProducts[2]._id, 7); chai.expect(insertContractSpy).to.have.been.called.once; chai.expect(updateContractSpy).to.have.been.called.once; chai.expect(updateOrderSpy).to.have.been.called.once contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(1); chai.expect(contracts[0].productId).to.equal(testProducts[2]._id); chai.expect(contracts[0].quantity).to.equal(7); chai.expect(contracts[0].orders.length).to.equal(3); return done(); }); it("should delete a supplyContract when user is admin", function() { sandbox.stub(Reaction, "hasAdminAccess", () => true); let newContractId = SupplyContracts.insert({ userId: Random.id(), orders: [], productId: Random.id(), quantity: 7, sentQuantity: 0, receivedQuantity: 0 }); testSupplyContracts.push(SupplyContracts.find({ _id: newContractId })); const removeContractSpy = sandbox.spy(SupplyContracts, "remove"); let contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(1); Meteor.call("supplyContracts/delete", newContractId); chai.expect(removeContractSpy).to.have.been.called.once; contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(0); }); it("should throw error if non-admin tries to delete a supplyContract", function() { sandbox.stub(Reaction, "hasAdminAccess", () => false); let newContractId = SupplyContracts.insert({ userId: Random.id(), orders: [], productId: Random.id(), quantity: 7, sentQuantity: 0, receivedQuantity: 0 }); testSupplyContracts.push(SupplyContracts.find({ _id: newContractId })); let contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(1); const removeContractSpy = sandbox.spy(SupplyContracts, "remove"); chai.expect(() => Meteor.call("supplyContracts/delete", newContractId)).to.throw(Meteor.Error, /Access Denied/); chai.expect(removeContractSpy).to.not.have.been.called; contracts = SupplyContracts.find({}).fetch(); chai.expect(contracts.length).to.equal(1); }); })
gpl-3.0
sartim/codebloga
static/blog/assets/frontend/one-page-revolution-slider/fashion/js/blankon.rs-fashion.js
3757
var BlankonOnePageRSFashion = function () { return { // ========================================================================= // CONSTRUCTOR APP // ========================================================================= init: function () { BlankonOnePageRSFashion.handleRevolutionSlider(); }, // ========================================================================= // REVOLUTION SLIDER // ========================================================================= handleRevolutionSlider: function () { var tpj=jQuery; var revapi10; tpj(document).ready(function() { if(tpj("#rev_slider_10_1").revolution == undefined){ revslider_showDoubleJqueryError("#rev_slider_10_1"); }else{ revapi10 = tpj("#rev_slider_10_1").show().revolution({ sliderType:"standard", jsFileLocation:"../../revolution/js/", sliderLayout:"fullscreen", dottedOverlay:"none", delay:9000, navigation: { keyboardNavigation:"on", keyboard_direction: "horizontal", mouseScrollNavigation:"on", onHoverStop:"off", touch:{ touchenabled:"on", swipe_threshold: 75, swipe_min_touches: 1, swipe_direction: "vertical", drag_block_vertical: false } , bullets: { enable:true, hide_onmobile:false, style:"uranus", hide_onleave:false, direction:"vertical", h_align:"left", v_align:"center", h_offset:30, v_offset:0, space:5, tmp:'<span class="tp-bullet-inner"></span>' } }, responsiveLevels:[1240,1024,778,480], gridwidth:[1240,1024,778,480], gridheight:[868,768,960,720], lazyType:"none", shadow:0, spinner:"off", stopLoop:"on", stopAfterLoops:0, stopAtSlide:1, shuffle:"off", autoHeight:"off", fullScreenAlignForce:"off", fullScreenOffsetContainer: "", fullScreenOffset: "", disableProgressBar:"on", hideThumbsOnMobile:"off", hideSliderAtLimit:0, hideCaptionAtLimit:0, hideAllCaptionAtLilmit:0, debugMode:false, fallbacks: { simplifyAll:"off", nextSlideOnWindowFocus:"off", disableFocusListener:false, } }); } }); /*ready*/ } }; }(); // Call main app init BlankonOnePageRSFashion.init();
gpl-3.0
Chilinot/SurvivalGamesMultiverse
src/main/java/se/lucasarnstrom/survivalgamesmultiverse/Config.java
3917
/** * Name: Config.java * Date: 14:27:53 - 8 sep 2012 * * Author: LucasEmanuel @ bukkit forums * * * Copyright 2013 Lucas Arnström * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Filedescription: * * * * * */ package se.lucasarnstrom.survivalgamesmultiverse; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; public class Config { @SuppressWarnings("serial") public static void load(JavaPlugin plugin) { FileConfiguration config = plugin.getConfig(); boolean save = false; HashMap<String, Object> world_defaults = new HashMap<String, Object>() {{ put("players_to_wait_for", 2); put("enable_healthregeneration", true); put("blockfilter", false); put("enable_abilities", true); put("grace.enabled", true); put("grace.time_in_seconds", 15); }}; // -- Fix old entries if(config.contains("worldnames")) { for(String name : config.getStringList("worldnames")) { for(Entry<String, Object> entry : world_defaults.entrySet()) { config.set("worlds." + name + "." + entry.getKey(), entry.getValue()); } } // Remove the now obsolete entry config.set("worldnames", null); save = true; } if(!config.contains("worlds")) { // This doesn't need to be any more specific. config.set("worlds.survivalgames1.players_to_wait_for", 2); config.set("worlds.survivalgames2.players_to_wait_for", 2); save = true; } // Add missing settings to existing worlds. if(config.contains("worlds")) { for(String name : config.getConfigurationSection("worlds").getKeys(false)) { for(Entry<String, Object> entry : world_defaults.entrySet()) { String key = "worlds." + name + "." + entry.getKey(); if(!config.contains(key)) config.set(key, entry.getValue()); } save = true; } } // -- Default entries HashMap<String, Object> defaults = new HashMap<String, Object>() {{ // General put("debug", false); put("lobbyworld", "world"); put("allowedCommandsInGame", new ArrayList<String>() {{ add("/sgplayers"); add("/sgleave"); }}); // Update put("auto-update", true); // Backup put("backup.inventories", true); // Halloween put("halloween.enabled", false); put("halloween.forcepumpkin", false); // Time put("timeoutTillStart", 120); put("timeoutTillArenaInSeconds", 180); put("timeoutAfterArena", 60); // Database put("database.enabled", false); put("database.auth.username", "username"); put("database.auth.password", "password"); put("database.settings.host", "localhost"); put("database.settings.port", 3306); put("database.settings.database", "survivalgames"); put("database.settings.tablename", "sg_stats"); // Abilities put("abilities.enabled", true); put("abilities.compass.enabled", true); put("abilities.compass.duration_in_seconds", 30); }}; for(Entry<String, Object> entry : defaults.entrySet()) { if(!config.contains(entry.getKey())) { config.set(entry.getKey(), entry.getValue()); save = true; } } if(save) { plugin.saveConfig(); } } }
gpl-3.0
MeteorAdminz/dnSpy
dnSpy/dnSpy/Text/Editor/TextViewModel.cs
2101
/* Copyright (C) 2014-2016 de4dot@gmail.com This file is part of dnSpy dnSpy 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. dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>. */ using System; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace dnSpy.Text.Editor { sealed class TextViewModel : ITextViewModel { public PropertyCollection Properties { get; } public ITextDataModel DataModel { get; } public ITextBuffer DataBuffer => DataModel.DataBuffer; public ITextBuffer EditBuffer { get; } public ITextBuffer VisualBuffer => EditBuffer; public TextViewModel(ITextDataModel textDataModel) : this(textDataModel, textDataModel.DataBuffer) { } public TextViewModel(ITextDataModel textDataModel, ITextBuffer editBuffer) { if (textDataModel == null) throw new ArgumentNullException(nameof(textDataModel)); if (editBuffer == null) throw new ArgumentNullException(nameof(editBuffer)); Properties = new PropertyCollection(); DataModel = textDataModel; EditBuffer = editBuffer; } public SnapshotPoint GetNearestPointInVisualBuffer(SnapshotPoint editBufferPoint) => editBufferPoint; public SnapshotPoint GetNearestPointInVisualSnapshot(SnapshotPoint editBufferPoint, ITextSnapshot targetVisualSnapshot, PointTrackingMode trackingMode) => editBufferPoint.TranslateTo(targetVisualSnapshot, trackingMode); public bool IsPointInVisualBuffer(SnapshotPoint editBufferPoint, PositionAffinity affinity) => true; public void Dispose() { } } }
gpl-3.0
zebraxxl/CIL2Java
StdLibs/System/System/ComponentModel/BooleanConverter.cs
1186
using System; using System.Globalization; namespace System.ComponentModel { public class BooleanConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { throw new NotImplementedException(); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { throw new NotImplementedException(); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { throw new NotImplementedException(); } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { throw new NotImplementedException(); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { throw new NotImplementedException(); } public BooleanConverter() { throw new NotImplementedException(); } } }
gpl-3.0
Kodomo/Dazzler
BAM/lib/class/Response.inc.php
24866
<?php /* ! * This file is part of Dazzler * Copyright(c) 2011 USI - Universidad de Concepcion * * Dazzler 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. * * Dazzler 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 Dazzler. If not, see <http://www.gnu.org/licenses/>. * */ require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Db.inc.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Usuario.inc.php'; class BogusAction { public $action; public $method; public $data; public $tid; } class Response{ public $Peticiones; public $dataout; public $datain; public $Loaded; public $Error; public $isForm; public $isUpload; public $Valido; // Conexiones a Bases de Datos protected $User; protected $DB; //Conexion de Base de datos del Objeto. // Crear un objeto usuario, criterios Login, Rut. function __construct($rawdata,$post, $files){ global $IdentificadorUsuario; global $conf; $this->DB = new Db($conf->db->name, $conf->db->host, $conf->db->user, $conf->db->password, 'pg'); $this->User = new Usuario($IdentificadorUsuario); $this->Loaded = array(); $this->Load($rawdata,$post, $files); return $this->Valido; } function Load($rawdata,$post=array(), $files=array()){ if(isset($rawdata)){ // header('Content-Type: text/javascript'); $this->datain = json_decode($rawdata); $this->isForm = false; $this->isUpload = false; $this->Valido = true; $this->Peticiones = count($this->datain); $this->dataout = null; }else if(isset($post['extAction'])){ // form post $this->datain = new BogusAction(); $this->datain->action = $post['extAction']; $this->datain->method = $post['extMethod']; $this->datain->tid = isset($post['extTID']) ? $post['extTID'] : null; // not set for upload $this->datain->data = array_merge($post, $files); $this->dataout = null; $this->isUpload = $post['extUpload'] == 'true'; $this->isForm = true; $this->Valido = true; $this->Peticiones = 1; }else{ $this->dataout = null; $this->Valido = false; $this->Error = "Invalid Request"; $this->Peticiones = 0; } } function addResponse($res){ if($this->dataout == null) $this->dataout = $res; elseif(!isset($this->dataout[0])){ $this->dataout = array($this->dataout); $this->dataout[] = $res; } else{ $this->dataout[] = $res; } } function echoResponse(){ header("Cache-Control: no-store, no-cache"); echo json_encode($this->dataout); } function guestRequests(){ if($this->Peticiones == 1) $this->doGuestRPC($this->datain); else{ foreach($this->datain as $datain){ $this->doGuestRPC($datain); } } } function userRequest(){ if($this->Peticiones == 1) $this->doUserRPC($this->datain); else{ foreach($this->datain as $datain){ $this->doUserRPC($datain); } } } function doGuestRPC($request){ global $IdentificadorUsuario; $response = array('type'=>'rpc','tid'=>$request->tid,'action'=>$request->action,'method'=>$request->method,'level'=>'Guest' ); if(!strcmp($request->action, 'Remote')){ /* Accion unica */ if(!strcmp($request->method, 'login')){/* Metodo único, logueo */ $params = isset($request->data) && is_array($request->data) ? $request->data : array(); $loginUsername = isset($params["loginUsername"]) ? $params["loginUsername"] : ""; $elogin = $this->DB->EscapeString($loginUsername); $epass = $this->DB->EscapeString($params["loginPassword"]); $n = $this->DB->Consulta("select id,activo from usuarios where login = '{$elogin}' and clave = '{$epass}'"); if ($n == 1){ list ($IdentificadorUsuario,$activo) = $this->DB->Sacatupla(); // Check for current sessions $this->DB->Consulta("select sesion from usuarios where id = {$IdentificadorUsuario}"); list ($lasSSID) = $this->DB->SacaTupla(); if( $lasSSID > 0){ //- dirty logout! $this->DB->Consulta("select fin,estado from sesiones where id = {$lasSSID}"); list ($UltimoT, $EstadoF) = $this->DB->SacaTupla(); $Delta = $UltimoT - time(); if(($EstadoF == 0) && ($Delta < 900)){ //- conectado y ultimo acceso hace menos de 15 minutos //- Considera desconexion por logeo de otra ubicacion $this->DB->Consulta("update sesiones set estado=3 where id = {$lasSSID}"); } elseif($EstadoF == 0){ //- conectado y ultimo acceso hace +15 minutos //- Considera timeout $this->DB->Consulta("update sesiones set estado=2 where id = {$lasSSID}"); } else{ //- no conectado? //- Considera error } } //Fill session data! if (!empty($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])){ $Ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]; }else{ $Ip = $_SERVER["REMOTE_ADDR"]; } require($_SERVER['DOCUMENT_ROOT'].'/BAM/lib/GeoIp/geoip.inc.php'); $gi = geoip_open($_SERVER['DOCUMENT_ROOT']."/BAM/lib/GeoIp/GeoIP.dat",GEOIP_STANDARD); $cid = geoip_country_id_by_addr($gi, $Ip); require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Plataforma.inc.php'; $Plat = new Plataforma($_SERVER['HTTP_USER_AGENT']); $pixels = intval($params["spixels"]); $ancho = intval($params["swidth"]); $IpL = ip2long($Ip); $EUA = $this->DB->EscapeString($_SERVER['HTTP_USER_AGENT']); $Ahora = time(); $this->DB->Consulta("select nextval('sesiones_id_seq'::regclass)"); list($nextid) = $this->DB->SacaTupla(); if($activo == 0){ $this->DB->Consulta("insert into sesiones (id,inicio,fin,usuario,estado,ip,useragent,so,navegador,pais,p,w) Values($nextid,$Ahora,$Ahora,$IdentificadorUsuario,5,$IpL,'$EUA',{$Plat->NumOs},{$Plat->NumBrow},$cid,$pixels,$ancho)"); $this->DB->Consulta("update usuarios set sesion=0 where id = {$IdentificadorUsuario}"); $response['result']["success"] = false; $response['result']["error"]["reason"] = "Esta cuenta ha sido desactivada por el administrador del sistema."; } else{ $this->DB->Consulta("insert into sesiones (id,inicio,fin,usuario,estado,ip,useragent,so,navegador,pais,p,w) Values($nextid,$Ahora,$Ahora,$IdentificadorUsuario,0,$IpL,'$EUA',{$Plat->NumOs},{$Plat->NumBrow},$cid,$pixels,$ancho)"); $_SESSION['SesionId'] = $nextid; $this->DB->Consulta("update usuarios set sesion=$nextid where id = {$IdentificadorUsuario}"); $response['result']["success"] = true; } } else { $response['result']["success"] = false; $response['result']["error"]["reason"] = "Nombre de usuario o clave incorrecta. Inténtelo nuevamente."; } } else{ $response['result']["success"] = false; $response['result']["error"]["reason"] = "Método desconocido: ".$request->action.".".$request->method; } } elseif(!strcmp($request->action, 'core')){ /* Acciones de la aplicacion */ if(!strcmp($request->method, 'Logout')){ unset($_SESSION); $response['result']["success"] = true; } else{ /* Cualquier otro evento indica que el usuario esta realmente deslogueado */ $event = array('type'=>'event','name'=>'lpc','data'=>'login'); $this->addResponse($event); $response['result']["success"] = false; $response['result']["error"]["reason"] = "Método desconocido: ".$request->action.".".$request->method; } } else{ $response['result']["success"] = false; $response['result']["error"]["reason"] = "Acción desconocida: ".$request->action; /* Se asume que intento acceder una RPC de usuario logueado, envia evento de logeo */ $event = array('type'=>'event','name'=>'lpc','data'=>'login'); $this->addResponse($event); } $this->addResponse($response); } function doUserRPC($request){ $response = array('type'=>'rpc','tid'=>$request->tid,'action'=>$request->action,'method'=>$request->method,'level'=>'User' ); if(!strcmp($request->action, 'core')){ /* Acciones de la aplicacion */ if(!strcmp($request->method, 'getTree')){/* Metodo para obtener los nodos del Treepanel */ list($crap,$nid) = explode('.',$request->data[0]); $tree = array(); $this->DB->Consulta("select contenido.id as xid,contenido.tipo,contenido.hijos,contenido.nombre as text,contenido.icon as xicon from (contenido left join gcontenido on (contenido.id = gcontenido.cid)) where contenido.id > 1 and contenido.pid = {$nid} and gcontenido.gid in (select gid from gusuarios where uid = {$this->User->Uid}) order by contenido.pos asc;"); while($el = $this->DB->Sacatupla(false)){ if ($el['hijos'] > 0) $el['leaf'] = false; else $el['leaf'] = true; $el['id'] = 'menunode.'.$el['xid']; $tree[$el['xid']] = $el; } $response['result'] = array_values($tree); } elseif(!strcmp($request->method, 'show')){ $contentId = intval($request->data[0]); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); list($code,$tipo) = $this->DB->SacaTupla(); if($tipo == 2){ $code = file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( "App_show" )){ $show = App_show(); $response['result']["success"] = true; $response['result']["nodeid"] = $contentId; if($request->data[1]){ if(function_exists ( "App_define" )){ $define = App_define(); } $response['result']['show'] = "<script>$define $show</script>"; } else{ $response['result']['show'] = "<script>$show</script>"; } } else{ $response['result']["success"] = false; $response['result']["error"]["reason"] = "Show is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["error"]["reason"] = "Invalid Id:".$contentId; } } elseif(!strcmp($request->method, 'Logout')){ $now = time(); $this->DB->Consulta("update sesiones set fin=$now,estado=1 where id = {$_SESSION['SesionId']}"); $this->DB->Consulta("update usuarios set sesion=0 where id = {$this->User->Uid}"); session_destroy(); $response['result']["success"] = true; } elseif(!strcmp($request->method, 'userGroups')){ $response['result'] = array(); $response['result']['groups'] = array(); $this->DB->Consulta("select count(*) from gusuarios where uid={$this->User->Uid}"); list ($response['result']['totalCount']) = $this->DB->SacaTupla(); $this->DB->Consulta("select id,nombre from grupos where id in (select gid from gusuarios where uid = {$this->User->Uid}) order by {$request->data[0]->sort} {$request->data[0]->dir} offset {$request->data[0]->start} limit {$request->data[0]->limit};"); while($t = $this->DB->SacaTupla(false)){ $response['result']['groups'][] = $t; } $response['result']['success'] = true; } elseif(!strcmp($request->method, 'userSession')){ $response['result'] = array(); $response['result']['sessions'] = array(); $this->DB->Consulta("select count(*) from sesiones where usuario={$this->User->Uid}"); list ($response['result']['totalCount']) = $this->DB->SacaTupla(); require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Plataforma.inc.php'; $Plat = new Plataforma(); $this->DB->Consulta("select id,inicio,fin,ip, estado, useragent,so,navegador,pais,p,w from sesiones where usuario={$this->User->Uid} order by {$request->data[0]->sort} {$request->data[0]->dir} offset {$request->data[0]->start} limit {$request->data[0]->limit};"); while($t = $this->DB->SacaTupla(false)){ $o['ip'] = long2ip($t['ip']); $o['iptxt'] = $Plat->GEOIP_COUNTRY_NAMES[$t['pais']] . " ({$o['ip']})"; $o['ipcls'] = $Plat->GEOIP_COUNTRY_CODES[$t['pais']]; $o['inicio'] = date('H:i:s d/m/Y',$t['inicio']); $o['fin'] = date('H:i:s d/m/Y',$t['fin']); $duracion = $t['fin']-$t['inicio']; $o['duracion'] = ''; $d=$h=$m=0; if($duracion > 86400){ $d = floor($duracion / 86400); $duracion -= $d * 86400; } if($duracion > 3600){ $h = floor($duracion / 3600); $duracion -= $h * 3600; } if($duracion > 60){ $m = floor($duracion / 60); $duracion -= $m * 60; } if($d>1) $o['duracion'] .= "$d días, "; elseif($d) $o['duracion'] .= "1 día, "; if($h>1) $o['duracion'] .= "$h horas, "; elseif($h) $o['duracion'] .= "1 hora, "; if($m>1) $o['duracion'] .= "$m minutos, "; elseif($m) $o['duracion'] .= "1 minuto, "; if($duracion!=1) $o['duracion'] .= "$duracion segundos"; else $o['duracion'] .= "1 segundo"; $o['resolucion'] = $t['w'].'x'.$t['p']/$t['w']; $o['sotxt'] = $Plat->SO[$t['so']]; $o['socls'] = $Plat->SO_ico[$t['so']]; $tmp = 100* intval($t['navegador']/100); $o['navegadortxt'] = $Plat->Navegador[$tmp]; $o['navegadorcls'] = $Plat->Navegador_ico[$tmp]; $o['useragent'] = $t['useragent']; $o['estado'] = $t['estado']; if($t['estado'] == '0'){ $o['estadotxt'] = "Conectado"; } elseif($t['estado'] == '1'){ $o['estadotxt'] = "Desconectado"; } elseif($t['estado'] == '2'){ $o['estadotxt'] = "Timeout"; } elseif($t['estado'] == '3'){ $o['estadotxt'] = "Inicio desde otra ubicación"; } elseif($t['estado'] == '5'){ $o['estadotxt'] = "Usuario desactivado"; } $o['id'] = $t['id']; $response['result']['sessions'][] = $o; } $response['result']['success'] = true; } elseif(!strcmp($request->method, 'UserLoad')){ $response['result'] = array(); $response['result']['data'] = array(); $response['result']['data']['login'] = $this->User->Login; $response['result']['data']['nombre']= $this->User->Nombre; $response['result']['data']['cargo']= $this->User->Cargo; $response['result']['data']['correo']= $this->User->Correo; $response['result']['success'] = true; } elseif(!strcmp($request->method, 'UserSave')){ if(!strcmp($request->data['aclave'],$this->User->Contrasena)){ $Escaped = $this->DB->EscapeArray($request->data,array('nclave','nombre','correo','cargo')); if(!strcmp($request->data['cclave'],$request->data['nclave']) && (strlen($request->data['nclave']) >= 6 )){ $this->DB->Consulta("update usuarios set clave='{$Escaped['nclave']}', nombre='{$Escaped['nombre']}' where id = {$this->User->Uid}"); } else{ $this->DB->Consulta("update usuarios set nombre='{$Escaped['nombre']}' where id = {$this->User->Uid}"); } $response['result'] = array(); $response['result']['success'] = true; } else{ $response['result'] = array(); $response['result']["error"]["reason"] = "La clave ingresada es incorrecta."; $response['result']['success'] = false; } } else{ $response['result']["success"] = false; $response['result']["error"]["reason"] = "Método desconocido: ".$request->action.".".$request->method; } } elseif(!strcmp($request->action, 'api')){ /* Acciones de la API */ if(!strcmp($request->method, 'DirectRead')){ $contentId = intval($request->data[0]->xid); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); list($code,$tipo) = $this->DB->SacaTupla(); if($tipo == 2){ $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( "DirectRead" )){ $response['result'] = DirectRead($this->DB,$request->data[0]); } else{ $response['result']["success"] = false; $response['result']["msg"] = "DirectRead is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["msg"] = "Invalid Id:".$contentId; } } elseif(!strcmp($request->method, 'DirectCreate')){ $contentId = intval($request->data[0]->xid); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); list($code,$tipo) = $this->DB->SacaTupla(); if($tipo == 2){ $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( "DirectCreate" )){ $response['result'] = DirectCreate($this->DB,$request->data[0]); } else{ $response['result']["success"] = false; $response['result']["msg"] = "DirectCreate is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["msg"] = "Invalid Id:".$contentId; } } elseif(!strcmp($request->method, 'DirectUpdate')){ $contentId = intval($request->data[0]->xid); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); list($code,$tipo) = $this->DB->SacaTupla(); if($tipo == 2){ $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( "DirectUpdate" )){ $response['result'] = DirectUpdate($this->DB,$request->data[0]); } else{ $response['result']["users"] = array(); $response['result']["success"] = false; $response['result']["msg"] = "DirectUpdate is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["msg"] = "Invalid Id:".$contentId; } } elseif(!strcmp($request->method, 'DirectDestroy')){ $contentId = intval($request->data[0]->xid); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); list($code,$tipo) = $this->DB->SacaTupla(); if($tipo == 2){ $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( "DirectDestroy" )){ $response['result'] = DirectDestroy($this->DB,$request->data[0]); } else{ $response['result']["success"] = false; $response['result']["msg"] = "DirectDestroy is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["msg"] = "Invalid Id:".$contentId; } } elseif(!strcmp($request->method, 'getTree')){ $contentId = intval($request->data[0]->xid); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); list($code,$tipo) = $this->DB->SacaTupla(); if($tipo == 2){ $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( "getTree" )){ $response['result'] = getTree($this->DB,$request->data[0]); } else{ $response['result']["success"] = false; $response['result']["msg"] = "getTree is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["msg"] = "Invalid Id:".$contentId; } } elseif(!strcmp($request->method, 'loadForm')){ $contentId = intval($request->data[0]->xid); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); list($code,$tipo) = $this->DB->SacaTupla(); if($tipo == 2){ $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( "loadForm" )){ $response['result'] = loadForm($this->DB,$request->data[0]); } else{ $response['result']["success"] = false; $response['result']["msg"] = "loadForm is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["msg"] = "Invalid Id:".$contentId; } } elseif(!strcmp($request->method, 'submitForm')){ $contentId = intval($request->data['xid']); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); list($code,$tipo) = $this->DB->SacaTupla(); if($tipo == 2){ $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( "submitForm" )){ $response['result'] = submitForm($this->DB,$request->data); } else{ $response['result']["success"] = false; $response['result']["msg"] = "submitForm is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["msg"] = "Invalid Id:".$contentId; } } elseif(!strcmp($request->method, 'customFn')){ $contentId = intval($request->data[0]->xid); if($contentId > 0){ if(!in_array($contentId,$this->Loaded)){ $this->DB->Consulta("select contenido from contenido where id = $contentId;"); list($code) = $this->DB->SacaTupla(); if($tipo == 0){ $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); } $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); eval( $code ); $this->Loaded[] = $contentId; } if(function_exists ( $request->data[0]->customFn )){ $response['result'] = call_user_func($request->data[0]->customFn, $this->DB,$request->data[0]); } else{ $response['result']["success"] = false; $response['result']["msg"] = "{$request->data[0]->customFn} is undefined for $contentId"; } } else{ $response['result']["success"] = false; $response['result']["msg"] = "Invalid Id:".$contentId; } } else{ $response['result']["success"] = false; $response['result']["error"]["reason"] = "Método desconocido: ".$request->action.".".$request->method; } } else{ $response['result']["success"] = false; $response['result']["error"]["reason"] = "Acción desconocida: ".$request->action ; /* Se asume que intento acceder una RPC de usuario logueado, envia evento de logeo */ $event = array('type'=>'event','name'=>'lpc','data'=>'login'); $this->addResponse($event); } $this->addResponse($response); } } ?>
gpl-3.0
Sethorax/t3essentials
Classes/Service/TyposcriptLoader.php
2061
<?php namespace Sethorax\T3essentials\Service; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Class TyposcriptLoader * @package Sethorax\T3essentials\Service */ class TyposcriptLoader { /** * Returns typoscript settings for the given $_EXTKEY as an array without the dots. * * @return array */ public static function getSetup($_EXTKEY, $plugin = true) { $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager'); $configurationManager = $objectManager->get('TYPO3\\CMS\\Extbase\\Configuration\\ConfigurationManagerInterface'); $settings = $configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT); return self::removeDotsFromKeys($settings[$plugin ? 'plugin.' : 'config.'][$_EXTKEY . '.']); } /** * Creates an array without the dots from typoscript settings. * If $value is an array it will clean the dots as well. * * @param $settings * @return array */ private static function removeDotsFromKeys($settings) { $conf = []; if (is_array($settings)) { foreach ($settings as $key => $value) { $conf[self::removeDotFromString($key)] = is_array($value) ? self::removeDotsFromKeys($value) : $value; } } return $conf; } /** * Removes a dot at the end of the given $string. * * @param $string * @return mixed */ private static function removeDotFromString($string) { return preg_replace('/\.$/', '', $string); } }
gpl-3.0
dandrocec/PaaSInterop
SemanticServiceDescription/src/java/hr/org/foi/jena/SalesforceDataOntologyCreator.java
16095
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hr.org.foi.jena; import com.hp.hpl.jena.datatypes.RDFDatatype; import com.hp.hpl.jena.datatypes.xsd.XSDDatatype; import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.XSD; import com.sforce.soap.enterprise.DescribeSObjectResult; import java.util.ArrayList; import com.sforce.soap.enterprise.sobject.SObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import com.sforce.soap.enterprise.Field; import com.sforce.soap.enterprise.FieldType; import hr.org.foi.salesforce.api.services.Constants; import java.util.List; /** * * @author Darko Androcec */ public class SalesforceDataOntologyCreator { public static final String ONTOLOGY_NAME = "SalesforceDataModel#"; public static final String ONTOLOGY_DISKFILE = "D:\\DOKTORAT\\generiraneOntologije\\SalesforceDataModel.owl"; // list of retrieved data entities public static ArrayList<SObject[]> listOfEntityList = new ArrayList<SObject[]>(); // list of object metadata public static ArrayList<DescribeSObjectResult> describeList = new ArrayList<DescribeSObjectResult>(); public static ArrayList<DescribeSObjectResult> getDescribeList() { return describeList; } public static void setDescribeList(ArrayList<DescribeSObjectResult> describeList) { SalesforceDataOntologyCreator.describeList = describeList; } public static ArrayList<SObject[]> getListOfEntityList() { return listOfEntityList; } public static void setListOfEntityList(ArrayList<SObject[]> listOfEntityList) { SalesforceDataOntologyCreator.listOfEntityList = listOfEntityList; } // get data types public static List<String> getDataTypesInCurrentData() { List<String> result = new ArrayList(); if (listOfEntityList != null && listOfEntityList.size() > 0 && describeList != null && describeList.size() > 0) { System.out.println("DEBUG: List of entities list size = " + listOfEntityList.size()); // create ontology using Jena int brojac = 0; for (SObject[] objectArray : listOfEntityList) { for (int i = 0; i < objectArray.length; i++) { SObject objekt = objectArray[i]; // System.out.println("DEBUG: Naziv klase objekta " + objekt.getClass()); DescribeSObjectResult describe = describeList.get(brojac); String nazivKlase = objekt.getClass().toString(); String className = nazivKlase.substring(nazivKlase.lastIndexOf(".") + 1, nazivKlase.indexOf("__c")); if (i == 0) { // Get the fields Field[] fields = describe.getFields(); // Iterate through each field and gets its properties for (int j = 0; j < fields.length; j++) { Field field = fields[j]; // System.out.println("Field name: " + field.getName()); String fieldType = field.getType().toString(); System.out.println("Field type: " + fieldType); if (fieldType.contains("_")){ fieldType = fieldType.replace("_", ""); } // create properties of the class using key values String fieldname = field.getName(); // uzimaju se samo custom fields i Id (primary key) if (fieldname.contains("__c") || fieldname.compareTo("Id") == 0) { if (result != null && !result.contains(fieldType)) { result.add(fieldType); } } } } } } } return result; } /* * Field types in SOAP API Developer's Guide - stranica 29 ID - Primary key field for the object reference - Cross-references to a different object. Analogous to a foreign key field in SQL. */ public static void create() { if (listOfEntityList != null && listOfEntityList.size() > 0 && describeList != null && describeList.size() > 0) { System.out.println("DEBUG: List of entities list size = " + listOfEntityList.size()); // create ontology using Jena String baseURI = "http://hr.org.foi.ontology/" + ONTOLOGY_NAME; OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM); // for first element of a list, I need to create OWL class OntClass ontologyClass = null; // create object property for object relationship (similar to foreign keys) ObjectProperty objectRelationshipProperty = model.createObjectProperty(baseURI + "hasLinkToObject"); objectRelationshipProperty.setDomain(OWL.Thing); objectRelationshipProperty.setRange(OWL.Thing); // add key to identifier data ptoperty of the ontology DatatypeProperty dataKeyProperty = model.createDatatypeProperty(baseURI + "identifier"); dataKeyProperty.setDomain(OWL.Thing); dataKeyProperty.setRange(XSD.xstring); int brojac = 0; for (SObject[] objectArray : listOfEntityList) { for (int i = 0; i < objectArray.length; i++) { SObject objekt = objectArray[i]; System.out.println("DEBUG: Naziv klase objekta " + objekt.getClass()); DescribeSObjectResult describe = describeList.get(brojac); String nazivKlase = objekt.getClass().toString(); String className = nazivKlase.substring(nazivKlase.lastIndexOf(".") + 1, nazivKlase.indexOf("__c")); System.out.println("DEBUG: className" + className); if (i == 0) { // create new OWL class // System.out.println("DEBUG: Naziv klase ==> " + className); ontologyClass = model.createClass(baseURI + className); // Get the fields Field[] fields = describe.getFields(); System.out.println("Has " + fields.length + " fields"); // Iterate through each field and gets its properties for (int j = 0; j < fields.length; j++) { Field field = fields[j]; // System.out.println("Field name: " + field.getName()); System.out.println("Field type: " + field.getType().toString()); // create properties of the class using key values String fieldname = field.getName(); if (fieldname.contains("__c")) { fieldname = fieldname.substring(0, fieldname.indexOf("__c")); DatatypeProperty dataProperty = model.createDatatypeProperty(baseURI + fieldname); dataProperty.setDomain(ontologyClass); Resource resurs = DataTypeConverter.convertToOwlDataPropertyRange(TypeConstants.SALESFORCE, field.getType().toString()); dataProperty.setRange(resurs); } } } // for all elements, I need to create OWL individuals // I need to parse object string representations and find property values. // for all elements, I need to create OWL individuals if (ontologyClass != null) { int num = i + 1; // I need to parse object string representation String objectString = objekt.toString(); System.out.println("DEBUG: Object to string " + objectString); // Get the fields Field[] fields = describe.getFields(); //System.out.println("Has " + fields.length + " fields"); // Iterate through each field and gets its properties Individual individual = null; for (int j = 0; j < fields.length; j++) { Field field = fields[j]; String fieldname = field.getName(); String fieldType = field.getType().toString(); String fieldValue = objectString.substring(objectString.indexOf(fieldname)); System.out.println("DEBUG fieldname " + fieldname); // add identifier to the ontology if (fieldname.compareTo("Id") == 0) { System.out.println("DEBUG identifier full field value = " + fieldValue); fieldValue = fieldValue.substring(fieldValue.indexOf(fieldname + "=\'"), fieldValue.indexOf("\'\n")); fieldValue = fieldValue.substring(fieldValue.indexOf("\'") + 1); System.out.println("DEBUG identifierValue = " + fieldValue); individual = model.createIndividual(baseURI + className + "_" + fieldValue, ontologyClass); if (dataKeyProperty != null ) { individual.addProperty(dataKeyProperty, fieldValue, XSDDatatype.XSDstring); } } if (fieldname.contains("__c")) { fieldValue = fieldValue.substring(fieldValue.indexOf(fieldname + "=\'"), fieldValue.indexOf("\'\n")); fieldValue = fieldValue.substring(fieldValue.indexOf("\'") + 1); System.out.println("DEBUG fieldValue = " + fieldValue); fieldname = fieldname.substring(0, fieldname.indexOf("__c")); System.out.println("DEBUG: fieldname == " + fieldname); DatatypeProperty dataProperty = model.getDatatypeProperty(baseURI + fieldname); // TODO: implement mapper for data type RDFDatatype datatype = DataTypeConverter.convertToOwlDataTypesForIndividual(TypeConstants.SALESFORCE, field.getType().toString()); individual.addProperty(dataProperty, fieldValue, datatype); } } } } brojac++; } // add instances for hasLinkObject properties - for foreign key relationship brojac = 0; for (SObject[] objectArray : listOfEntityList) { for (int i = 0; i < objectArray.length; i++) { SObject objekt = objectArray[i]; DescribeSObjectResult describe = describeList.get(brojac); String objectString = objekt.toString(); Field[] fields = describe.getFields(); System.out.println("Has " + fields.length + " fields"); // Iterate through each field and gets its properties for (int j = 0; j < fields.length; j++) { Field field = fields[j]; String fieldName = field.getName(); String fieldType = field.getType().toString(); if (fieldName.contains("__c") && fieldType.compareTo(Constants.SALESFORCE_REFERENCE_DATATYPE) == 0) { System.out.println("DEBUG: Reference is found in " + fieldName); String master = objectString.substring(objectString.indexOf("[")+1, objectString.indexOf("__c")); System.out.println("DEBUG master = " + master); String child = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.indexOf("Id")); System.out.println("DEBUG child = " + child); String foreignKeyColumn = fieldName.substring(0, fieldName.indexOf("__c")); System.out.println("DEBUG foreignKeyColumn = " + foreignKeyColumn); if (model.getOntClass(baseURI + master) != null) { ExtendedIterator<Individual> individuals = model.listIndividuals(model.getOntClass(baseURI + master)); if (individuals != null) { while (individuals.hasNext()) { Individual individualMaster = individuals.next(); OntProperty foreignKeyProperty = model.getOntProperty(baseURI + foreignKeyColumn); if (foreignKeyProperty != null) { RDFNode iValue = individualMaster.getPropertyValue(foreignKeyProperty); if (iValue != null) { String foreignId = iValue.toString(); if (foreignId != null) { String childIndividualString = child + "_" + foreignId; System.out.println("DEBUG childIndividualString = " + childIndividualString); childIndividualString = childIndividualString.substring(0, childIndividualString.indexOf("^^")); Individual childIndividual = model.getIndividual(baseURI + childIndividualString); System.out.println("DEBUG childIndividual = " + childIndividual); if (childIndividual != null) { individualMaster.addProperty(objectRelationshipProperty, childIndividual); } } } } } } } } } } brojac++; } // on the end, write ontology to a specified file try { File file = new File(ONTOLOGY_DISKFILE); model.write(new FileOutputStream(file)); } catch (IOException e) { e.printStackTrace(); } } } }
gpl-3.0
nelmio/techup-mobile
app/views/EventAttendees.js
1658
/** * * @copyright (c) 2011 Nelmio * @license http://opensource.org/licenses/gpl-3.0.html GNU Public License, version 3 * */ techup.views.EventAttendees = Ext.extend(Ext.Panel, { record: undefined, layout: 'fit', dockedItems: [ { xtype: 'toolbar', title: 'Attendees', items: [ { text: 'Event', ui: 'back', listeners: { 'tap': function () { Ext.dispatch({ controller: techup.controllers.events, action: 'show', record: techup.views.eventAttendees.items.record, animation: {type:'slide', direction:'right'} }); } } } ] } ], items: [ { xtype: 'list', id: 'eventattendees', itemCls: 'avatar-list-item attendees', itemTpl: [ '<img class="avatar-img small" src="http://img.tweetimag.es/i/{twitter_handle}_n"/>', '<div class="name">{fullname}</div>', '<div class="date">@{twitter_handle}</div>' ], store: false } ], updateWithRecord: function(record) { this.items.record = record; var store = new Ext.data.JsonStore({ model: 'techup.Attendee', data: record.data.attendees }); Ext.getCmp('eventattendees').bindStore(store); } });
gpl-3.0
psci2195/espresso-ffans
src/core/collision.hpp
5602
/* * Copyright (C) 2011-2019 The ESPResSo project * * This file is part of ESPResSo. * * ESPResSo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ESPResSo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _COLLISION_H #define _COLLISION_H /** \name bits of possible modes for collision handling. * The modes can be combined by or-ing together, but not all combinations are * possible. */ /*@{*/ #define COLLISION_MODE_OFF 0 /// Just create bond between centers of colliding particles #define COLLISION_MODE_BOND 2 /** Create a bond between the centers of the colliding particles, * plus two virtual sites at the point of collision and bind them * together. This prevents the particles from sliding against each * other. Requires VIRTUAL_SITES_RELATIVE and @ref COLLISION_MODE_BOND */ #define COLLISION_MODE_VS 4 /** Glue a particle to a specific spot on the surface of an other */ #define COLLISION_MODE_GLUE_TO_SURF 8 /// Three particle binding mode #define COLLISION_MODE_BIND_THREE_PARTICLES 16 /*@}*/ #include "Particle.hpp" #include "bonded_interactions/bonded_interaction_data.hpp" #include "integrate.hpp" #include "virtual_sites.hpp" class Collision_parameters { public: Collision_parameters() : mode(COLLISION_MODE_OFF), distance(0.), distance2(0.), bond_centers(-1), bond_vs(-1), bond_three_particles(-1){}; /// collision handling mode, a combination of constants COLLISION_MODE_* int mode; /// distance at which particles are bound double distance; // Square of distance at which particle are bound double distance2; /// bond type used between centers of colliding particles int bond_centers; /// bond type used between virtual sites int bond_vs; /// particle type for virtual sites created on collision int vs_particle_type; /** Raise exception on collision */ bool exception_on_collision; /// For mode "glue to surface": The distance from the particle which is to be /// glued to the new virtual site double dist_glued_part_to_vs; /// For mode "glue to surface": The particle type being glued int part_type_to_be_glued; /// For mode "glue to surface": The particle type to which the virtual site is /// attached int part_type_to_attach_vs_to; /// Particle type to which the newly glued particle is converted int part_type_after_glueing; /// First bond type (for zero degrees) used for the three-particle bond /// (angle potential) int bond_three_particles; /// Number of angle bonds to use (angular resolution) /// different angle bonds with different equilibrium angles /// Are expected to have ids immediately following to bond_three_particles int three_particle_angle_resolution; /** Placement of virtual sites for MODE_VS. * 0=on same particle as related to, * 1=on collision partner, * 0.5=in the middle between */ double vs_placement; }; /// Parameters for collision detection extern Collision_parameters collision_params; #ifdef COLLISION_DETECTION void prepare_local_collision_queue(); /// Handle the collisions recorded in the queue void handle_collisions(); /** @brief Validates collision parameters and creates particle types if needed */ bool validate_collision_parameters(); /** @brief Add the collision between the given particle ids to the collision * queue */ void queue_collision(int part1, int part2); /** @brief Check additional criteria for the glue_to_surface collision mode */ inline bool glue_to_surface_criterion(Particle const &p1, Particle const &p2) { return (((p1.p.type == collision_params.part_type_to_be_glued) && (p2.p.type == collision_params.part_type_to_attach_vs_to)) || ((p2.p.type == collision_params.part_type_to_be_glued) && (p1.p.type == collision_params.part_type_to_attach_vs_to))); } /** @brief Detect (and queue) a collision between the given particles. */ inline void detect_collision(Particle const &p1, Particle const &p2, const double &dist_betw_part2) { if (dist_betw_part2 > collision_params.distance2) return; // If we are in the glue to surface mode, check that the particles // are of the right type if (collision_params.mode & COLLISION_MODE_GLUE_TO_SURF) if (!glue_to_surface_criterion(p1, p2)) return; #ifdef VIRTUAL_SITES_RELATIVE // Ignore virtual particles if ((p1.p.is_virtual) || (p2.p.is_virtual)) return; #endif // Check, if there's already a bond between the particles if (pair_bond_exists_on(p1, p2, collision_params.bond_centers)) return; if (pair_bond_exists_on(p2, p1, collision_params.bond_centers)) return; /* If we're still here, there is no previous bond between the particles, we have a new collision */ // do not create bond between ghost particles if (p1.l.ghost && p2.l.ghost) { return; } queue_collision(p1.p.identity, p2.p.identity); } #endif inline double collision_detection_cutoff() { #ifdef COLLISION_DETECTION if (collision_params.mode) return collision_params.distance; #endif return 0.; } #endif
gpl-3.0
javocsoft/javocsoft-toolbox
src/es/javocsoft/android/lib/toolbox/sms/observer/SMSObserver.java
12174
/* * Copyright (C) 2010-2014 - JavocSoft - Javier Gonzalez Serrano * http://javocsoft.es/proyectos/code-libs/android/javocsoft-toolbox-android-library * * This file is part of JavocSoft Android Toolbox library. * * JavocSoft Android Toolbox library 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. * * JavocSoft Android Toolbox library is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License * along with JavocSoft Android Toolbox library. If not, see * <http://www.gnu.org/licenses/>. * */ package es.javocsoft.android.lib.toolbox.sms.observer; import java.text.Normalizer; import java.util.Calendar; import android.annotation.SuppressLint; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Handler; import android.telephony.TelephonyManager; import android.util.Log; /** * SMS Observer for sent/received sms. * * Requires permissions: * * <uses-permission android:name="android.permission.READ_PHONE_STATE" /> * <uses-permission android:name="android.permission.READ_SMS" /> * <uses-permission android:name="android.permission.SEND_SMS"/> * * Usage: * * Handler smsHandler = new Handler(); * if(ToolBox.device_isHardwareFeatureAvailable(this, PackageManager.FEATURE_TELEPHONY)){ * smsObserver = new SMSObserver(smsHandler, getApplicationContext(), msgReceivedCallback, msgSentCallback); * * ContentResolver mContentResolver = getContentResolver(); * mContentResolver.registerContentObserver(Uri.parse("content://sms/"),true, smsObserver); * } * * @author JavocSoft 2013 * @version 1.0 */ public class SMSObserver extends ContentObserver { private Context context; private static int initialPos; /** Enables or disables the log. */ public static boolean LOG_ENABLE = true; private static final String TAG = "javocsoft-toolbox: SMSObserver"; private static final Uri uriSMS = Uri.parse("content://sms/"); private SMSRunnableTask msgReceivedCallback; private SMSRunnableTask msgSentCallback; /** * This is a general SMS observer. It allows to do something when a SMS is sent * or received. * * @param handler * @param ctx * @param msgReceivedCallback * @param msgSentCallback */ public SMSObserver(Handler handler, Context ctx, SMSRunnableTask msgReceivedCallback, SMSRunnableTask msgSentCallback) { super(handler); context = ctx; this.msgReceivedCallback = msgReceivedCallback; this.msgSentCallback = msgSentCallback; initialPos = getLastMsgId(); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); queryLastSentSMS(); } public synchronized int getLastMsgId() { int lastMsgId = -1; Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null); if(cur.getCount()>0){ cur.moveToFirst(); lastMsgId = cur.getInt(cur.getColumnIndex("_id")); if(LOG_ENABLE) Log.i(TAG, "Last sent message id: " + String.valueOf(lastMsgId)); } return lastMsgId; } protected synchronized void queryLastSentSMS() { new Thread(new Runnable() { @SuppressWarnings("unused") @Override public void run() { Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null); if (cur.moveToNext()) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String myDeviceId = tm.getDeviceId(); String myTelephoneNumber = tm.getLine1Number(); Calendar c = Calendar.getInstance(); int day = c.get(Calendar.DAY_OF_MONTH); int month = c.get(Calendar.MONTH); int year = c.get(Calendar.YEAR); int hour = c.get(Calendar.HOUR); int minute = c.get(Calendar.MINUTE); int seconds = c.get(Calendar.SECOND); try { String receiver = cur.getString(cur.getColumnIndex("address")); String body = cur.getString(cur.getColumnIndex("body")); String protocol = cur.getString(cur.getColumnIndex("protocol")); String reformated_body = formatBody(body); if (initialPos != getLastMsgId()) { // Only get the last SMS. SMSData smsData = new SMSData(cur); String logMessage = null; String notificationMessage = null; String smsEventType = null; if (protocol != null) { //SMS received smsEventType = "R"; logMessage = "SMS Sent: [" + day + "-" + month + "-" + year + " " + hour + ":" + minute + ":" + seconds + "]" + " From: [" + receiver + "]" + " Message: [" + reformated_body + "]"; if(msgReceivedCallback!=null){ msgReceivedCallback.setSMSData(smsData); msgReceivedCallback.setContext(context); msgReceivedCallback.start(); } }else{ //SMS sent smsEventType = "S"; logMessage = "SMS Sent: [" + day + "-" + month + "-" + year + " " + hour + ":" + minute + ":" + seconds + "]" + " Receiver: [" + receiver + "]" + " Message: [" + reformated_body + "]"; if(msgSentCallback!=null){ msgSentCallback.setSMSData(smsData); msgSentCallback.setContext(context); msgSentCallback.start(); } } if(LOG_ENABLE) Log.i(TAG, logMessage); // Then, set initialPos to the current position. initialPos = getLastMsgId(); } } catch (Exception e) { Log.e(TAG, "Error getting SMS (" + e.getMessage() + ")", e); } } cur.close(); } }).start(); } //AUXILIAR @SuppressWarnings("unused") private void printSMSFieldNames(Cursor sms_sent_cursor){ //Get Column names. String[] colNames = sms_sent_cursor.getColumnNames(); if(colNames != null){ for(int k=0; k<colNames.length; k++){ Log.i("Info","colNames["+k+"] : " + colNames[k]); } } } @SuppressWarnings("unused") private void printSMSData(Cursor sms_sent_cursor){ Log.i("Info","Id : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("_id"))); Log.i("Info","Thread Id : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("thread_id"))); Log.i("Info","Address : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("address"))); Log.i("Info","Person : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("person"))); Log.i("Info","Date : " + sms_sent_cursor.getLong(sms_sent_cursor.getColumnIndex("date"))); Log.i("Info","Read : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("read"))); Log.i("Info","Status : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("status"))); Log.i("Info","Type : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("type"))); Log.i("Info","Rep Path Present : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("reply_path_present"))); Log.i("Info","Subject : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("subject"))); Log.i("Info","Body : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("body"))); Log.i("Info","Err Code : " + sms_sent_cursor.getString(sms_sent_cursor.getColumnIndex("error_code"))); } /** * Replace all non ASCII, non-printable and control characters * * @param body * @return */ @SuppressLint("NewApi") private String formatBody(String body){ String reformated_body = null; if(android.os.Build.VERSION.SDK_INT<9){ reformated_body = body.replaceAll("[^\\x20-\\x7E]", ""); }else{ reformated_body = Normalizer.normalize(body, Normalizer.Form.NFD) .replaceAll("[^\\p{ASCII}]", ""); } return reformated_body; } /** * This class allows to do something when a sms is sent or recived. * * @author JavocSoft 2013. * @since 2013 */ public static abstract class SMSRunnableTask extends Thread implements Runnable { protected Context context; protected SMSData sms; public SMSRunnableTask() {} @Override public void run() { pre_task(); task(); post_task(); } /** * Allows to set the SMS content. * * @param sms */ protected void setSMSData (SMSData sms) { this.sms = sms; } protected void setContext (Context context) { this.context = context; } protected abstract void pre_task(); protected abstract void task(); protected abstract void post_task(); } /** * SMS information. * * @author JavocSoft 2013 * @since 2013 * */ public class SMSData { public String thread_id; public String address; public String person; public long date; public String read; public String status; public String type; public String reply_path_present; public String subject; public String body; public String formattedBody; public String error_code; public SMSData(Cursor sms_cursor) { thread_id = sms_cursor.getString(sms_cursor.getColumnIndex("thread_id")); address = sms_cursor.getString(sms_cursor.getColumnIndex("address")); person = sms_cursor.getString(sms_cursor.getColumnIndex("person")); date = sms_cursor.getLong(sms_cursor.getColumnIndex("date")); read = sms_cursor.getString(sms_cursor.getColumnIndex("read")); status = sms_cursor.getString(sms_cursor.getColumnIndex("status")); type = sms_cursor.getString(sms_cursor.getColumnIndex("type")); reply_path_present = sms_cursor.getString(sms_cursor.getColumnIndex("reply_path_present")); subject = sms_cursor.getString(sms_cursor.getColumnIndex("subject")); body = sms_cursor.getString(sms_cursor.getColumnIndex("body")); formattedBody = formatBody(body); error_code = sms_cursor.getString(sms_cursor.getColumnIndex("error_code")); } } }
gpl-3.0
fbacchella/ipmilib
sample/com/veraxsystems/vxipmi/test/ChassisControlRunner.java
4688
/* * VxipmiRunner.java * Created on 2011-09-20 * * Copyright (c) Verax Systems 2011. * All rights reserved. * * This software is furnished under a license. Use, duplication, * disclosure and all other uses are restricted to the rights * specified in the written license agreement. */ package com.veraxsystems.vxipmi.test; import java.net.InetAddress; import com.veraxsystems.vxipmi.api.async.ConnectionHandle; import com.veraxsystems.vxipmi.api.sync.IpmiConnector; import com.veraxsystems.vxipmi.coding.commands.IpmiVersion; import com.veraxsystems.vxipmi.coding.commands.PrivilegeLevel; import com.veraxsystems.vxipmi.coding.commands.chassis.ChassisControl; import com.veraxsystems.vxipmi.coding.commands.chassis.ChassisControlResponseData; import com.veraxsystems.vxipmi.coding.commands.chassis.GetChassisStatus; import com.veraxsystems.vxipmi.coding.commands.chassis.GetChassisStatusResponseData; import com.veraxsystems.vxipmi.coding.commands.chassis.PowerCommand; import com.veraxsystems.vxipmi.coding.commands.session.SetSessionPrivilegeLevel; import com.veraxsystems.vxipmi.coding.protocol.AuthenticationType; import com.veraxsystems.vxipmi.coding.security.CipherSuite; public class ChassisControlRunner { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { IpmiConnector connector; // Create the connector, specify port that will be used to communicate // with the remote host. The UDP layer starts listening at this port, so // no 2 connectors can work at the same time on the same port. connector = new IpmiConnector(6000); System.out.println("Connector created"); // Create the connection and get the handle, specify IP address of the // remote host. The connection is being registered in ConnectionManager, // the handle will be needed to identify it among other connections // (target IP address isn't enough, since we can handle multiple // connections to the same host) ConnectionHandle handle = connector.createConnection(InetAddress.getByName("192.168.1.1")); System.out.println("Connection created"); // Get available cipher suites list via getAvailableCipherSuites and // pick one of them that will be used further in the session. CipherSuite cs = connector.getAvailableCipherSuites(handle).get(3); System.out.println("Cipher suite picked"); // Provide chosen cipher suite and privilege level to the remote host. // From now on, your connection handle will contain these information. connector.getChannelAuthenticationCapabilities(handle, cs, PrivilegeLevel.Administrator); System.out.println("Channel authentication capabilities receivied"); // Start the session, provide username and password, and optionally the // BMC key (only if the remote host has two-key authentication enabled, // otherwise this parameter should be null) connector.openSession(handle, "user", "pass", null); System.out.println("Session open"); // Send some message and read the response GetChassisStatusResponseData rd = (GetChassisStatusResponseData) connector.sendMessage(handle, new GetChassisStatus(IpmiVersion.V20, cs, AuthenticationType.RMCPPlus)); System.out.println("Received answer"); System.out.println("System power state is " + (rd.isPowerOn() ? "up" : "down")); // Set session privilege level to administrator, as ChassisControl command requires this level connector.sendMessage(handle, new SetSessionPrivilegeLevel(IpmiVersion.V20, cs, AuthenticationType.RMCPPlus, PrivilegeLevel.Administrator)); ChassisControl chassisControl = null; //Power on or off if (!rd.isPowerOn()) { chassisControl = new ChassisControl(IpmiVersion.V20, cs, AuthenticationType.RMCPPlus, PowerCommand.PowerUp); } else { chassisControl = new ChassisControl(IpmiVersion.V20, cs, AuthenticationType.RMCPPlus, PowerCommand.PowerDown); } ChassisControlResponseData data = (ChassisControlResponseData) connector.sendMessage(handle, chassisControl); // Close the session connector.closeSession(handle); System.out.println("Session closed"); // Close connection manager and release the listener port. connector.tearDown(); System.out.println("Connection manager closed"); } }
gpl-3.0
kuiwang/my-dev
src/main/java/com/taobao/api/request/ScitemGetRequest.java
1987
package com.taobao.api.request; import java.util.Map; import com.taobao.api.ApiRuleException; import com.taobao.api.TaobaoRequest; import com.taobao.api.internal.util.RequestCheckUtils; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.response.ScitemGetResponse; /** * TOP API: taobao.scitem.get request * * @author auto create * @since 1.0, 2014-11-02 16:51:11 */ public class ScitemGetRequest implements TaobaoRequest<ScitemGetResponse> { private Map<String, String> headerMap = new TaobaoHashMap(); /** * 商品id */ private Long itemId; private Long timestamp; private TaobaoHashMap udfParams; // add user-defined text parameters @Override public void check() throws ApiRuleException { RequestCheckUtils.checkNotEmpty(itemId, "itemId"); } @Override public String getApiMethodName() { return "taobao.scitem.get"; } @Override public Map<String, String> getHeaderMap() { return headerMap; } public Long getItemId() { return this.itemId; } @Override public Class<ScitemGetResponse> getResponseClass() { return ScitemGetResponse.class; } @Override public Map<String, String> getTextParams() { TaobaoHashMap txtParams = new TaobaoHashMap(); txtParams.put("item_id", this.itemId); if (this.udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } @Override public Long getTimestamp() { return this.timestamp; } @Override public void putOtherTextParam(String key, String value) { if (this.udfParams == null) { this.udfParams = new TaobaoHashMap(); } this.udfParams.put(key, value); } public void setItemId(Long itemId) { this.itemId = itemId; } @Override public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } }
gpl-3.0
drewlu/ossql
src/s3ql/cli/adm.py
27015
''' adm.py - this file is part of S3QL (http://s3ql.googlecode.com) Copyright (C) 2008-2009 Nikolaus Rath <Nikolaus@rath.org> This program can be distributed under the terms of the GNU GPLv3. ''' from __future__ import division, print_function, absolute_import from datetime import datetime as Datetime from getpass import getpass from s3ql import CURRENT_FS_REV from s3ql.backends.common import (BetterBucket, get_bucket, NoSuchBucket, ChecksumError, AbstractBucket, NoSuchObject) from s3ql.backends.local import Bucket as LocalBucket, ObjectR, unescape, escape from s3ql.common import (QuietError, restore_metadata, cycle_metadata, dump_metadata, create_tables, setup_logging, get_bucket_cachedir) from s3ql.database import Connection from s3ql.fsck import Fsck from s3ql.parse_args import ArgumentParser import ConfigParser import cPickle as pickle import errno import hashlib import logging import os import re import shutil import stat import sys import tempfile import textwrap import time log = logging.getLogger("adm") def parse_args(args): '''Parse command line''' parser = ArgumentParser( description="Manage S3QL Buckets.", epilog=textwrap.dedent('''\ Hint: run `%(prog)s <action> --help` to get help on the additional arguments that the different actions take.''')) pparser = ArgumentParser(add_help=False, epilog=textwrap.dedent('''\ Hint: run `%(prog)s --help` to get help on other available actions and optional arguments that can be used with all actions.''')) pparser.add_storage_url() subparsers = parser.add_subparsers(metavar='<action>', dest='action', help='may be either of') subparsers.add_parser("passphrase", help="change bucket passphrase", parents=[pparser]) subparsers.add_parser("upgrade", help="upgrade file system to newest revision", parents=[pparser]) subparsers.add_parser("clear", help="delete all S3QL data from the bucket", parents=[pparser]) subparsers.add_parser("download-metadata", help="Interactively download metadata backups. " "Use only if you know what you are doing.", parents=[pparser]) parser.add_debug_modules() parser.add_quiet() parser.add_log() parser.add_authfile() parser.add_cachedir() parser.add_version() options = parser.parse_args(args) return options def main(args=None): '''Change or show S3QL file system parameters''' if args is None: args = sys.argv[1:] options = parse_args(args) setup_logging(options) # Check if fs is mounted on this computer # This is not foolproof but should prevent common mistakes match = options.storage_url + ' /' with open('/proc/mounts', 'r') as fh: for line in fh: if line.startswith(match): raise QuietError('Can not work on mounted file system.') if options.action == 'clear': return clear(get_bucket(options, plain=True), get_bucket_cachedir(options.storage_url, options.cachedir)) if options.action == 'upgrade': return upgrade(get_possibly_old_bucket(options)) bucket = get_bucket(options) if options.action == 'passphrase': return change_passphrase(bucket) if options.action == 'download-metadata': return download_metadata(bucket, options.storage_url) def download_metadata(bucket, storage_url): '''Download old metadata backups''' backups = sorted(bucket.list('s3ql_metadata_bak_')) if not backups: raise QuietError('No metadata backups found.') log.info('The following backups are available:') log.info('%3s %-23s %-15s', 'No', 'Name', 'Date') for (i, name) in enumerate(backups): params = bucket.lookup(name) if 'last-modified' in params: date = Datetime.fromtimestamp(params['last-modified']).strftime('%Y-%m-%d %H:%M:%S') else: # (metadata might from an older fs revision) date = '(unknown)' log.info('%3d %-23s %-15s', i, name, date) name = None while name is None: buf = raw_input('Enter no to download: ') try: name = backups[int(buf.strip())] except: log.warn('Invalid input') log.info('Downloading %s...', name) cachepath = get_bucket_cachedir(storage_url, '.') for i in ('.db', '.params'): if os.path.exists(cachepath + i): raise QuietError('%s already exists, aborting.' % cachepath+i) os.close(os.open(cachepath + '.db', os.O_RDWR | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR), 'w+b') param = bucket.lookup(name) try: db = Connection(cachepath + '.db') log.info('Reading metadata...') with bucket.open_read(name) as fh: restore_metadata(fh, db) restore_metadata(fh, db) except: # Don't keep file if it doesn't contain anything sensible os.unlink(cachepath + '.db') raise # Raise sequence number so that fsck.s3ql actually uses the # downloaded backup seq_nos = [ int(x[len('s3ql_seq_no_'):]) for x in bucket.list('s3ql_seq_no_') ] param['seq_no'] = max(seq_nos) + 1 pickle.dump(param, open(cachepath + '.params', 'wb'), 2) def change_passphrase(bucket): '''Change bucket passphrase''' if not isinstance(bucket, BetterBucket) and bucket.passphrase: raise QuietError('Bucket is not encrypted.') data_pw = bucket.passphrase if sys.stdin.isatty(): wrap_pw = getpass("Enter new encryption password: ") if not wrap_pw == getpass("Confirm new encryption password: "): raise QuietError("Passwords don't match") else: wrap_pw = sys.stdin.readline().rstrip() bucket.passphrase = wrap_pw bucket['s3ql_passphrase'] = data_pw bucket.passphrase = data_pw def clear(bucket, cachepath): print('I am about to delete the S3QL file system in %s.' % bucket, 'Please enter "yes" to continue.', '> ', sep='\n', end='') if sys.stdin.readline().strip().lower() != 'yes': raise QuietError() log.info('Deleting...') for suffix in ('.db', '.params'): name = cachepath + suffix if os.path.exists(name): os.unlink(name) name = cachepath + '-cache' if os.path.exists(name): shutil.rmtree(name) bucket.clear() print('File system deleted.') if not bucket.is_get_consistent(): log.info('Note: it may take a while for the removals to propagate through the backend.') def get_possibly_old_bucket(options, plain=False): '''Return factory producing bucket objects for given storage-url If *plain* is true, don't attempt to unlock and don't wrap into BetterBucket. ''' hit = re.match(r'^([a-zA-Z0-9]+)://(.+)$', options.storage_url) if not hit: raise QuietError('Unknown storage url: %s' % options.storage_url) backend_name = 's3ql.backends.%s' % hit.group(1) bucket_name = hit.group(2) try: __import__(backend_name) except ImportError: raise QuietError('No such backend: %s' % hit.group(1)) bucket_class = getattr(sys.modules[backend_name], 'Bucket') # Read authfile config = ConfigParser.SafeConfigParser() if os.path.isfile(options.authfile): mode = os.stat(options.authfile).st_mode if mode & (stat.S_IRGRP | stat.S_IROTH): raise QuietError("%s has insecure permissions, aborting." % options.authfile) config.read(options.authfile) backend_login = None backend_pw = None bucket_passphrase = None for section in config.sections(): def getopt(name): try: return config.get(section, name) except ConfigParser.NoOptionError: return None pattern = getopt('storage-url') if not pattern or not options.storage_url.startswith(pattern): continue backend_login = backend_login or getopt('backend-login') backend_pw = backend_pw or getopt('backend-password') bucket_passphrase = bucket_passphrase or getopt('bucket-passphrase') if not backend_login and bucket_class.needs_login: if sys.stdin.isatty(): backend_login = getpass("Enter backend login: ") else: backend_login = sys.stdin.readline().rstrip() if not backend_pw and bucket_class.needs_login: if sys.stdin.isatty(): backend_pw = getpass("Enter backend password: ") else: backend_pw = sys.stdin.readline().rstrip() bucket = bucket_class(bucket_name, backend_login, backend_pw) if bucket_class == LocalBucket and 's3ql_metadata.dat' in bucket: bucket_class = LegacyLocalBucket bucket = bucket_class(bucket_name, backend_login, backend_pw) if plain: return bucket try: encrypted = 's3ql_passphrase' in bucket except NoSuchBucket: raise QuietError('Bucket %d does not exist' % bucket_name) if encrypted and not bucket_passphrase: if sys.stdin.isatty(): bucket_passphrase = getpass("Enter bucket encryption passphrase: ") else: bucket_passphrase = sys.stdin.readline().rstrip() elif not encrypted: bucket_passphrase = None if hasattr(options, 'compress'): compress = options.compress else: compress = 'zlib' if not encrypted: return BetterBucket(None, compress, bucket_class(bucket_name, backend_login, backend_pw)) tmp_bucket = BetterBucket(bucket_passphrase, compress, bucket) try: data_pw = tmp_bucket['s3ql_passphrase'] except ChecksumError: raise QuietError('Wrong bucket passphrase') return BetterBucket(data_pw, compress, bucket_class(bucket_name, backend_login, backend_pw)) def upgrade(bucket): '''Upgrade file system to newest revision''' # Access to protected member #pylint: disable=W0212 log.info('Getting file system parameters..') seq_nos = [ int(x[len('s3ql_seq_no_'):]) for x in bucket.list('s3ql_seq_no_') ] seq_no = max(seq_nos) if not seq_nos: raise QuietError(textwrap.dedent(''' File system revision too old to upgrade! You need to use an older S3QL version to upgrade to a more recent revision before you can use this version to upgrade to the newest revision. ''')) param = bucket.lookup('s3ql_metadata') # Check for unclean shutdown if param['seq_no'] < seq_no: if bucket.is_get_consistent(): raise QuietError(textwrap.fill(textwrap.dedent('''\ It appears that the file system is still mounted somewhere else. If this is not the case, the file system may have not been unmounted cleanly and you should try to run fsck on the computer where the file system has been mounted most recently. '''))) else: raise QuietError(textwrap.fill(textwrap.dedent('''\ It appears that the file system is still mounted somewhere else. If this is not the case, the file system may have not been unmounted cleanly or the data from the most-recent mount may have not yet propagated through the backend. In the later case, waiting for a while should fix the problem, in the former case you should try to run fsck on the computer where the file system has been mounted most recently. '''))) # Check that the fs itself is clean if param['needs_fsck']: raise QuietError("File system damaged, run fsck!") # Check revision if param['revision'] < CURRENT_FS_REV - 1: raise QuietError(textwrap.dedent(''' File system revision too old to upgrade! You need to use an older S3QL version to upgrade to a more recent revision before you can use this version to upgrade to the newest revision. ''')) elif param['revision'] >= CURRENT_FS_REV: print('File system already at most-recent revision') return print(textwrap.dedent(''' I am about to update the file system to the newest revision. You will not be able to access the file system with any older version of S3QL after this operation. You should make very sure that this command is not interrupted and that no one else tries to mount, fsck or upgrade the file system at the same time. ''')) print('Please enter "yes" to continue.', '> ', sep='\n', end='') if sys.stdin.readline().strip().lower() != 'yes': raise QuietError() log.info('Upgrading from revision %d to %d...', CURRENT_FS_REV - 1, CURRENT_FS_REV) if 's3ql_hash_check_status' not in bucket: if (isinstance(bucket, LegacyLocalBucket) or (isinstance(bucket, BetterBucket) and isinstance(bucket.bucket, LegacyLocalBucket))): if isinstance(bucket, LegacyLocalBucket): bucketpath = bucket.name else: bucketpath = bucket.bucket.name for (path, _, filenames) in os.walk(bucketpath, topdown=True): for name in filenames: if not name.endswith('.meta'): continue basename = os.path.splitext(name)[0] if '=00' in basename: raise RuntimeError("No, seriously, you tried to break things, didn't you?") with open(os.path.join(path, name), 'r+b') as dst: dst.seek(0, os.SEEK_END) with open(os.path.join(path, basename + '.dat'), 'rb') as src: shutil.copyfileobj(src, dst) basename = basename.replace('#', '=23') os.rename(os.path.join(path, name), os.path.join(path, basename)) os.unlink(os.path.join(path, basename + '.dat')) if isinstance(bucket, LegacyLocalBucket): bucket = LocalBucket(bucket.name, None, None) else: bucket.bucket = LocalBucket(bucket.bucket.name, None, None) # Download metadata log.info("Downloading & uncompressing metadata...") dbfile = tempfile.NamedTemporaryFile() with tempfile.TemporaryFile() as tmp: with bucket.open_read("s3ql_metadata") as fh: shutil.copyfileobj(fh, tmp) db = Connection(dbfile.name, fast_mode=True) tmp.seek(0) restore_legacy_metadata(tmp, db) # Increase metadata sequence no param['seq_no'] += 1 bucket['s3ql_seq_no_%d' % param['seq_no']] = 'Empty' for i in seq_nos: if i < param['seq_no'] - 5: del bucket['s3ql_seq_no_%d' % i ] log.info("Uploading database..") cycle_metadata(bucket) param['last-modified'] = time.time() - time.timezone with bucket.open_write("s3ql_metadata", param) as fh: dump_metadata(fh, db) else: log.info("Downloading & uncompressing metadata...") dbfile = tempfile.NamedTemporaryFile() with tempfile.TemporaryFile() as tmp: with bucket.open_read("s3ql_metadata") as fh: shutil.copyfileobj(fh, tmp) db = Connection(dbfile.name, fast_mode=True) tmp.seek(0) restore_metadata(tmp, db) print(textwrap.dedent(''' The following process may take a long time, but can be interrupted with Ctrl-C and resumed from this point by calling `s3qladm upgrade` again. Please see Changes.txt for why this is necessary. ''')) if 's3ql_hash_check_status' not in bucket: log.info("Starting hash verification..") start_obj = 0 else: start_obj = int(bucket['s3ql_hash_check_status']) log.info("Resuming hash verification with object %d..", start_obj) try: total = db.get_val('SELECT COUNT(id) FROM objects') i = 0 for (obj_id, hash_) in db.query('SELECT obj_id, hash FROM blocks JOIN objects ' 'ON obj_id == objects.id WHERE obj_id > ? ' 'ORDER BY obj_id ASC', (start_obj,)): if i % 100 == 0: log.info(' ..checked %d/%d objects..', i, total) sha = hashlib.sha256() with bucket.open_read("s3ql_data_%d" % obj_id) as fh: while True: buf = fh.read(128*1024) if not buf: break sha.update(buf) if sha.digest() != hash_: log.warn('Object %d corrupted! Deleting..', obj_id) bucket.delete('s3ql_data_%d' % obj_id) i += 1 except KeyboardInterrupt: log.info("Storing verification status...") bucket['s3ql_hash_check_status'] = '%d' % obj_id raise QuietError('Aborting..') log.info('Running fsck...') fsck = Fsck(tempfile.mkdtemp(), bucket, param, db) fsck.check() if fsck.uncorrectable_errors: raise QuietError("Uncorrectable errors found, aborting.") param['revision'] = CURRENT_FS_REV param['seq_no'] += 1 bucket['s3ql_seq_no_%d' % param['seq_no']] = 'Empty' log.info("Uploading database..") cycle_metadata(bucket) param['last-modified'] = time.time() - time.timezone with bucket.open_write("s3ql_metadata", param) as fh: dump_metadata(fh, db) def restore_legacy_metadata(ifh, conn): unpickler = pickle.Unpickler(ifh) (data_start, to_dump, sizes, columns) = unpickler.load() ifh.seek(data_start) create_tables(conn) create_legacy_tables(conn) for (table, _) in to_dump: log.info('Loading %s', table) col_str = ', '.join(columns[table]) val_str = ', '.join('?' for _ in columns[table]) if table in ('inodes', 'blocks', 'objects', 'contents'): sql_str = 'INSERT INTO leg_%s (%s) VALUES(%s)' % (table, col_str, val_str) else: sql_str = 'INSERT INTO %s (%s) VALUES(%s)' % (table, col_str, val_str) for _ in xrange(sizes[table]): buf = unpickler.load() for row in buf: conn.execute(sql_str, row) # Create a block for each object conn.execute(''' INSERT INTO blocks (id, hash, refcount, obj_id, size) SELECT id, hash, refcount, id, size FROM leg_objects ''') conn.execute(''' INSERT INTO objects (id, refcount, compr_size) SELECT id, 1, compr_size FROM leg_objects ''') conn.execute('DROP TABLE leg_objects') # Create new inode_blocks table for inodes with multiple blocks conn.execute(''' CREATE TEMP TABLE multi_block_inodes AS SELECT inode FROM leg_blocks GROUP BY inode HAVING COUNT(inode) > 1 ''') conn.execute(''' INSERT INTO inode_blocks (inode, blockno, block_id) SELECT inode, blockno, obj_id FROM leg_blocks JOIN multi_block_inodes USING(inode) ''') # Create new inodes table for inodes with multiple blocks conn.execute(''' INSERT INTO inodes (id, uid, gid, mode, mtime, atime, ctime, refcount, size, rdev, locked, block_id) SELECT id, uid, gid, mode, mtime, atime, ctime, refcount, size, rdev, locked, NULL FROM leg_inodes JOIN multi_block_inodes ON inode == id ''') # Add inodes with just one block or no block conn.execute(''' INSERT INTO inodes (id, uid, gid, mode, mtime, atime, ctime, refcount, size, rdev, locked, block_id) SELECT id, uid, gid, mode, mtime, atime, ctime, refcount, size, rdev, locked, obj_id FROM leg_inodes LEFT JOIN leg_blocks ON leg_inodes.id == leg_blocks.inode GROUP BY leg_inodes.id HAVING COUNT(leg_inodes.id) <= 1 ''') conn.execute(''' INSERT INTO symlink_targets (inode, target) SELECT id, target FROM leg_inodes WHERE target IS NOT NULL ''') conn.execute('DROP TABLE leg_inodes') conn.execute('DROP TABLE leg_blocks') # Sort out names conn.execute(''' INSERT INTO names (name, refcount) SELECT name, COUNT(name) FROM leg_contents GROUP BY name ''') conn.execute(''' INSERT INTO contents (name_id, inode, parent_inode) SELECT names.id, inode, parent_inode FROM leg_contents JOIN names ON leg_contents.name == names.name ''') conn.execute('DROP TABLE leg_contents') conn.execute('ANALYZE') def create_legacy_tables(conn): conn.execute(""" CREATE TABLE leg_inodes ( id INTEGER PRIMARY KEY, uid INT NOT NULL, gid INT NOT NULL, mode INT NOT NULL, mtime REAL NOT NULL, atime REAL NOT NULL, ctime REAL NOT NULL, refcount INT NOT NULL, target BLOB(256) , size INT NOT NULL DEFAULT 0, rdev INT NOT NULL DEFAULT 0, locked BOOLEAN NOT NULL DEFAULT 0 ) """) conn.execute(""" CREATE TABLE leg_objects ( id INTEGER PRIMARY KEY AUTOINCREMENT, refcount INT NOT NULL, hash BLOB(16) UNIQUE, size INT NOT NULL, compr_size INT )""") conn.execute(""" CREATE TABLE leg_blocks ( inode INTEGER NOT NULL REFERENCES leg_inodes(id), blockno INT NOT NULL, obj_id INTEGER NOT NULL REFERENCES leg_objects(id), PRIMARY KEY (inode, blockno) )""") conn.execute(""" CREATE TABLE leg_contents ( rowid INTEGER PRIMARY KEY AUTOINCREMENT, name BLOB(256) NOT NULL, inode INT NOT NULL REFERENCES leg_inodes(id), parent_inode INT NOT NULL REFERENCES leg_inodes(id), UNIQUE (name, parent_inode) )""") def create_legacy_indices(conn): conn.execute('CREATE INDEX ix_leg_contents_parent_inode ON contents(parent_inode)') conn.execute('CREATE INDEX ix_leg_contents_inode ON contents(inode)') conn.execute('CREATE INDEX ix_leg_objects_hash ON objects(hash)') conn.execute('CREATE INDEX ix_leg_blocks_obj_id ON blocks(obj_id)') conn.execute('CREATE INDEX ix_leg_blocks_inode ON blocks(inode)') class LegacyLocalBucket(AbstractBucket): needs_login = False def __init__(self, name, backend_login, backend_pw): #IGNORE:W0613 super(LegacyLocalBucket, self).__init__() self.name = name if not os.path.exists(name): raise NoSuchBucket(name) def lookup(self, key): path = self._key_to_path(key) + '.meta' try: with open(path, 'rb') as src: return pickle.load(src) except IOError as exc: if exc.errno == errno.ENOENT: raise NoSuchObject(key) else: raise def open_read(self, key): path = self._key_to_path(key) try: fh = ObjectR(path + '.dat') except IOError as exc: if exc.errno == errno.ENOENT: raise NoSuchObject(key) else: raise fh.metadata = pickle.load(open(path + '.meta', 'rb')) return fh def open_write(self, key, metadata=None): raise RuntimeError('Not implemented') def clear(self): raise RuntimeError('Not implemented') def copy(self, src, dest): raise RuntimeError('Not implemented') def contains(self, key): path = self._key_to_path(key) try: os.lstat(path + '.meta') except OSError as exc: if exc.errno == errno.ENOENT: return False raise return True def delete(self, key, force=False): raise RuntimeError('Not implemented') def list(self, prefix=''): if prefix: base = os.path.dirname(self._key_to_path(prefix)) else: base = self.name for (path, dirnames, filenames) in os.walk(base, topdown=True): # Do not look in wrong directories if prefix: rpath = path[len(self.name):] # path relative to base prefix_l = ''.join(rpath.split('/')) dirs_to_walk = list() for name in dirnames: prefix_ll = unescape(prefix_l + name) if prefix_ll.startswith(prefix[:len(prefix_ll)]): dirs_to_walk.append(name) dirnames[:] = dirs_to_walk for name in filenames: key = unescape(name) if not prefix or key.startswith(prefix): if key.endswith('.meta'): yield key[:-5] def _key_to_path(self, key): key = escape(key) if not key.startswith('s3ql_data_'): return os.path.join(self.name, key) no = key[10:] path = [ self.name, 's3ql_data_'] for i in range(0, len(no), 3): path.append(no[:i]) path.append(key) return os.path.join(*path) def is_get_consistent(self): return True def is_list_create_consistent(self): return True if __name__ == '__main__': main(sys.argv[1:])
gpl-3.0