repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
rogerdv/keyw
|
Assets/Scripts/RPG/ItemWeapon.cs
|
2038
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class ItemWeapon : BaseItem {
public override void Use (GameObject owner, GameObject target) {
//TODO: get weapon damages, etc
//get item parent skill level
var OwnSc = owner.GetComponent<BaseCharacter> ();
var TargetSc = target.GetComponent<BaseCharacter> ();
var ps = OwnSc.GetSkill(ParentSkill);
/*Debug.Log("Parent skill is "+ps.Name);
Debug.Log(ps.baseValue);*/
//calculate hit roll: determines if target is actually hit or evades attack
int AttackRoll = ps + OwnSc.GetAttribute( (int)Attributes.Str) + OwnSc.GetAttribute((int)Attributes.Dext);
int DodgeRoll = TargetSc.GetSkill("dodge") + TargetSc.GetAttribute((int)Attributes.Dext);
int roll = Random.Range (0, AttackRoll + DodgeRoll + 1);
if (roll > AttackRoll) {
//Debug.Log("Attack missed!!");
GameObject.Find("MessageBox").GetComponent<MsgList>().SetText(OwnSc.Name+" hits the air causing a lot of damege to nobody");
}
///weapon does damage: get all damage properties
foreach (Property p in props) {
if (p.type=="damage") {
Debug.Log("Dmg type: "+p.name);
Debug.Log("Dmg value: "+p.value);
float dmg = p.value+OwnSc.GetAttribute((int)Attributes.Str)*ps;
Debug.Log("Effective damage is "+dmg);
target.GetComponent<BaseCharacter> ().HitPoints [0]-= dmg;
var bar = GameObject.Find("blood-bar").GetComponent<Image>();
float percent = TargetSc.HitPoints [0]/TargetSc.HitPoints [1];
bar.transform.localScale = new Vector3(percent, 1.0f,1.0f);
//Debug.Log("Dmg value: "+p.value);
GameObject.Find("MessageBox").GetComponent<MsgList>().SetText(OwnSc.Name+" hits "+TargetSc.Name+" inflicting "+dmg.ToString() +" damage");
}
}
}//Use
public override void Equip(GameObject owner){
var OwnSc = owner.GetComponent<BaseCharacter> ();
foreach (var m in mods) {
if (m.type == "strength") {
int currentMod = OwnSc.GetBaseAttribute((int)Attributes.Str).modifier;
}
}
}
}
|
gpl-2.0
|
DencoDance/wpdndz
|
wp-content/themes/news/framework/inc/post-format-mini/format-video.php
|
827
|
<?php $postvideo_vimeo = get_post_meta(get_the_ID(),'mypassion_postvideo_v', true); global $admin_data; ?>
<?php $postvideo_youtube = get_post_meta(get_the_ID(),'mypassion_postvideo_y', true);?>
<?php if($postvideo_vimeo){ ?>
<div class="post-type-wrapper">
<div class="video2">
<iframe src="http://player.vimeo.com/video/<?php echo esc_html($postvideo_vimeo); ?>?title=0&byline=0&portrait=0&color=ffffff" width="100%" height="100%" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
</div>
</div>
<?php }else{ ?>
<div class="post-type-wrapper">
<div class="video2">
<iframe src='http://www.youtube.com/embed/<?php echo esc_html($postvideo_youtube); ?>?HD=1;rel=0;showinfo=0' width='100%' height='100%' class='iframe'></iframe>
</div>
</div>
<?php } ?>
|
gpl-2.0
|
bonfil1/masmuscular
|
wp-content/themes/sportexx/templates/sections/sportexx_mini_cart.php
|
4315
|
<?php if( apply_filters( 'sportexx_is_catalog_mode_disabled', TRUE ) ) : ?>
<div id="mini-cart">
<div class="dropdown dropdown-cart">
<?php
$data_hover_attr = '';
if( apply_filters( 'sportexx_top_cart_dropdown_trigger', 'click' ) === 'hover' ) {
$data_hover_attr = 'data-hover="dropdown"';
}
?>
<a href="#dropdown-menu-cart" class="dropdown-trigger-cart dropdown-toggle" data-toggle="dropdown" <?php echo $data_hover_attr; ?>><?php echo apply_filters( 'sportexx_top_cart_text', __( 'Cart/', 'sportexx' ) ); ?><span class="price"><?php echo WC()->cart->get_cart_subtotal(); ?></span></a>
<ul class="dropdown-menu dropdown-menu-cart <?php echo esc_attr( apply_filters( 'sportexx_top_cart_dropdown_animation', 'animated fadeInUp' ) ); ?>">
<li>
<?php if ( sizeof( WC()->cart->get_cart() ) > 0 ) : ?>
<div class="cart-item product-summary">
<p class="product-report"><?php echo sportexx_mini_cart_report(); ?></p>
<div class="cart-products">
<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_widget_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
$product_name = apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key );
$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );
$product_price = apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );
?>
<div class="basket-item product-item inner-bottom-xs">
<div class="row">
<div class="col-xs-5">
<div class="image">
<?php if ( ! $_product->is_visible() ) {
echo str_replace( array( 'http:', 'https:' ), '', $thumbnail );
} else {
echo '<a href="' . esc_url( $_product->get_permalink( $cart_item ) ) . '">' . str_replace( array( 'http:', 'https:' ), '', $thumbnail ) . '</a>';
} ?>
</div>
</div>
<div class="col-xs-7">
<h5 class="product-title">
<?php if ( ! $_product->is_visible() ) {
echo $product_name;
} else {
echo '<a href="' . esc_url( $_product->get_permalink( $cart_item ) ) . '">' . $product_name . '</a>';
} ?>
</h5>
<div class="price"><span class="amount"><?php echo $product_price; ?></span></div>
<?php echo apply_filters( 'woocommerce_widget_cart_item_quantity', '<div class="product-count">' . sprintf( __( 'QTY : %s', 'sportexx' ), $cart_item['quantity'] ) . '</div>', $cart_item, $cart_item_key ); ?>
<?php echo WC()->cart->get_item_data( $cart_item ); ?>
</div>
</div>
<?php echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf( '<a href="%s" class="remove" title="%s">×</a>', esc_url( WC()->cart->get_remove_url( $cart_item_key ) ), __( 'Remove this item', 'sportexx' ) ), $cart_item_key ); ?>
</div>
<?php
}
}
?>
<div class="cart-actions clearfix">
<a href="<?php echo WC()->cart->get_cart_url(); ?>" class="btn btn-default col-xs-6 btn-cart-view pull-left flip"><?php echo __( 'View Cart', 'sportexx' ); ?></a>
<a href="<?php echo WC()->cart->get_checkout_url(); ?>" class="btn btn-primary col-xs-6 btn-cart-checkout pull-right flip"><?php echo __( 'Checkout', 'sportexx' ); ?></a>
</div>
</div><!-- /.cart-products -->
</div>
<div class="clearfix"></div>
<?php else : ?>
<div class="alert alert-warning"><?php _e( 'No products in the cart.', 'sportexx' ); ?></div>
<?php endif; ?>
</li>
</ul><!-- /.dropdown-menu-cart -->
</div>
</div><!-- /#-mini-cart -->
<?php else : ?>
<div id="mini-cart">
<div class="dropdown dropdown-cart">
<span class="dropdown-trigger-cart dropdown-toggle"> </a>
</div>
</div>
<?php endif; ?>
|
gpl-2.0
|
cdymnikov/terminator-sc
|
Terminator/Device/Installer.cs
|
439
|
using Castle.Core;
using Castle.Windsor;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
namespace Terminator.Device
{
public class Installer : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Install(new Input.Installer());
container.Install(new Output.Installer());
}
}
}
|
gpl-2.0
|
pwujek/boats
|
tests/geomock.js
|
2745
|
// Generated by CoffeeScript 1.6.3
/*
(c) 2011 Jan Monschke
v1.0.1
GeoMock is licensed under the MIT license.
@see https://github.com/janmonschke/GeoMock
*/
(function() {
(function() {
if (typeof navigator === "undefined" || navigator === null) {
window.navigator = {};
}
if (navigator.geolocation == null) {
window.navigator.geolocation = {};
}
navigator.geolocation.delay = 1000;
navigator.geolocation.shouldFail = false;
navigator.geolocation.failsAt = -1;
navigator.geolocation.errorMessage = "There was an error retrieving the position!";
navigator.geolocation.currentTimeout = -1;
navigator.geolocation.lastPosReturned = 0;
navigator.geolocation._sanitizeLastReturned = function() {
if (this.lastPosReturned > this.waypoints.length - 1) {
return this.lastPosReturned = 0;
}
};
navigator.geolocation._geoCall = function(method, success, error) {
var _this = this;
if (this.shouldFail && (error != null)) {
return this.currentTimeout = window[method].call(null, function() {
return error(_this.errorMessage);
}, this.delay);
} else {
if (success != null) {
return this.currentTimeout = window[method].call(null, function() {
success(_this.waypoints[_this.lastPosReturned++]);
return _this._sanitizeLastReturned();
}, this.delay);
}
}
};
navigator.geolocation.getCurrentPosition = function(success, error) {
return this._geoCall("setTimeout", success, error);
};
navigator.geolocation.watchPosition = function(success, error) {
this._geoCall("setInterval", success, error);
return this.currentTimeout;
};
navigator.geolocation.clearWatch = function(id) {
return clearInterval(id);
};
return navigator.geolocation.waypoints = [
{
coords: {
latitude: 52.5168,
longitude: 13.3889,
accuracy: 1500
}
}, {
coords: {
latitude: 52.5162,
longitude: 13.3890,
accuracy: 1334
}
}, {
coords: {
latitude: 52.5154,
longitude: 13.3890,
accuracy: 631
}
}, {
coords: {
latitude: 52.5150,
longitude: 13.3890,
accuracy: 361
}
}, {
coords: {
latitude: 52.5144,
longitude: 13.3890,
accuracy: 150
}
}, {
coords: {
latitude: 52.5138,
longitude: 13.3890,
accuracy: 65
}
}, {
coords: {
latitude: 52.5138,
longitude: 13.3895,
accuracy: 65
}
}, {
coords: {
latitude: 52.5139,
longitude: 13.3899,
accuracy: 65
}
}, {
coords: {
latitude: 52.5140,
longitude: 13.3906,
accuracy: 65
}
}, {
coords: {
latitude: 52.5140,
longitude: 13.3910,
accuracy: 65
}
}
];
})();
}).call(this);
|
gpl-2.0
|
Nirage/angular
|
sideProj/crm/js/main.js
|
1495
|
$(function(){
var btn = $(".menu li"),
url = "js/jquery.carouFredSel-6.2.1-packed.js",
url2 = "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js";
// INITIAL CAROUSEL LOAD
$('#foo0').carouFredSel({
auto: { duration: 600, delay: 300 },
scroll: { fx: "uncover-fade", easing: "quadratic" },
pagination: { container: ".menu", anchorBuilder: false },
queue: false,
mousewheel: true,
swipe: { onMouse: true },
});
btn.on("click",function(){
$("#quest,.csr,.circle").hide();
});
// SECONDARY CIRCLE PAGES - Hide/Show on click btn
function menuBtn(){
$.getScript(url, function(){
for(i=0;i< btn.length;i++){
(function(j){
//console.log(j);
btn.eq(j).on('click',function(){
// Add/Remove "selected" class
$(this).addClass('selected').siblings('li').removeClass('selected');
// fadeIn new circle
$('.circle'+(j+1)).stop().fadeIn('fast');
// Secondary carousels initialing
$('#foo'+(j+1)).carouFredSel({
auto: {duration: 600},
pagination: ".pager",
queue: false,
mousewheel: true,
swipe: { onMouse: true }
});
return false;
});
})(i);
}
});
}menuBtn();
// ACCORDION
$.getScript( url2, function() {
$( ".accordion" ).accordion();
});
});
|
gpl-2.0
|
michaelcabus/MobileMidwife-Master
|
app/src/main/java/android/bignerdranch/com/mobilemidwife/LoginActivty.java
|
1976
|
package android.bignerdranch.com.mobilemidwife;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class LoginActivty extends ActionBarActivity {
protected TextView mRegisterTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activty);
mRegisterTextView = (TextView)findViewById(R.id.register);
mRegisterTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivty.this, LoginActivty.class);
startActivity(intent);
}
});
ActionBar actionBar = getActionBar();
actionBar.hide();
TextView textView = (TextView)findViewById(R.id.title);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/desyrel.ttf");
textView.setTypeface(typeFace);
}
@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_login_activty, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
gpl-2.0
|
epatel/qt-mac-free-3.3.8
|
examples/sql/overview/insert2/main.cpp
|
859
|
/****************************************************************************
** $Id: qt/main.cpp 3.3.8 edited Jan 11 14:37 $
**
** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include <qapplication.h>
#include <qsqldatabase.h>
#include <qsqlcursor.h>
#include "../connection.h"
int main( int argc, char *argv[] )
{
QApplication app( argc, argv, FALSE );
if ( createConnections() ) {
QSqlCursor cur( "prices" );
QSqlRecord *buffer = cur.primeInsert();
buffer->setValue( "id", 53981 );
buffer->setValue( "name", "Thingy" );
buffer->setValue( "price", 105.75 );
cur.insert();
}
return 0;
}
|
gpl-2.0
|
intelie/esper
|
esper/src/main/java/com/espertech/esper/view/StoppableView.java
|
830
|
/*
* *************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.view;
public interface StoppableView {
public void stop();
}
|
gpl-2.0
|
killerwife/mangos-classic
|
src/game/AI/ScriptDevAI/scripts/eastern_kingdoms/naxxramas/boss_grobbulus.cpp
|
6877
|
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* 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
*/
/* ScriptData
SDName: Boss_Grobbulus
SD%Complete: 80
SDComment: Timer need more care; Spells of Adds (Posion Cloud) need Mangos Fixes, and further handling
SDCategory: Naxxramas
EndScriptData */
/*Poison Cloud 26590
Slime Spray 28157
Fallout slime 28218
Mutating Injection 28169
Enrages 26527*/
#include "AI/ScriptDevAI/include/precompiled.h"
#include "naxxramas.h"
enum
{
EMOTE_SPRAY_SLIME = -1533021,
EMOTE_INJECTION = -1533158,
SPELL_SLIME_STREAM = 28137,
SPELL_MUTATING_INJECTION = 28169,
SPELL_POISON_CLOUD = 28240,
SPELL_SLIME_SPRAY = 28157,
SPELL_BERSERK = 26662,
NPC_FALLOUT_SLIME = 16290
};
struct boss_grobbulusAI : public ScriptedAI
{
boss_grobbulusAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (instance_naxxramas*)pCreature->GetInstanceData();
Reset();
}
instance_naxxramas* m_pInstance;
uint32 m_uiInjectionTimer;
uint32 m_uiPoisonCloudTimer;
uint32 m_uiSlimeSprayTimer;
uint32 m_uiBerserkTimer;
uint32 m_uiSlimeStreamTimer;
void Reset() override
{
m_uiInjectionTimer = 12 * IN_MILLISECONDS;
m_uiPoisonCloudTimer = urand(20 * IN_MILLISECONDS, 25 * IN_MILLISECONDS);
m_uiSlimeSprayTimer = urand(20 * IN_MILLISECONDS, 30 * IN_MILLISECONDS);
m_uiBerserkTimer = 12 * MINUTE * IN_MILLISECONDS;
m_uiSlimeStreamTimer = 5 * IN_MILLISECONDS; // The first few secs it is ok to be out of range
}
void Aggro(Unit* /*pWho*/) override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_GROBBULUS, IN_PROGRESS);
}
void JustDied(Unit* /*pKiller*/) override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_GROBBULUS, DONE);
}
void JustReachedHome() override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_GROBBULUS, FAIL);
}
// This custom selecting function, because we only want to select players without mutagen aura
bool DoCastMutagenInjection()
{
if (m_creature->IsNonMeleeSpellCasted(true))
return false;
std::vector<Unit*> suitableTargets;
ThreatList const& threatList = m_creature->getThreatManager().getThreatList();
for (ThreatList::const_iterator itr = threatList.begin(); itr != threatList.end(); ++itr)
{
if (Unit* pTarget = m_creature->GetMap()->GetUnit((*itr)->getUnitGuid()))
{
if (pTarget->GetTypeId() == TYPEID_PLAYER && !pTarget->HasAura(SPELL_MUTATING_INJECTION))
suitableTargets.push_back(pTarget);
}
}
if (suitableTargets.empty())
return false;
Unit* pTarget = suitableTargets[urand(0, suitableTargets.size() - 1)];
if (DoCastSpellIfCan(pTarget, SPELL_MUTATING_INJECTION) == CAST_OK)
{
DoScriptText(EMOTE_INJECTION, m_creature, pTarget);
return true;
}
else
return false;
}
void SpellHitTarget(Unit* pTarget, const SpellEntry* pSpell) override
{
if ((pSpell->Id == SPELL_SLIME_SPRAY) && pTarget->GetTypeId() == TYPEID_PLAYER)
m_creature->SummonCreature(NPC_FALLOUT_SLIME, pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_OOC_DESPAWN, 10 * IN_MILLISECONDS);
}
void UpdateAI(const uint32 uiDiff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
// Slime Stream
if (!m_uiSlimeStreamTimer)
{
if (!m_creature->CanReachWithMeleeAttack(m_creature->getVictim()))
{
if (DoCastSpellIfCan(m_creature, SPELL_SLIME_STREAM) == CAST_OK)
// Give some time, to re-reach grobbulus
m_uiSlimeStreamTimer = 3 * IN_MILLISECONDS;
}
}
else
{
if (m_uiSlimeStreamTimer < uiDiff)
m_uiSlimeStreamTimer = 0;
else
m_uiSlimeStreamTimer -= uiDiff;
}
// Berserk
if (m_uiBerserkTimer)
{
if (m_uiBerserkTimer <= uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_BERSERK) == CAST_OK)
m_uiBerserkTimer = 0;
}
else
m_uiBerserkTimer -= uiDiff;
}
// SlimeSpray
if (m_uiSlimeSprayTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_SLIME_SPRAY) == CAST_OK)
{
m_uiSlimeSprayTimer = urand(30 * IN_MILLISECONDS, 60 * IN_MILLISECONDS);
DoScriptText(EMOTE_SPRAY_SLIME, m_creature);
}
}
else
m_uiSlimeSprayTimer -= uiDiff;
// Mutagen Injection
if (m_uiInjectionTimer < uiDiff)
{
if (DoCastMutagenInjection())
{
// Mutagen Injection should be used more often when below 30%
if (m_creature->GetHealthPercent() > 30.0f)
m_uiInjectionTimer = urand(7000, 13000);
else
m_uiInjectionTimer = urand(3000, 7000);
}
}
else
m_uiInjectionTimer -= uiDiff;
// Poison Cloud
if (m_uiPoisonCloudTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_POISON_CLOUD) == CAST_OK)
m_uiPoisonCloudTimer = 15 * IN_MILLISECONDS;
}
else
m_uiPoisonCloudTimer -= uiDiff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_grobbulus(Creature* pCreature)
{
return new boss_grobbulusAI(pCreature);
}
void AddSC_boss_grobbulus()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "boss_grobbulus";
pNewScript->GetAI = &GetAI_boss_grobbulus;
pNewScript->RegisterSelf();
}
|
gpl-2.0
|
dreadwarrior/vantomas
|
web/typo3conf/ext/vantomas/Classes/Page/PageRenderer/HookInterface.php
|
1046
|
<?php
namespace DreadLabs\Vantomas\Page\PageRenderer;
/*
* 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!
*/
use DreadLabs\Vantomas\Page\PageRendererAdapter;
/**
* HookInterface
*
* API for PageRenderer hook implementations to allow modifications
* of the PageRenderer.
*
* @see \DreadLabs\Vantomas\Page\PageRenderer\HookContext\BackendInterface
* @see \DreadLabs\Vantomas\Page\PageRenderer\HookContext\FrontendInterface
*
* @author Thomas Juhnke <typo3@van-tomas.de>
*/
interface HookInterface
{
/**
* Modifies the PageRenderer
*
* @param PageRendererAdapter $pageRenderer
*/
public function modify(PageRendererAdapter $pageRenderer);
}
|
gpl-2.0
|
formfoxk/DesignPattern
|
4.CreationalPattern - FactoryMethod/C++/pizza/pizza/PizzaTestDrive.cpp
|
1080
|
#include "PizzaStore.h"
#include "NYPizzaStore.h"
#include "ChicagoPizzaStore.h"
int main(){
PizzaStore *nyStore = new NYPizzaStore();
PizzaStore *chicagoStore = new ChicagoPizzaStore();
Pizza *pizza = nyStore->orderPizza("cheese");
cout << "Ethan ordered a " << pizza->getName() << "\n" << endl;
pizza = chicagoStore->orderPizza("cheese");
cout << "Joel ordered a " << pizza->getName() << "\n" << endl;
pizza = nyStore->orderPizza("clam");
cout << "Ethan ordered a " << pizza->getName() + "\n" << endl;
pizza = chicagoStore->orderPizza("clam");
cout << "Joel ordered a " << pizza->getName() << "\n" << endl;
pizza = nyStore->orderPizza("pepperoni");
cout << "Ethan ordered a " << pizza->getName() << "\n" << endl;
pizza = chicagoStore->orderPizza("pepperoni");
cout << "Joel ordered a " << pizza->getName() << "\n" << endl;
pizza = nyStore->orderPizza("veggie");
cout << "Ethan ordered a " << pizza->getName() << "\n" << endl;
pizza = chicagoStore->orderPizza("veggie");
cout << "Joel ordered a " << pizza->getName() << "\n" << endl;
return 0;
}
|
gpl-2.0
|
uhonliu/Tolowan
|
Cdn/themes/dacms/js/main.js
|
8256
|
(function ($) {
window.jsui = {
www: 'http://cdn.demo.com',
uri: 'http://cdn.demo.com/themes/dacms',
ver: '1.6',
roll: ["1"],
url_rp: 'http://demo.com/password.html'
};
$('body').on('click', '[ajax-model]', function () {
var ajaxModel = $(this).attr('ajax-model');
var loadedAjaxModel = $('#myModal').attr('loaded-url');
if (ajaxModel == loadedAjaxModel) {
$('#myModal').modal('show');
} else {
$.get(ajaxModel, function (data) {
$('#myModal').html(data).attr('loaded-url', ajaxModel);
$('#myModal').modal('show');
});
}
return false;
});
$('[ajax-notice]').click(function () {
var ajaxModel = $(this).attr('ajax-notice');
$.ajax({
type: "get",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: ajaxModel,
success: function (data) {
if (typeof(data.notice) == "undefined" || typeof(data.state) == "undefined") {
$('#notice').html('请求失败,请检查网络');
} else {
$('#notice').html(data.notice);
}
$('#notice').fadeIn(500);
setTimeout(function () {
$('#notice').fadeOut(500);
}, 2500);
},
timeout: 1000,
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#notice').html('请求失败,请检查网络,或联系管理员');
$('#notice').fadeIn(500);
setTimeout(function () {
$('#notice').fadeOut(500);
}, 2500);
}
});
return false;
});
$('body').on('submit', '.ajax-submit form', function () {
$(this).next('.overlay').css('display', 'block');
me = $(this);
$(this).ajaxSubmit({
success: function (data) {
me.next('.overlay').css('display', 'none');
self.location.reload();
}
});
return false;
});
jsui.bd = $('body');
if ($('.widget-nav').length) {
$('.widget-nav li').each(function (e) {
$(this).hover(function () {
$(this).addClass('active').siblings().removeClass('active')
$('.widget-navcontent .item:eq(' + e + ')').addClass('active').siblings().removeClass('active')
});
});
}
if ($('.thumb:first').data('src') || $('.widget_ui_posts .thumb:first').data('src') || $('.wp-smiley:first').data('src') || $('.avatar:first').data('src')) {
$('.avatar').lazyload({
data_attribute: 'src',
placeholder: jsui.uri + '/images/avatar-default.png',
threshold: 400
});
$('.widget .avatar').lazyload({
data_attribute: 'src',
placeholder: jsui.uri + '/images/avatar-default.png',
threshold: 400
});
$('.thumb').lazyload({data_attribute: 'src', placeholder: jsui.uri + '/images/thumbnail.png', threshold: 400});
$('.widget_ui_posts .thumb').lazyload({
data_attribute: 'src',
placeholder: jsui.uri + '/images/thumbnail.png',
threshold: 400
});
$('.small-icon').lazyload({data_attribute: 'src', threshold: 400});
}
jsui.bd.append('<div class="m-mask"></div><div class="rollbar"><ul>' + '<li><a href="javascript:(scrollTo());"><i class="fa fa-angle-up"></i></a><h6>去顶部<i></i></h6></li></ul></div>');
var _wid = $(window).width();
var scroller = $('.rollbar');
var _fix = (jsui.bd.hasClass('nav_fixed') && !jsui.bd.hasClass('page-template-navs')) ? true : false;
$(window).scroll(function () {
var h = document.documentElement.scrollTop + document.body.scrollTop;
h > 200 ? scroller.fadeIn() : scroller.fadeOut();
});
$('.user-welcome').tooltip({container: 'body', placement: 'bottom'});
var _sidebar = $('.sidebar');
if (_wid > 1024 && _sidebar.length) {
var h1 = 0, h2 = 30;
var rollFirst = _sidebar.find('.widget:eq(' + (jsui.roll[0] - 1) + ')');
var sheight = rollFirst.height();
rollFirst.on('affix-top.bs.affix', function () {
rollFirst.css({top: 0});
sheight = rollFirst.height();
for (var i = 1; i < jsui.roll.length; i++) {
var item = jsui.roll[i] - 1;
var current = _sidebar.find('.widget:eq(' + item + ')');
current.removeClass('affix').css({top: 0})
}
});
rollFirst.on('affix.bs.affix', function () {
rollFirst.css({top: h1});
for (var i = 1; i < jsui.roll.length; i++) {
var item = jsui.roll[i] - 1;
var current = _sidebar.find('.widget:eq(' + item + ')');
current.addClass('affix').css({top: sheight + h2});
sheight += current.height() + 15
}
});
rollFirst.affix({offset: {top: _sidebar.height(), bottom: $('.footer').outerHeight()}});
}
$("#site-nav-ul").swipe({fingers: 2});
$('.book-toc-overbox').each(function (i) {
var bookActiveNode = $(this).attr('active-node');
$(this).find('#' + bookActiveNode).addClass('active');
});
jsui.bd.append($('.site-navbar').clone().attr('class', 'm-navbar'));
$('header .container').append($('.site-search-form').clone().attr('id', 'small-search-form'));
$('.m-icon .fa-bars').on('click', function () {
jsui.bd.addClass('m-nav-show');
$('.m-navbar').animate({left: 0}, 100);
$('.m-mask').fadeIn();
jsui.bd.removeClass('search-on');
});
$('.m-icon').on('click', '.fa-search', function () {
$('#small-search-form').fadeToggle();
$(this).removeClass('fa-search').addClass('fa-close');
});
$('.m-icon').on('click', '.fa-close', function () {
$('#small-search-form').fadeToggle();
$(this).removeClass('fa-close').addClass('fa-search');
});
$('.m-mask').on('click', function () {
$('.m-navbar').animate({left: "-246px",}, 100);
$(this).fadeOut();
jsui.bd.removeClass('m-nav-show');
});
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
function scrollTo(name, add, speed) {
if (!speed) speed = 300;
if (!name) {
$('html,body').animate({scrollTop: 0}, speed);
} else {
if ($(name).length > 0) {
$('html,body').animate({scrollTop: $(name).offset().top + (add || 0)}, speed);
}
}
}
function is_name(str) {
return /.{2,12}$/.test(str);
}
function is_url(str) {
return /^((http|https)\:\/\/)([a-z0-9-]{1,}.)?[a-z0-9-]{2,}.([a-z0-9-]{1,}.)?[a-z0-9]{2,}$/.test(str);
}
function is_qq(str) {
return /^[1-9]\d{4,13}$/.test(str);
}
function is_mail(str) {
return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(str);
}
function strToDate(str, fmt) {
if (!fmt) fmt = 'yyyy-MM-dd hh:mm:ss';
str = new Date(str * 1000);
var o = {
"M+": str.getMonth() + 1,
"d+": str.getDate(),
"h+": str.getHours(),
"m+": str.getMinutes(),
"s+": str.getSeconds(),
"q+": Math.floor((str.getMonth() + 3) / 3), //季度
"S": str.getMilliseconds()
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (str.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
|
gpl-2.0
|
simibimi/websocket-pong
|
source/web/sources/public_html/gamelogic/Ball.js
|
2156
|
function Ball(radius, x, y, vx, vy, canvasWidth, canvasHeight) {
this.radius = radius;
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.canvasWidth = canvasWidth;
this.canvasHeight = canvasHeight;
}
Ball.prototype.getX = function () {
return this.x;
};
Ball.prototype.setX = function (x) {
return this.x = x;
};
Ball.prototype.setY = function (y) {
return this.y = y;
};
Ball.prototype.getY = function () {
return this.y;
}
Ball.prototype.getVx = function () {
return this.vx;
}
Ball.prototype.getVy = function () {
return this.vy;
}
Ball.prototype.setVx = function (vx) {
this.vx = vx;
}
Ball.prototype.setVy = function (vy) {
this.vy = vy;
}
Ball.prototype.getCanvasWidth = function () {
return this.canvasWidth;
}
Ball.prototype.getCanvasHeight = function () {
return this.canvasHeight;
}
Ball.prototype.isMovingRight = function () {
return this.vx > 0;
}
Ball.prototype.isMovingDown = function () {
return this.vy > 0;
};
Ball.prototype.collidesWith = function (player) {
if (((this.y - this.radius) <= (player.getY() + player.getHeight())) && ((this.y + this.radius) >= player.getY())) {
if (player.getX() == 0) {
return (this.x - this.radius) <= 0;
} else {
return (this.x + this.radius) >= this.canvasWidth;
}
} else {
return false;
}
}
Ball.prototype.alternateXSpeed = function () {
this.vx = -this.vx;
}
Ball.prototype.alternateYSpeed = function () {
this.vy = -this.vy;
}
Ball.prototype.isTouchingTop = function () {
return ((this.y - this.radius) <= 0);
}
Ball.prototype.isTouchingBottom = function () {
return ((this.y + this.radius) >= this.canvasHeight);
}
Ball.prototype.calculateYSpeed = function (player) {
if (this.y <= (player.getY() + (player.getHeight() * 0.25))) {
this.vy -= 2;
} else if (this.y <= (player.getY() + (player.getHeight() * 0.5))) {
this.vy -= 1;
} else if (this.y <= (player.getY() + (player.getHeight() * 0.75))) {
this.vy += 1;
} else {
this.vy += 2;
}
}
module.exports = Ball;
|
gpl-2.0
|
langcog/wordbank
|
common/migrations/0014_source_license.py
|
482
|
# -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('common', '0013_auto_20160920_1514'),
]
operations = [
migrations.AddField(
model_name='source',
name='license',
field=models.CharField(default='CC-BY', max_length=15, choices=[(b'CC-BY', b'CC BY 4.0'), (b'CC-BY-NC', b'CC BY-NC 4.0')]),
preserve_default=False,
),
]
|
gpl-2.0
|
tinkajts/nobil.no_joomla
|
administrator/components/com_discussions/controllers/dashboard.php
|
585
|
<?php
/**
* @package Codingfish Discussions
* @subpackage com_discussions
* @copyright Copyright (C) 2010-2012 Codingfish (Achim Fischer). All rights reserved.
* @license GNU General Public License <http://www.gnu.org/copyleft/gpl.html>
* @link http://www.codingfish.com
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class DiscussionsControllerDashboard extends JController {
function display() {
JRequest::setVar('view', 'dashboard');
parent::display();
}
}
|
gpl-2.0
|
pbenner/tfbayes
|
tfbayes/phylotree/__init__.py
|
746
|
# Copyright (C) 2012 Philipp Benner
#
# 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
# 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
from interface import *
|
gpl-2.0
|
kunj1988/Magento2
|
app/code/Magento/Store/Api/WebsiteRepositoryInterface.php
|
1141
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Store\Api;
use Magento\Framework\Exception\NoSuchEntityException;
/**
* Website repository interface
*
* @api
* @since 100.0.2
*/
interface WebsiteRepositoryInterface
{
/**
* Retrieve website by code
*
* @param string $code
* @return \Magento\Store\Api\Data\WebsiteInterface
* @throws NoSuchEntityException
*/
public function get($code);
/**
* Retrieve website by id
*
* @param int $id
* @return \Magento\Store\Api\Data\WebsiteInterface
* @throws NoSuchEntityException
*/
public function getById($id);
/**
* Retrieve list of all websites
*
* @return \Magento\Store\Api\Data\WebsiteInterface[]
*/
public function getList();
/**
* Retrieve default website
*
* @return \Magento\Store\Api\Data\WebsiteInterface
* @throws \DomainException
*/
public function getDefault();
/**
* Clear cached entities
*
* @return void
*/
public function clean();
}
|
gpl-2.0
|
GravityPDF/gravity-forms-pdf-extended
|
tests/e2e/advanced-checks/merge-tags.test.js
|
1496
|
import { infoText } from '../utilities/page-model/helpers/field'
import AdvancedCheck from '../utilities/page-model/helpers/advanced-check'
const advancedCheck = new AdvancedCheck()
fixture`Form merge tags test`
test('should check if form merge tags is working properly', async t => {
// Actions
await advancedCheck.navigateConfirmationSection('gf_edit_forms&view=settings&subview=confirmation&id=4')
await t
.click(advancedCheck.confirmationTextCheckbox)
.click(advancedCheck.wysiwgEditorTextTab)
.click(advancedCheck.wysiwgEditor)
.pressKey('ctrl+a')
.pressKey('backspace')
await advancedCheck.pickMergeTag('Text')
await advancedCheck.pickMergeTag('Name (First)')
await advancedCheck.pickMergeTag('Name (Last)')
await advancedCheck.pickMergeTag('Email')
await t
.click(advancedCheck.saveConfirmationButton)
.click(advancedCheck.previewLink)
.typeText(advancedCheck.textInputField, 'texttest', { paste: true })
.typeText(advancedCheck.fNameInputField, 'firstnametest', { paste: true })
.typeText(advancedCheck.lNameInputField, 'lastnametest', { paste: true })
.typeText(advancedCheck.emailInputField, 'email@test.com', { paste: true })
.click(advancedCheck.submitButton)
// Assertions
await t
.expect(infoText('texttest', 'div').exists).ok()
.expect(infoText('firstnametest', 'div').exists).ok()
.expect(infoText('lastnametest', 'div').exists).ok()
.expect(infoText('email@test.com', 'div').exists).ok()
})
|
gpl-2.0
|
puntable/kraken-magento
|
app/code/local/Welance/Kraken/Block/Adminhtml/Images/Skin.php
|
908
|
<?php
class Welance_Kraken_Block_Adminhtml_Images_Skin extends Mage_Core_Block_Template
{
public function getSkinImageCount()
{
return Mage::helper('welance_kraken')->getImageCount(Welance_Kraken_Model_Abstract::TYPE_SKIN);
}
public function getSkinImageFolderCount()
{
return Mage::helper('welance_kraken')->countImages(Welance_Kraken_Model_Abstract::TYPE_SKIN);
}
public function getNewImagesAsJson()
{
$helper = Mage::helper('welance_kraken');
$images = $helper->getAllImages(Welance_Kraken_Model_Abstract::TYPE_SKIN);
$i = 0;
foreach($images as $image){
if($helper->imageExits(Welance_Kraken_Model_Abstract::TYPE_SKIN,$image['dir'],$image['name'],$image['checksum'])){
unset($images[$i]);
}
$i++;
}
return json_encode(array_values($images));
}
}
|
gpl-2.0
|
Fat-Zer/tdelibs
|
interfaces/tdeimproxy/library/tdeimproxy.cpp
|
17968
|
/*
tdeimproxy.cpp
IM service library for KDE
Copyright (c) 2004 Will Stephenson <lists@stevello.free-online.co.uk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <tqglobal.h>
#include <tqpixmapcache.h>
#include <dcopclient.h>
#include <tdeapplication.h>
#include <kdcopservicestarter.h>
#include <kdebug.h>
#include <tdemessagebox.h>
#include <ksimpleconfig.h>
#include <kiconloader.h>
#include <kservice.h>
#include <kservicetype.h>
#include "kimiface_stub.h"
#include "tdeimproxy.h"
static KStaticDeleter<KIMProxy> _staticDeleter;
KIMProxy * KIMProxy::s_instance = 0L;
struct AppPresenceCurrent
{
TQCString appId;
int presence;
};
class ContactPresenceListCurrent : public TQValueList<AppPresenceCurrent>
{
public:
// return value indicates if the supplied parameter was better than any existing presence
bool update( const AppPresenceCurrent );
AppPresenceCurrent best();
};
struct KIMProxy::Private
{
DCOPClient * dc;
// list of the strings in use by KIMIface
TQStringList presence_strings;
// list of the icon names in use by KIMIface
TQStringList presence_icons;
// map of presences
PresenceStringMap presence_map;
};
bool ContactPresenceListCurrent::update( AppPresenceCurrent ap )
{
if ( isEmpty() )
{
append( ap );
return true;
}
bool bestChanged = false;
AppPresenceCurrent best;
best.presence = -1;
ContactPresenceListCurrent::iterator it = begin();
const ContactPresenceListCurrent::iterator itEnd = end();
ContactPresenceListCurrent::iterator existing = itEnd;
while ( it != itEnd )
{
if ( (*it).presence > best.presence )
best = (*it);
if ( (*it).appId == ap.appId )
existing = it;
++it;
}
if ( ap.presence > best.presence ||
best.appId == ap.appId )
bestChanged = true;
if ( existing != itEnd )
{
remove( existing );
append( ap );
}
return bestChanged;
}
AppPresenceCurrent ContactPresenceListCurrent::best()
{
AppPresenceCurrent best;
best.presence = -1;
ContactPresenceListCurrent::iterator it = begin();
const ContactPresenceListCurrent::iterator itEnd = end();
while ( it != itEnd )
{
if ( (*it).presence > best.presence )
best = (*it);
++it;
}
// if it's still -1 here, we have no presence data, so we return Unknown
if ( best.presence == -1 )
best.presence = 0;
return best;
}
// int bestPresence( AppPresence* ap )
// {
// Q_ASSERT( ap );
// AppPresence::const_iterator it;
// it = ap->begin();
// int best = 0; // unknown
// if ( it != ap->end() )
// {
// best = it.data();
// ++it;
// for ( ; it != ap->end(); ++it )
// {
// if ( it.data() > best )
// best = it.data();
// }
// }
// return best;
// }
//
// TQCString bestAppId( AppPresence* ap )
// {
// Q_ASSERT( ap );
// AppPresence::const_iterator it;
// TQCString bestAppId;
// it = ap->begin();
// if ( it != ap->end() )
// {
// int best = it.data();
// bestAppId = it.key();
// ++it;
// for ( ; it != ap->end(); ++it )
// {
// if ( it.data() > best )
// {
// best = it.data();
// bestAppId = it.key();
// }
// }
// }
// return bestAppId;
// }
KIMProxy * KIMProxy::instance( DCOPClient * client )
{
if ( client )
{
if ( !s_instance )
_staticDeleter.setObject( s_instance, new KIMProxy( client ) );
return s_instance;
}
else
return 0L;
}
KIMProxy::KIMProxy( DCOPClient* dc ) : DCOPObject( "KIMProxyIface" ), TQObject(), d( new Private )
{
m_im_client_stubs.setAutoDelete( true );
d->dc = dc;
m_initialized = false;
connect( d->dc, TQT_SIGNAL( applicationRemoved( const TQCString& ) ) , this, TQT_SLOT( unregisteredFromDCOP( const TQCString& ) ) );
connect( d->dc, TQT_SIGNAL( applicationRegistered( const TQCString& ) ) , this, TQT_SLOT( registeredToDCOP( const TQCString& ) ) );
d->dc->setNotifications( true );
d->presence_strings.append( "Unknown" );
d->presence_strings.append( "Offline" );
d->presence_strings.append( "Connecting" );
d->presence_strings.append( "Away" );
d->presence_strings.append( "Online" );
d->presence_icons.append( "presence_unknown" );
d->presence_icons.append( "presence_offline" );
d->presence_icons.append( "presence_connecting" );
d->presence_icons.append( "presence_away" );
d->presence_icons.append( "presence_online" );
//TQCString senderApp = "Kopete";
//TQCString senderObjectId = "KIMIface";
TQCString method = "contactPresenceChanged( TQString, TQCString, int )";
//TQCString receiverObjectId = "KIMProxyIface";
// FIXME: make this work when the sender object id is set to KIMIFace
if ( !connectDCOPSignal( 0, 0, method, method, false ) )
kdWarning() << "Couldn't connect DCOP signal. Won't receive any status notifications!" << endl;
}
KIMProxy::~KIMProxy( )
{
//d->dc->setNotifications( false );
}
bool KIMProxy::initialize()
{
if ( !m_initialized )
{
m_initialized = true; // we should only do this once, as registeredToDCOP() will catch any new starts
// So there is no error from a failed query when using tdelibs 3.2, which don't have this servicetype
if ( KServiceType::serviceType( IM_SERVICE_TYPE ) )
{
//kdDebug( 790 ) << k_funcinfo << endl;
TQCString dcopObjectId = "KIMIface";
// see what apps implementing our service type are out there
KService::List offers = KServiceType::offers( IM_SERVICE_TYPE );
KService::List::iterator offer;
typedef TQValueList<TQCString> QCStringList;
QCStringList registeredApps = d->dc->registeredApplications();
QCStringList::iterator app;
const QCStringList::iterator end = registeredApps.end();
// for each registered app
for ( app = registeredApps.begin(); app != end; ++app )
{
//kdDebug( 790 ) << " considering: " << *app << endl;
//for each offer
for ( offer = offers.begin(); offer != offers.end(); ++offer )
{
TQCString dcopService = (*offer)->property("X-DCOP-ServiceName").toString().latin1();
if ( !dcopService.isEmpty() )
{
//kdDebug( 790 ) << " is it: " << dcopService << "?" << endl;
// get the application name ( minus any process ID )
TQCString instanceName = (*app).left( dcopService.length() );
// if the application implements the dcop service, add it
if ( instanceName == dcopService )
{
m_apps_available = true;
//kdDebug( 790 ) << " app name: " << (*offer)->name() << ", has instance " << *app << ", dcopService: " << dcopService << endl;
if ( !m_im_client_stubs.find( dcopService ) )
{
kdDebug( 790 ) << "App " << *app << ", dcopObjectId " << dcopObjectId << " found, using it for presence info." << endl;
m_im_client_stubs.insert( *app, new KIMIface_stub( d->dc, *app, dcopObjectId ) );
pollApp( *app );
}
}
}
}
}
}
}
return !m_im_client_stubs.isEmpty();
}
void KIMProxy::registeredToDCOP( const TQCString& appId )
{
//kdDebug( 790 ) << k_funcinfo << " appId '" << appId << "'" << endl;
// check that appId implements our service
// if the appId ends with a number, i.e. a pid like in foobar-12345,
if ( appId.isEmpty() )
return;
bool newApp = false;
// get an up to date list of offers in case a new app was installed
// and check each of the offers that implement the service type we're looking for,
// to see if any of them are the app that just registered
const KService::List offers = KServiceType::offers( IM_SERVICE_TYPE );
KService::List::const_iterator it;
for ( it = offers.begin(); it != offers.end(); ++it )
{
TQCString dcopObjectId = "KIMIface";
TQCString dcopService = (*it)->property("X-DCOP-ServiceName").toString().latin1();
if ( appId.left( dcopService.length() ) == dcopService )
{
// if it's not already known, insert it
if ( !m_im_client_stubs.find( appId ) )
{
newApp = true;
kdDebug( 790 ) << "App: " << appId << ", dcopService: " << dcopService << " started, using it for presence info."<< endl;
m_im_client_stubs.insert( appId, new KIMIface_stub( d->dc, appId, dcopObjectId ) );
}
}
//else
// kdDebug( 790 ) << "App doesn't implement our ServiceType" << endl;
}
//if ( newApp )
// emit sigPresenceInfoExpired();
}
void KIMProxy::unregisteredFromDCOP( const TQCString& appId )
{
//kdDebug( 790 ) << k_funcinfo << appId << endl;
if ( m_im_client_stubs.find( appId ) )
{
kdDebug( 790 ) << appId << " quit, removing its presence info." << endl;
PresenceStringMap::Iterator it = d->presence_map.begin();
const PresenceStringMap::Iterator end = d->presence_map.end();
for ( ; it != end; ++it )
{
ContactPresenceListCurrent list = it.data();
ContactPresenceListCurrent::iterator cpIt = list.begin();
while( cpIt != list.end() )
{
ContactPresenceListCurrent::iterator gone = cpIt++;
if ( (*gone).appId == appId )
{
list.remove( gone );
}
}
}
m_im_client_stubs.remove( appId );
emit sigPresenceInfoExpired();
}
}
void KIMProxy::contactPresenceChanged( TQString uid, TQCString appId, int presence )
{
// update the presence map
//kdDebug( 790 ) << k_funcinfo << "uid: " << uid << " appId: " << appId << " presence " << presence << endl;
ContactPresenceListCurrent current;
current = d->presence_map[ uid ];
//kdDebug( 790 ) << "current best presence from : " << current.best().appId << " is: " << current.best().presence << endl;
AppPresenceCurrent newPresence;
newPresence.appId = appId;
newPresence.presence = presence;
if ( current.update( newPresence ) )
{
d->presence_map.insert( uid, current );
emit sigContactPresenceChanged( uid );
}
}
int KIMProxy::presenceNumeric( const TQString& uid )
{
AppPresenceCurrent ap;
ap.presence = 0;
if ( initialize() )
{
ContactPresenceListCurrent presence = d->presence_map[ uid ];
ap = presence.best();
}
return ap.presence;
}
TQString KIMProxy::presenceString( const TQString& uid )
{
AppPresenceCurrent ap;
ap.presence = 0;
if ( initialize() )
{
ContactPresenceListCurrent presence = d->presence_map[ uid ];
ap = presence.best();
}
if ( ap.appId.isEmpty() )
return TQString::null;
else
return d->presence_strings[ ap.presence ];
}
TQPixmap KIMProxy::presenceIcon( const TQString& uid )
{
AppPresenceCurrent ap;
ap.presence = 0;
if ( initialize() )
{
ContactPresenceListCurrent presence = d->presence_map[ uid ];
ap = presence.best();
}
if ( ap.appId.isEmpty() )
{
//kdDebug( 790 ) << k_funcinfo << "returning a null TQPixmap because we were asked for an icon for a uid we know nothing about" << endl;
return TQPixmap();
}
else
{
//kdDebug( 790 ) << k_funcinfo << "returning this: " << d->presence_icons[ ap.presence ] << endl;
return SmallIcon( d->presence_icons[ ap.presence ]);
}
}
TQStringList KIMProxy::allContacts()
{
TQStringList value = d->presence_map.keys();
return value;
}
TQStringList KIMProxy::reachableContacts()
{
TQStringList value;
if ( initialize() )
{
TQDictIterator<KIMIface_stub> it( m_im_client_stubs );
for ( ; it.current(); ++it )
{
value += it.current()->reachableContacts( );
}
}
return value;
}
TQStringList KIMProxy::onlineContacts()
{
TQStringList value;
PresenceStringMap::iterator it = d->presence_map.begin();
const PresenceStringMap::iterator end= d->presence_map.end();
for ( ; it != end; ++it )
if ( it.data().best().presence > 2 /*Better than Connecting, ie Away or Online*/ )
value.append( it.key() );
return value;
}
TQStringList KIMProxy::fileTransferContacts()
{
TQStringList value;
if ( initialize() )
{
TQDictIterator<KIMIface_stub> it( m_im_client_stubs );
for ( ; it.current(); ++it )
{
value += it.current()->fileTransferContacts( );
}
}
return value;
}
bool KIMProxy::isPresent( const TQString& uid )
{
return ( !d->presence_map[ uid ].isEmpty() );
}
TQString KIMProxy::displayName( const TQString& uid )
{
TQString name;
if ( initialize() )
{
if ( KIMIface_stub* s = stubForUid( uid ) )
name = s->displayName( uid );
}
//kdDebug( 790 ) << k_funcinfo << name << endl;
return name;
}
bool KIMProxy::canReceiveFiles( const TQString & uid )
{
if ( initialize() )
{
if ( KIMIface_stub* s = stubForUid( uid ) )
return s->canReceiveFiles( uid );
}
return false;
}
bool KIMProxy::canRespond( const TQString & uid )
{
if ( initialize() )
{
if ( KIMIface_stub* s = stubForUid( uid ) )
return s->canRespond( uid );
}
return false;
}
TQString KIMProxy::context( const TQString & uid )
{
if ( initialize() )
{
if ( KIMIface_stub* s = stubForUid( uid ) )
return s->context( uid );
}
return TQString::null;
}
void KIMProxy::chatWithContact( const TQString& uid )
{
if ( initialize() )
{
if ( KIMIface_stub* s = stubForUid( uid ) )
{
kapp->updateRemoteUserTimestamp( s->app() );
s->chatWithContact( uid );
}
}
return;
}
void KIMProxy::messageContact( const TQString& uid, const TQString& message )
{
if ( initialize() )
{
if ( KIMIface_stub* s = stubForUid( uid ) )
{
kapp->updateRemoteUserTimestamp( s->app() );
s->messageContact( uid, message );
}
}
return;
}
void KIMProxy::sendFile(const TQString &uid, const KURL &sourceURL, const TQString &altFileName, uint fileSize )
{
if ( initialize() )
{
TQDictIterator<KIMIface_stub> it( m_im_client_stubs );
for ( ; it.current(); ++it )
{
if ( it.current()->canReceiveFiles( uid ) )
{
kapp->updateRemoteUserTimestamp( it.current()->app() );
it.current()->sendFile( uid, sourceURL, altFileName, fileSize );
break;
}
}
}
return;
}
bool KIMProxy::addContact( const TQString &contactId, const TQString &protocol )
{
if ( initialize() )
{
if ( KIMIface_stub* s = stubForProtocol( protocol ) )
return s->addContact( contactId, protocol );
}
return false;
}
TQString KIMProxy::locate( const TQString & contactId, const TQString & protocol )
{
if ( initialize() )
{
if ( KIMIface_stub* s = stubForProtocol( protocol ) )
return s->locate( contactId, protocol );
}
return TQString::null;
}
bool KIMProxy::imAppsAvailable()
{
return ( !m_im_client_stubs.isEmpty() );
}
bool KIMProxy::startPreferredApp()
{
TQString preferences = TQString("[X-DCOP-ServiceName] = '%1'").arg( preferredApp() );
// start/find an instance of DCOP/InstantMessenger
TQString error;
TQCString dcopService;
// Get a preferred IM client.
// The app will notify itself to us using registeredToDCOP, so we don't need to record a stub for it here
// FIXME: error in preferences, see debug output
preferences = TQString::null;
int result = KDCOPServiceStarter::self()->findServiceFor( IM_SERVICE_TYPE, TQString::null, preferences, &error, &dcopService );
kdDebug( 790 ) << k_funcinfo << "error was: " << error << ", dcopService: " << dcopService << endl;
return ( result == 0 );
}
void KIMProxy::pollAll( const TQString &uid )
{
/* // We only need to call this function if we don't have any data at all
// otherwise, the data will be kept fresh by received presence change
// DCOP signals
if ( !d->presence_map.contains( uid ) )
{
AppPresence *presence = new AppPresence();
// record current presence from known clients
TQDictIterator<KIMIface_stub> it( m_im_client_stubs );
for ( ; it.current(); ++it )
{
presence->insert( it.currentKey().ascii(), it.current()->presenceStatus( uid ) ); // m_im_client_stubs has qstring keys...
}
d->presence_map.insert( uid, presence );
}*/
}
void KIMProxy::pollApp( const TQCString & appId )
{
//kdDebug( 790 ) << k_funcinfo << endl;
KIMIface_stub * appStub = m_im_client_stubs[ appId ];
TQStringList contacts = m_im_client_stubs[ appId ]->allContacts();
TQStringList::iterator it = contacts.begin();
TQStringList::iterator end = contacts.end();
for ( ; it != end; ++it )
{
ContactPresenceListCurrent current = d->presence_map[ *it ];
AppPresenceCurrent ap;
ap.appId = appId;
ap.presence = appStub->presenceStatus( *it );
current.append( ap );
d->presence_map.insert( *it, current );
if ( current.update( ap ) )
emit sigContactPresenceChanged( *it );
//kdDebug( 790 ) << " uid: " << *it << " presence: " << ap.presence << endl;
}
}
KIMIface_stub * KIMProxy::stubForUid( const TQString &uid )
{
// get best appPresence
AppPresenceCurrent ap = d->presence_map[ uid ].best();
// look up the presence string from that app
return m_im_client_stubs.find( ap.appId );
}
KIMIface_stub * KIMProxy::stubForProtocol( const TQString &protocol)
{
KIMIface_stub * app;
// see if the preferred client supports this protocol
TQString preferred = preferredApp();
if ( ( app = m_im_client_stubs.find( preferred ) ) )
{
if ( app->protocols().grep( protocol ).count() > 0 )
return app;
}
// preferred doesn't do this protocol, try the first of the others that says it does
TQDictIterator<KIMIface_stub> it( m_im_client_stubs );
for ( ; it.current(); ++it )
{
if ( it.current()->protocols().grep( protocol ).count() > 0 )
return it.current();
}
return 0L;
}
TQString KIMProxy::preferredApp()
{
TDEConfig *store = new KSimpleConfig( IM_CLIENT_PREFERENCES_FILE );
store->setGroup( IM_CLIENT_PREFERENCES_SECTION );
TQString preferredApp = store->readEntry( IM_CLIENT_PREFERENCES_ENTRY );
//kdDebug( 790 ) << k_funcinfo << "found preferred app: " << preferredApp << endl;
return preferredApp;
}
#include "tdeimproxy.moc"
|
gpl-2.0
|
Morthalin/TheGame
|
V pasti/Assets/Scripts/GUI/Choice.cs
|
1784
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Choice : MonoBehaviour {
// Use this for initialization
float oldTimeScale;
void Start () {
GameObject.Find ("Player").GetComponent<BasePlayer> ().pause++;
oldTimeScale = Time.timeScale;
Time.timeScale = 0.0f;
}
// Update is called once per frame
void Update () {
}
// show it by: GameObject.Find ("Interface").transform.Find ("Choice").gameObject.SetActive (true);
public void V1_onClick(){
BasePlayer pl = GameObject.Find ("Player").GetComponent<BasePlayer> ();
if (!pl) {
Debug.LogError ("Missing player");
return;
}
pl.storyCheckpoint = 28;
GameObject.Find ("Interface").transform.Find ("Choice").gameObject.SetActive (false);
// GameObject.Find ("Mages_cave").transform.Find ("mage").GetComponent<Animator>().SetBool("combat", false);
// GameObject.Find ("Mages_cave").transform.Find ("mage").GetComponent<Animator>().SetBool("running", false);
GameObject.Find("Player").GetComponent<BasePlayer>().pause--;
Time.timeScale = oldTimeScale;
}
public void V2_onClick(){
BasePlayer pl = GameObject.Find ("Player").GetComponent<BasePlayer> ();
if (!pl) {
Debug.LogError ("Missing player");
return;
}
pl.storyCheckpoint = 30;
GameObject.Find ("Interface").transform.Find ("Choice").gameObject.SetActive (false);
// GameObject.Find ("Mages_cave").transform.Find ("mage").GetComponent<Animator>().SetBool("combat", true);
// GameObject.Find ("Mages_cave").transform.Find ("mage").GetComponent<Animator>().SetBool("running", true);
// GameObject.Find ("Mages_cave").transform.Find ("mage").transform.GetComponent<BaseNPC> ().inCombat = true;
GameObject.Find("Player").GetComponent<BasePlayer>().pause--;
Time.timeScale = oldTimeScale;
}
}
|
gpl-2.0
|
lpinsivy/centreon
|
core/internal/Install/Db.php
|
13200
|
<?php
/*
* Copyright 2005-2015 CENTREON
* Centreon is developped by : Julien Mathis and Romain Le Merlus under
* GPL Licence 2.0.
*
* 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.
*
* 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>.
*
* Linking this program statically or dynamically with other modules is making a
* combined work based on this program. Thus, the terms and conditions of the GNU
* General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this program give CENTREON
* permission to link this program with independent modules to produce an executable,
* regardless of the license terms of these independent modules, and to copy and
* distribute the resulting executable under terms of CENTREON choice, provided that
* CENTREON also meet, for each linked independent module, the terms and conditions
* of the license of that module. An independent module is a module which is not
* derived from this program. If you modify this program, you may extend this
* exception to your version of the program, but you are not obliged to do so. If you
* do not wish to do so, delete this exception statement from your version.
*
* For more information : contact@centreon.com
*
*/
namespace Centreon\Internal\Install;
use Centreon\Internal\Utils\Filesystem\File;
use Centreon\Internal\Utils\Filesystem\Directory;
use Centreon\Internal\Di;
use Centreon\Custom\Propel\CentreonMysqlPlatform;
use Centreon\Internal\Module\Informations;
class Db
{
/**
*
* @param string $module
* @param string $action
*/
public static function update($module, $action = 'create')
{
$targetDbName = 'centreon';
ini_set('memory_limit', '-1');
$di = Di::getDefault();
$config = $di->get('config');
$targetDb = 'db_centreon';
$db = $di->get($targetDb);
// Configuration for Propel
$configParams = array(
'propel.project' => 'centreon',
'propel.database' => 'mysql',
'propel.database.url' => $config->get($targetDb, 'dsn'),
'propel.database.user' => $config->get($targetDb, 'username'),
'propel.database.password' => $config->get($targetDb, 'password')
);
// Set the Current Platform and DB Connection
$platform = new CentreonMysqlPlatform($db);
// Initilize Schema Parser
$propelDb = new \MysqlSchemaParser($db);
$propelDb->setGeneratorConfig(new \GeneratorConfig($configParams));
$propelDb->setPlatform($platform);
// get Current Db State
$currentDbAppData = new \AppData($platform);
$currentDbAppData->setGeneratorConfig(new \GeneratorConfig($configParams));
$currentDb = $currentDbAppData->addDatabase(array('name' => $targetDbName));
$propelDb->parse($currentDb);
// Retreive target DB State
$updatedAppData = new \AppData($platform);
self::getDbFromXml($updatedAppData, 'centreon');
// Get diff between current db state and target db state
$diff = \PropelDatabaseComparator::computeDiff(
$currentDb,
$updatedAppData->getDatabase('centreon'),
false
);
if ($diff !== false) {
$strDiff = $platform->getModifyDatabaseDDL($diff);
$sqlToBeExecuted = \PropelSQLParser::parseString($strDiff);
$finalSql = "\nSET FOREIGN_KEY_CHECKS = 0;\n\n";
if ($action == 'create') {
$finalSql .= implode(";\n\n", static::keepCreateStatement($sqlToBeExecuted, $module));
} elseif ($action == 'delete') {
$finalSql .= implode(";\n\n", static::keepDeleteStatement($sqlToBeExecuted, $module));
}
$finalSql .= ";\n\nSET FOREIGN_KEY_CHECKS = 1;\n\n";
\PropelSQLParser::executeString($finalSql, $db);
}
// Empty Target DB
self::deleteTargetDbSchema($targetDbName);
}
/**
*
* @param \AppData $myAppData
* @param string $targetDbName
*/
public static function getDbFromXml(& $myAppData, $targetDbName)
{
$db = self::getDbConnector($targetDbName);
$xmlDbFiles = self::buildTargetDbSchema($targetDbName);
// Initialize XmlToAppData object
$appDataObject = new \XmlToAppData(new CentreonMysqlPlatform($db), null, 'utf-8');
// Get DB File
foreach ($xmlDbFiles as $dbFile) {
$myAppData->joinAppDatas(array($appDataObject->parseFile($dbFile)));
unset($appDataObject);
$appDataObject = new \XmlToAppData(new CentreonMysqlPlatform($db), null, 'utf-8');
}
unset($appDataObject);
}
/**
*
* @param string $targetDbName
*/
private static function deleteTargetDbSchema($targetDbName = 'centreon')
{
// Initialize configuration
$di = Di::getDefault();
$config = $di->get('config');
$centreonPath = $config->get('global', 'centreon_generate_tmp_dir');
$targetFolder = $centreonPath . '/tmp/db/target/' . $targetDbName . '/';
$currentFolder = $centreonPath . '/tmp/db/current/' . $targetDbName . '/';
// Copy to destination
if (!file_exists($currentFolder)) {
mkdir($currentFolder, 0775, true);
if (posix_getuid() == 0) {
chown($currentFolder, 'centreon');
chgrp($currentFolder, 'centreon');
}
}
$fileList = glob($targetFolder . '/*.xml');
$nbOfFiles = count($fileList);
for ($i=0; $i<$nbOfFiles; $i++) {
$targetFile = $currentFolder . basename($fileList[$i]);
copy($fileList[$i], $targetFile);
if (posix_getuid() == 0) {
chmod($targetFile, 0664);
chown($targetFile, 'centreon');
chgrp($targetFile, 'centreon');
}
unlink($fileList[$i]);
}
Directory::delete($targetFolder, true);
}
/**
*
* @param string $path
* @return boolean
*/
private static function deleteFolder($path)
{
if (is_dir($path) === true) {
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file) {
unlink(realpath($path) . '/' . $file);
}
return rmdir($path);
} else if (is_file($path) === true) {
return unlink($path);
}
return false;
}
/**
*
* @param type $targetDbName
* @return type
*/
private static function buildTargetDbSchema($targetDbName = 'centreon')
{
// Initialize configuration
$di = Di::getDefault();
$config = $di->get('config');
$centreonPath = $config->get('global', 'centreon_path');
$targetFolder = '';
$tmpFolder = '';
$tmpFolder .= trim($config->get('global', 'centreon_generate_tmp_dir'));
if (!empty($tmpFolder)) {
$targetFolder .= $tmpFolder . '/centreon/db/target/' . $targetDbName . '/';
} else {
$targetFolder .= $centreonPath . '/tmp/db/target/' . $targetDbName . '/';
}
$fileList = array();
// Mandatory tables
$fileList = array_merge(
$fileList,
File::getFiles($centreonPath . '/install/db/' . $targetDbName, 'xml')
);
$moduleList = Informations::getModuleList(false);
foreach ($moduleList as $module) {
$expModuleName = array_map(function ($n) { return ucfirst($n); }, explode('-', $module));
$moduleFileSystemName = implode("", $expModuleName) . 'Module';
$fileList = array_merge(
$fileList,
File::getFiles(
$centreonPath . '/modules/' . $moduleFileSystemName . '/install/db/' . $targetDbName, 'xml'
)
);
}
// Copy to destination
if (!file_exists($targetFolder)) {
mkdir($targetFolder, 0777, true);
}
$nbOfFiles = count($fileList);
for ($i=0; $i<$nbOfFiles; $i++) {
$targetFile = $targetFolder . basename($fileList[$i]);
copy($fileList[$i], $targetFile);
}
// send back the computed db
return glob($targetFolder . '/*.xml');
}
/**
*
* @param string $dirname
* @param string $targetDbName
*/
public static function loadDefaultDatas($dirname, $targetDbName = 'centreon')
{
$dirname = rtrim($dirname, '/');
$orderFile = $dirname . '/' . $targetDbName . '.json';
$db = self::getDbConnector($targetDbName);
$db->beginTransaction();
if (file_exists($orderFile)) {
$insertionOrder = json_decode(file_get_contents($orderFile), true);
foreach ($insertionOrder as $fileBaseName) {
$datasFile = $dirname . '/' . $targetDbName . '/'. $fileBaseName . '.json';
self::insertDatas($datasFile, $targetDbName);
}
} else {
$datasFiles = File::getFiles($dirname, 'json');
foreach ($datasFiles as $datasFile) {
self::insertDatas($datasFile, $targetDbName);
}
}
$db->commit();
}
/**
*
* @param string $datasFile
* @param string $targetDbName
*/
private static function insertDatas($datasFile, $targetDbName)
{
ini_set('memory_limit', '-1');
$db = self::getDbConnector($targetDbName);
if (file_exists($datasFile)) {
$tableName = basename($datasFile, '.json');
$datas = json_decode(file_get_contents($datasFile), true);
foreach ($datas as $data) {
$fields = "";
$values = "";
foreach ($data as $key=>$value) {
$fields .= "`$key`,";
if (is_array($value)) {
if ($value['domain'] == 'php') {
$values .= $db->quote($value['function']()) . ",";
} else {
$values .= "$value[function](),";
}
} else {
$values .= $db->quote($value) . ",";
}
}
$insertQuery = "INSERT INTO `$tableName` (". rtrim($fields, ',') .") VALUES (" . rtrim($values, ',') . ") ";
$db->query($insertQuery);
}
}
}
/**
*
* @param string $dbName
* @return type
*/
private static function getDbConnector($dbName)
{
$di = Di::getDefault();
if ($dbName == 'centreon_storage') {
$targetDb = 'db_storage';
} else {
$targetDb = 'db_' . $dbName;
}
$db = $di->get($targetDb);
return $db;
}
/**
*
* @param array $queries
* @param string $module
* @return array
*/
private static function keepCreateStatement($queries, $module)
{
return static::keepStatement('CREATE TABLE', $queries, $module);
}
/**
*
* @param array $queries
* @param string $module
* @return array
*/
private static function keepDeleteStatement($queries, $module)
{
return static::keepStatement('DROP TABLE', $queries, $module);
}
/**
*
* @param string $statement
* @param array $queries
* @param string $module
* @return array
*/
private static function keepStatement($statement, $queries, $module)
{
$finalQueries = array();
$moduleTables = Informations::getModuleTables($module);
$numberOfQueries = count($queries);
for ($i=0; $i<$numberOfQueries; $i++) {
if (strpos($queries[$i], $statement) !== false) {
preg_match("/\`\w+\`/", $queries[$i], $rawTargetTable);
$targetTable = trim($rawTargetTable[0], '`');
if (in_array($targetTable, $moduleTables)) {
$finalQueries[] = $queries[$i];
}
}
}
return $finalQueries;
}
}
|
gpl-2.0
|
matthewepler/moralcourage
|
wp-content/themes/moralcourage/page-tab2.php
|
1863
|
<?php
/**
* Template Name: Tab 2 Layout
*/
global $page;
$content = get_custom_content( $page->ID, 'td-layout-2');
$videoCategory = $content['video-list'];
?>
<article class="tab-layout tab2">
<h2><?php print_content($content['alternative-page-title']); ?></h2>
<p><?php print_content($content['subtitle-paragraph']); ?></p>
<section class="section-video video-tabs clearfix">
<article class="video-main clearfix">
<?php the_videos($videoCategory, 'main_video'); ?>
</article>
<aside class="shadow-div scroll-top">
<div class="video-thumbs">
<?php the_videos($videoCategory, 'thumb_video'); ?>
</div>
</aside>
<a class="load-more" href="#"><?php echo __('Load more videos'); ?></a>
</section>
<section class="section-text">
<h2><?php print_content($content['under-video-title']); ?></h2>
<?php if ($content['under-video-col-1']): ?>
<p class="paragraph col"><?php print_content($content['under-video-col-1']); ?></p>
<?php endif; ?>
<?php if ($content['under-video-col-2']): ?>
<p class="middle paragraph col"><?php print_content($content['under-video-col-2']); ?></p>
<?php endif; ?>
<?php if ($content['under-video-col-3']): ?>
<p class="paragraph col"><?php print_content($content['under-video-col-3']); ?></p>
<?php endif; ?>
<p class="last paragraph">
<?php print_content($content['last-paragraph']); ?>
</p>
</section>
</article>
<?php
?>
|
gpl-2.0
|
DOable/DOable
|
sites/all/modules/contrib/acquia_lift/js/acquia_lift.goals_queue.js
|
14499
|
/**
* Utility functions for stateless queue cookie processing.
*
* Functionality includes basic read/write functionality.
*/
(function ($, Drupal) {
"use strict";
Drupal.acquiaLiftUtility = Drupal.acquiaLiftUtility || {};
Drupal.acquiaLiftUtility.QueueItem = function (params) {
var queueItemUid,
queueItemData,
queueItemProcessing = false,
numberTried = 0;
/**
* Returns the unique ID assigned to this queue item.
*/
this.getId = function () {
return queueItemUid;
};
/**
* Sets the unique ID assigned to this queue item.
*/
this.setId = function (value) {
queueItemUid = value;
}
/**
* Returns the data that is held by this queue item.
*/
this.getData = function () {
return queueItemData;
};
/**
* Setter for the data held by this queue item.
*/
this.setData = function (value) {
queueItemData = value;
}
;
/**
* Determines if this queue item is currently processing.
*/
this.isProcessing = function () {
return queueItemProcessing;
};
/**
* Setter for the processing flag for this queue item.
*/
this.setProcessing = function (isProcessing) {
queueItemProcessing = isProcessing;
};
/**
* Gets the number of times this item has been tried in the queue.
*/
this.getNumberTried = function () {
return numberTried;
};
/**
* Sets the number of times this item has been tried in the queue.
*/
this.setNumberTried = function (value) {
numberTried = value;
};
/**
* Increments the number of times this item has been tried.
*/
this.incrementTries = function () {
numberTried++;
};
// Constructor handling.
if (params.hasOwnProperty('id')
&& params.hasOwnProperty('data')
&& params.hasOwnProperty('pflag')
&& params.hasOwnProperty('try')) {
this.setId(params.id);
this.setData(params.data);
this.setProcessing(params.pflag);
this.setNumberTried(params.try);
} else {
var uid = 'acquia-lift-ts-' + new Date().getTime() + Math.random();
this.setId(uid);
this.setData(params);
this.setProcessing(false);
this.setNumberTried(0);
}
};
Drupal.acquiaLiftUtility.QueueItem.prototype = {
constructor: Drupal.acquiaLiftUtility.QueueItem,
/**
* Determines if QueueItem is equal to the current QueueItem.
*
* @param queueItem
* The item to check against.
* @returns
* True if equal, false if unequal.
*/
'equals': function (queueItem) {
return (queueItem instanceof Drupal.acquiaLiftUtility.QueueItem && queueItem.getId() == this.getId());
},
/**
* Resets the processing flag on this queue item.
*/
'reset': function() {
this.setProcessing(false);
},
/**
* Parses the QueueItem into a simple object.
*/
'toObject': function () {
return {
'id': this.getId(),
'data': this.getData(),
'pflag': this.isProcessing(),
'try': this.getNumberTried()
};
}
}
Drupal.acquiaLiftUtility.Queue = Drupal.acquiaLiftUtility.Queue || (function($) {
// @todo: Would be cool if we could swap out back-ends to local storage or
// other mechanism.
var cookieName = 'acquiaLiftQueue', maxRetries = 5;
/**
* Indicates if the cookie handling script handles object serialization.
* This is not available in the jquery.cookie.js version that ships with
* Drupal 7 but some installations use a later version.
*
* @return boolean
* True if cookie handles serialization, false if data must be manually
* serialized before writing.
*/
function cookieHandlesSerialization() {
return ($.cookie.json && $.cookie.json == true);
}
/**
* Reads the queue from storage.
*
* @returns array
* An array of QueueItems.
*/
function readQueue() {
var queue = $.cookie(cookieName);
var unserialized = cookieHandlesSerialization() ? queue : $.parseJSON(queue);
return $.isArray(unserialized) ? unserialized : [];
}
/**
* Returns a fully-parsed queue.
*/
function getAll() {
var unserialized = readQueue(), i, num = unserialized.length, queue = [];
for (i = 0; i < num; i++) {
queue.push(new Drupal.acquiaLiftUtility.QueueItem(unserialized[i]));
}
return queue;
}
/**
* Returns the first unprocessed QueueItem.
*/
function getFirstUnprocessed() {
var unserialized = readQueue(), i, num = unserialized.length, item;
for (i = 0; i < num; i++) {
item = new Drupal.acquiaLiftUtility.QueueItem(unserialized[i]);
if (!item.isProcessing()) {
return item;
}
}
return null;
}
/**
* Find index of a QueueItem within the Queue.
*
* @param queue
* An instance of the queue to search.
* @param item
* The QueueItem to find within the queue.
* @return int
* The index of the item in the queue or -1 if not found.
*/
function indexOf(queue, item) {
var i,
num = queue.length,
test;
// Only initialize as many as we have to in order to find a match.
for (i = 0; i < num; i++) {
test = new Drupal.acquiaLiftUtility.QueueItem(queue[i]);
if (test.equals(item)) {
return i;
}
}
return -1;
}
/**
* Writes the queue to storage.
*
* @param array
* The queue as an array.
*/
function writeQueue(queue) {
var queueData = [], i, num = queue.length;
// Prepare the queue by making sure all items to save are simple objects.
for (i = 0; i < num; i++) {
if (queue[i] instanceof Drupal.acquiaLiftUtility.QueueItem) {
queueData.push(queue[i].toObject())
} else {
queueData.push(queue[i]);
}
}
// Serialize if necessary.
if (!cookieHandlesSerialization()) {
queueData = JSON.stringify(queueData);
}
// Write to the cookie.
$.cookie(cookieName, queueData);
}
/**
* Adds an existing QueueItem back to the queue for re-processing.
*
* @param queueItem
* The item to add back into the queue.
* @param reset
* Boolean indicates if the processing flag should be reset, defaults
* false.
*/
function addBack(queueItem, reset) {
var queue = readQueue();
var index = indexOf(queue, queueItem);
if (reset && reset == true) {
queueItem.reset();
queueItem.incrementTries();
}
if (queueItem.getNumberTried() >= maxRetries) {
// This item is beyond the maximum number of tries and should be
// removed from the queue so don't add it back.
Drupal.acquiaLiftUtility.Queue.remove(queueItem);
return;
}
if (index >= 0) {
queue.splice(index, 1, queueItem);
} else {
queue.push(queueItem);
}
writeQueue(queue);
};
/**
* Publicly accessible queue methods.
*/
return {
/**
* Adds a QueueItem to the queue.
*
* The item can be new data to add, a new QueueItem to add, or an
* existing QueueItem to return to the queue for re-processing.
*
* @param data
* Data or a QueueItem to add to the queue.
* @param reset
* Indicates if the processing should be reset (defaults to true).
*/
'add': function (data, reset) {
reset = reset == undefined ? true : reset;
if (data instanceof Drupal.acquiaLiftUtility.QueueItem) {
addBack(data, reset);
return;
}
var queue = readQueue();
queue.push(new Drupal.acquiaLiftUtility.QueueItem(data));
writeQueue(queue);
},
/**
* Gets the next unprocessed item in the queue for processing.
* @returns a queueItem or null;
* The queueItem.
*/
'getNext': function () {
var item = getFirstUnprocessed();
if (item) {
item.setProcessing(true);
// Save the updated item back into the queue (will overwrite).
this.add(item, false);
}
return item;
},
/**
* Removes a queueItem from the processing queue.
*
* @param queueItem
* The item to remove.
* @returns
* True if the item was found to remove, false if not found.
*/
'remove': function (queueItem) {
var queue = readQueue();
var index = indexOf(queue, queueItem);
if (index >= 0) {
queue.splice(index, 1);
writeQueue(queue);
return true;
}
return false;
},
/**
* Resets the processing status on all items in the queue.
*/
'reset': function () {
var i,
queue = getAll(),
num = queue.length;
for (i = 0; i < num; i++) {
queue[i].reset();
}
writeQueue(queue);
},
/**
* Empties the queue of all options (typcially used for testing purposes).
*/
'empty': function () {
writeQueue([]);
}
}
}($));
}(Drupal.jQuery, Drupal));
/**
* Acquia Lift goals processing queue functions.
*/
(function ($, Drupal) {
"use strict";
Drupal.acquiaLiftUtility = Drupal.acquiaLiftUtility || {};
Drupal.acquiaLiftUtility.GoalQueue = Drupal.acquiaLiftUtility.GoalQueue || (function($) {
var acquiaLiftAPI;
/**
* Converts the data for a goal into the format for saving in the queue.
*
* @param goal
* An object with the following keys:
* - agentName: The name of the agent for this gaol
* - options: An object of goal options to be sent with the goal.
* @return object
* A simple object of data to be saved.
*/
function convertGoalToQueueData(goal) {
return {'a': goal.agentName, 'o': goal.options};
}
/**
* Converts the queue data into the data for a goal.
*
* @param item
* The queue item data.
* @return object
* An object with the following keys:
* - agentName: The name of the agent for this gaol
* - options: An object of goal options to be sent with the goal.
*/
function convertQueueDataToGoal(item) {
if (!item.a || !item.o) {
return {};
}
// Make a deep copy of the object data as the goal data will be
// transformed and updated by the API call.
return {
'agentName': item.a,
'options': $.extend(true, {}, item.o)
};
}
/**
* Processes a goal QueueItem through the Acquia Lift service.
*
* @param queueItem
* The item to process.
* @param callback
* A callback function to be used for notification when processing is
* complete. The callback will receive:
* - an instance of the QueueItem processed
* - a boolean indicating if the processing was successful.
*/
function processGoalItem(queueItem, callback) {
var api = Drupal.acquiaLiftAPI.getInstance();
var goal = convertQueueDataToGoal(queueItem.getData());
if (!goal.agentName || !goal.options) {
throw new Error('Invalid goal data.');
}
api.goal(goal.agentName, goal.options, function(accepted, session, retryable) {
if (callback && typeof callback === 'function') {
callback(queueItem, accepted, session, retryable);
}
});
if (api.isManualBatch()) {
api.batchSend();
}
}
return {
/**
* Adds goal data to the persistent queue.
*
* @param agentName
* The name of the agent for the goal.
* @param options
* Goal options to send with the goal.
* @param process
* Boolean indicating if goals should be immediately processed,
* defaults to true.
*/
'addGoal': function (agentName, options, process) {
var data = convertGoalToQueueData({'agentName': agentName, 'options': options});
var process = process == undefined ? true : process;
// Add the data to the persistent queue.
Drupal.acquiaLiftUtility.Queue.add(data);
// Now attempt to process the queue.
if (process) {
this.processQueue();
}
},
/**
* Process the queue by sending goals to the Acquia Lift agent.
*
* @param reset
* (Optional) True if the queue should be reset such that all items are
* tried (such as in an initial processing for the page request).
*/
'processQueue': function (reset) {
reset = reset || false;
// The processing status should be reset upon the initial page load.
if (reset) {
Drupal.acquiaLiftUtility.Queue.reset();
}
var failed = [];
// Function to kick off the processing for the next goal.
function processNext () {
var item = Drupal.acquiaLiftUtility.Queue.getNext();
if (item) {
try {
processGoalItem(item, processComplete);
}
catch (e) {
// If there was an exception, then this goal data cannot be
// processed so remove it and move on.
Drupal.acquiaLiftUtility.Queue.remove(item);
processNext();
}
} else {
// We are all done with processing the queue. Add back in any
// failures to try again the next time the queue is processed.
var i, num = failed.length;
for (i = 0; i < num; i++) {
Drupal.acquiaLiftUtility.Queue.add(failed[i]);
}
}
}
// Callback for when a single goal processing call is complete.
function processComplete (item, accepted, session, retryable) {
if (!accepted && retryable) {
failed.push(item);
} else {
Drupal.acquiaLiftUtility.Queue.remove(item)
}
processNext();
}
// Kick off the queue.
processNext();
}
}
}($));
}(Drupal.jQuery, Drupal));
//# sourceMappingURL=acquia_lift.goals_queue.js.map
|
gpl-2.0
|
Alexandre-T/2666
|
jeuderole/language/fr/common.php
|
47904
|
<?php
/**
*
* common [Standard french]
* translated originally by PhpBB-fr.com <http://www.phpbb-fr.com/> and phpBB.biz <http://www.phpBB.biz>
*
* @package language
* @version $Id: common.php 79 2013-10-01 00:10:32Z Skouat $
* @copyright (c) 2005 phpBB Group
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
// DEVELOPERS PLEASE NOTE
//
// All language files should use UTF-8 as their encoding and the files must not contain a BOM.
//
// Placeholders can now contain order information, e.g. instead of
// 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows
// translators to re-order the output of data while ensuring it remains correct
//
// You do not need this where single placeholders are used, e.g. 'Message %d' is fine
// equally where a string contains only two placeholders which are used to wrap text
// in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine
//
// Some characters you may want to copy&paste:
// ’ « » “ ” …
//
$lang = array_merge($lang, array(
'TRANSLATION_INFO' => 'Traduction par <a href="http://forums.phpbb-fr.com">phpBB-fr.com</a>',
'DIRECTION' => 'ltr',
'DATE_FORMAT' => '|d M Y|', // 01 Jan 2007 (with Relative days enabled)
'USER_LANG' => 'fr',
'1_DAY' => '1 jour',
'1_MONTH' => '1 mois',
'1_YEAR' => '1 an',
'2_WEEKS' => '2 semaines',
'3_MONTHS' => '3 mois',
'6_MONTHS' => '6 mois',
'7_DAYS' => '7 jours',
'ACCOUNT_ALREADY_ACTIVATED' => 'Votre compte est déjà activé.',
'ACCOUNT_DEACTIVATED' => 'Votre compte a été désactivé manuellement et n’est réactivable que par un administrateur.',
'ACCOUNT_NOT_ACTIVATED' => 'Votre compte n’a pas encore été activé.',
'ACP' => 'Panneau d’administration',
'ACTIVE' => 'Actif',
'ACTIVE_ERROR' => 'Le nom d’utilisateur indiqué est actuellement inactif. Si vous avez des problèmes pour activer votre compte, contactez l’administrateur du forum.',
'ADMINISTRATOR' => 'Originel',
'ADMINISTRATORS' => 'Originels',
'AGE' => 'Âge',
'AIM' => 'AIM',
'ALLOWED' => 'Autorisé',
'ALL_FILES' => 'Tous les fichiers',
'ALL_FORUMS' => 'Tous les forums',
'ALL_MESSAGES' => 'Tous les messages',
'ALL_POSTS' => 'Tous',
'ALL_TIMES' => 'Heures au format %1$s %2$s',
'ALL_TOPICS' => 'Tous',
'AND' => 'et',
'ARE_WATCHING_FORUM' => 'Vous surveillez maintenant les nouveaux messages de ce forum.',
'ARE_WATCHING_TOPIC' => 'Vous surveillez maintenant les nouveaux messages de ce sujet.',
'ASCENDING' => 'Croissant',
'ATTACHMENTS' => 'Fichiers joints',
'ATTACHED_IMAGE_NOT_IMAGE' => 'Le fichier image que vous essayez de joindre n’est pas valide.',
'AUTHOR' => 'Auteur',
'AUTH_NO_PROFILE_CREATED' => 'Impossible de créer le nouveau profil de l’utilisateur.',
'AVATAR_DISALLOWED_CONTENT' => 'Le chargement a été rejeté car le fichier chargé a été identifié comme un vecteur éventuel d’attaque.',
'AVATAR_DISALLOWED_EXTENSION' => 'Ce fichier ne peut pas être affiché car l’extension <strong>%s</strong> n’est pas autorisée.',
'AVATAR_EMPTY_REMOTE_DATA' => 'L’avatar indiqué n’a pas pu être chargé car les données distantes semblent être invalides ou corrompues.',
'AVATAR_EMPTY_FILEUPLOAD' => 'Le fichier avatar chargé est vide.',
'AVATAR_INVALID_FILENAME' => '%s est un nom de fichier invalide.',
'AVATAR_NOT_UPLOADED' => 'L’avatar n’a pas pu être chargé.',
'AVATAR_NO_SIZE' => 'Impossible de déterminer la largeur ou la hauteur de l’avatar lié, entrez-les manuellement',
'AVATAR_PARTIAL_UPLOAD' => 'Le fichier n’a pu être que partiellement chargé.',
'AVATAR_PHP_SIZE_NA' => 'La taille de l’avatar est trop importante.<br />La taille maximum réglée dans php.ini n’a pas pu être déterminée.',
'AVATAR_PHP_SIZE_OVERRUN' => 'La taille de l’avatar est trop importante. La taille maximum de chargement autorisée est %1$d %2$s.<br />Notez que ce paramètre est inscrit dans php.ini et ne peut pas être dépassé.',
'AVATAR_URL_INVALID' => 'L’URL indiquée est invalide.',
'AVATAR_URL_NOT_FOUND' => 'Le fichier indiqué est introuvable.',
'AVATAR_WRONG_FILESIZE' => 'La taille de l’avatar doit être comprise entre 0 et %1d %2s.',
'AVATAR_WRONG_SIZE' => 'L’avatar envoyé a une largeur de %5$d pixels et une hauteur de %6$d pixels. Les avatars doivent faire au moins %1$d pixels de large et %2$d pixels de haut, mais au plus %3$d pixels de large et %4$d pixels de haut.',
'BACK_TO_TOP' => 'Haut',
'BACK_TO_PREV' => 'Retour à la page précédente',
'BAN_TRIGGERED_BY_EMAIL'=> 'Votre adresse e-mail a été bannie.',
'BAN_TRIGGERED_BY_IP' => 'Votre adresse IP a été bannie.',
'BAN_TRIGGERED_BY_USER' => 'Votre nom d’utilisateur a été banni.',
'BBCODE_GUIDE' => 'Guide du BBCode',
'BCC' => 'CCI',
'BIRTHDAYS' => 'Anniversaires',
'BOARD_BAN_PERM' => 'Vous avez été banni <strong>définitivement</strong> de ce forum.<br /><br />Contactez l’%2$sAdministrateur du forum%3$s pour plus d’informations.',
'BOARD_BAN_REASON' => 'Raison du bannissement: <strong>%s</strong>',
'BOARD_BAN_TIME' => 'Vous avez été banni de ce forum jusqu’au <strong>%1$s</strong>.<br /><br />Contactez l’%2$sAdministrateur du forum%3$s pour plus d’informations.',
'BOARD_DISABLE' => 'Désolé, mais ce forum est actuellement indisponible.',
'BOARD_DISABLED' => 'Ce forum est actuellement désactivé.',
'BOARD_UNAVAILABLE' => 'Désolé, mais le forum est temporairement indisponible, réessayez dans quelques minutes.',
'BROWSING_FORUM' => 'Utilisateurs parcourant ce forum: %1$s',
'BROWSING_FORUM_GUEST' => 'Utilisateurs parcourant ce forum: %1$s et %2$d invité',
'BROWSING_FORUM_GUESTS' => 'Utilisateurs parcourant ce forum: %1$s et %2$d invités',
'BYTES' => 'Octets',
'CANCEL' => 'Annuler',
'CHANGE' => 'Valider',
'CHANGE_FONT_SIZE' => 'Modifier la taille de la police',
'CHANGING_PREFERENCES' => 'Modifie les préférences du forum',
'CHANGING_PROFILE' => 'Modifie son profil',
'CLICK_VIEW_PRIVMSG' => '%sAller à votre boîte de réception%s',
//MOD AT BEGIN
'CLOSE' => 'Fermer',
//MOD AT END
'COLLAPSE_VIEW' => 'Réduire la vue',
'CLOSE_WINDOW' => 'Fermer la fenêtre',
'COLOUR_SWATCH' => 'Palette de couleurs',
'COMMA_SEPARATOR' => ', ', // Used in pagination of ACP & prosilver, use localised comma if appropriate, eg: Ideographic or Arabic
'CONFIRM' => 'Confirmer',
'CONFIRM_CODE' => 'Code de confirmation',
'CONFIRM_CODE_EXPLAIN' => 'Entrez le code exactement comme vous le voyez dans l’image. Notez que le code n’est pas sensible à la casse.',
'CONFIRM_CODE_WRONG' => 'Le code de confirmation que vous avez entré est incorrect.',
'CONFIRM_OPERATION' => 'Êtes-vous sûr de vouloir effectuer cette opération ?',
'CONGRATULATIONS' => 'Félicitations à',
'CONNECTION_FAILED' => 'La connexion a échouée.',
'CONNECTION_SUCCESS' => 'Vous êtes connecté !',
'COOKIES_DELETED' => 'Tous les cookies du forum ont été supprimés.',
'CURRENT_TIME' => 'Nous sommes le %s',
'DAY' => 'Jour',
'DAYS' => 'jours',
'DELETE' => 'Supprimer',
'DELETE_ALL' => 'Tout supprimer',
'DELETE_COOKIES' => 'Supprimer les cookies du forum',
'DELETE_MARKED' => 'Supprimer la sélection',
'DELETE_POST' => 'Supprimer le message',
'DELIMITER' => 'Séparateur',
'DESCENDING' => 'Décroissant',
'DISABLED' => 'Désactivé',
'DISPLAY' => 'Afficher',
'DISPLAY_GUESTS' => 'Afficher les invités',
'DISPLAY_MESSAGES' => 'Afficher les messages postés depuis',
'DISPLAY_POSTS' => 'Afficher les messages postés depuis',
'DISPLAY_TOPICS' => 'Afficher les sujets postés depuis',
'DOWNLOADED' => 'Téléchargé',
'DOWNLOADING_FILE' => 'Téléchargement en cours',
'DOWNLOAD_COUNT' => 'Téléchargé %d fois',
'DOWNLOAD_COUNTS' => 'Téléchargé %d fois',
'DOWNLOAD_COUNT_NONE' => 'Pas encore téléchargé',
'VIEWED_COUNT' => 'Vu %d fois',
'VIEWED_COUNTS' => 'Vu %d fois',
'VIEWED_COUNT_NONE' => 'Pas encore vu',
'EDIT_POST' => 'Éditer le message',
'EMAIL' => 'E-mail', // Short form for EMAIL_ADDRESS
'EMAIL_ADDRESS' => 'Adresse e-mail',
'EMAIL_INVALID_EMAIL' => 'L’adresse e-mail que vous avez saisie est invalide.',
'EMAIL_SMTP_ERROR_RESPONSE' => 'Un problème est survenu lors de l’envoi de l’e-mail à la <strong>ligne %1$s</strong>. Réponse: %2$s.',
'EMPTY_SUBJECT' => 'Vous devez indiquer un titre pour poster un nouveau sujet.',
'EMPTY_MESSAGE_SUBJECT' => 'Vous devez indiquer un sujet quand vous envoyez un nouveau message.',
'ENABLED' => 'Activé',
'ENCLOSURE' => 'Clôture',
'ENTER_USERNAME' => 'Entrer le nom d’utilisateur',
'ERR_CHANGING_DIRECTORY' => 'Impossible de changer de répertoire.',
'ERR_CONNECTING_SERVER' => 'Erreur de connexion au serveur.',
'ERR_JAB_AUTH' => 'Impossible de s’authentifier sur le serveur Jabber.',
'ERR_JAB_CONNECT' => 'Impossible de se connecter sur le serveur Jabber.',
'ERR_UNABLE_TO_LOGIN' => 'Le nom d’utilisateur ou le mot de passe indiqué est incorrect.',
'ERR_UNWATCHING' => 'Une erreur est survenue pendant la tentative de désinscription.',
'ERR_WATCHING' => 'Une erreur est survenue pendant la tentative d’inscription.',
'ERR_WRONG_PATH_TO_PHPBB' => 'Le chemin phpBB indiqué ne semble pas être valide.',
'EXPAND_VIEW' => 'Étendre la vue',
'EXTENSION' => 'Extension',
'EXTENSION_DISABLED_AFTER_POSTING' => 'L’extension <strong>%s</strong> a été désactivée et ne peut plus être affichée.',
'FAQ' => 'FAQ',
'FAQ_EXPLAIN' => 'Foire aux questions (Questions posées fréquemment)',
'FILENAME' => 'Nom',
'FILESIZE' => 'Taille',
'FILEDATE' => 'Date',
'FILE_COMMENT' => 'Commentaire',
'FILE_NOT_FOUND' => 'Le fichier recherché est introuvable.',
'FIND_USERNAME' => 'Rechercher un membre',
'FOLDER' => 'Dossier',
'FORGOT_PASS' => 'J’ai oublié mon mot de passe',
'FORM_INVALID' => 'Le formulaire envoyé est invalide. Essayez à nouveau.',
'FORUM' => 'Forums',
'FORUMS' => 'Forums',
'FORUMS_MARKED' => 'Les forums ont été marqués comme lus.',
'FORUM_CAT' => 'Catégorie du forum',
'FORUM_INDEX' => 'Index du forum',
'FORUM_LINK' => 'Forum-lien',
'FORUM_LOCATION' => 'Localisation sur le forum',
'FORUM_LOCKED' => 'Forum verrouillé',
'FORUM_RULES' => 'Règles du forum',
'FORUM_RULES_LINK' => 'Cliquez pour voir les règles du forum',
'FROM' => 'de',
'FSOCK_DISABLED' => 'Impossible de finir cette opération car la fonction <var>fsockopen</var> est désactivée ou le serveur requis n’a pas pu être trouvé.',
'FSOCK_TIMEOUT' => 'Le temps d’attente a été dépassé lors de la lecture du flux réseau.',
'FTP_FSOCK_HOST' => 'Serveur FTP',
'FTP_FSOCK_HOST_EXPLAIN' => 'Serveur FTP utilisé pour se connecter à votre site.',
'FTP_FSOCK_PASSWORD' => 'Mot de passe FTP',
'FTP_FSOCK_PASSWORD_EXPLAIN' => 'Mot de passe pour votre compte FTP.',
'FTP_FSOCK_PORT' => 'Port FTP',
'FTP_FSOCK_PORT_EXPLAIN' => 'Port utilisé pour se connecter à votre serveur.',
'FTP_FSOCK_ROOT_PATH' => 'Chemin vers phpBB',
'FTP_FSOCK_ROOT_PATH_EXPLAIN' => 'Chemin depuis la racine vers votre forum phpBB.',
'FTP_FSOCK_TIMEOUT' => 'Temps d’attente FTP',
'FTP_FSOCK_TIMEOUT_EXPLAIN' => 'La durée en secondes que le système attendra pour une réponse de votre serveur.',
'FTP_FSOCK_USERNAME' => 'Nom d’utilisateur FTP',
'FTP_FSOCK_USERNAME_EXPLAIN' => 'Nom d’utilisateur utilisé pour se connecter à votre serveur.',
'FTP_HOST' => 'Serveur FTP',
'FTP_HOST_EXPLAIN' => 'Serveur FTP utilisé pour se connecter à votre site.',
'FTP_PASSWORD' => 'Mot de passe FTP',
'FTP_PASSWORD_EXPLAIN' => 'Mot de passe pour votre compte FTP.',
'FTP_PORT' => 'Port FTP',
'FTP_PORT_EXPLAIN' => 'Port utilisé pour se connecter à votre serveur.',
'FTP_ROOT_PATH' => 'Chemin vers phpBB',
'FTP_ROOT_PATH_EXPLAIN' => 'Chemin depuis la racine vers votre forum phpBB.',
'FTP_TIMEOUT' => 'Temps d’attente FTP',
'FTP_TIMEOUT_EXPLAIN' => 'La durée en secondes que le système attendra pour une réponse de votre serveur.',
'FTP_USERNAME' => 'Nom d’utilisateur FTP',
'FTP_USERNAME_EXPLAIN' => 'Nom d’utilisateur utilisé pour se connecter à votre serveur.',
'GENERAL_ERROR' => 'Erreur générale',
'GB' => 'Go',
'GIB' => 'Gio',
'GO' => 'Aller',
'GOTO_PAGE' => 'Aller à la page',
'GROUP' => 'Groupe',
'GROUPS' => 'Groupes',
'GROUP_ERR_TYPE' => 'Le type de groupe indiqué est inapproprié.',
'GROUP_ERR_USERNAME' => 'Aucun nom de groupe indiqué.',
'GROUP_ERR_USER_LONG' => 'Les noms de groupe ne peuvent pas dépasser 60 caractères. Le nom du groupe indiqué est trop long.',
'GUEST' => 'Invité',
'GUEST_USERS_ONLINE' => 'Il y a %d invités en ligne',
'GUEST_USERS_TOTAL' => '%d invités',
'GUEST_USERS_ZERO_ONLINE' => '0 invité en ligne',
'GUEST_USERS_ZERO_TOTAL' => '0 invité',
'GUEST_USER_ONLINE' => 'Il y a %d invité en ligne',
'GUEST_USER_TOTAL' => '%d invité',
'G_ADMINISTRATORS' => 'Originels (Administrateurs)',
'G_BOTS' => 'Robots',
'G_GUESTS' => 'Invités',
'G_REGISTERED' => 'Utilisateurs enregistrés',
'G_REGISTERED_COPPA' => 'Utilisateurs COPPA enregistrés',
'G_GLOBAL_MODERATORS' => 'Modérateurs globaux',
'G_NEWLY_REGISTERED' => 'Nouveaux utilisateurs enregistrés',
'HIDDEN_USERS_ONLINE' => '%d utilisateurs invisibles en ligne',
'HIDDEN_USERS_TOTAL' => '%d invisibles',
'HIDDEN_USERS_TOTAL_AND' => '%d invisibles et ',
'HIDDEN_USERS_ZERO_ONLINE' => '0 utilisateur invisible en ligne',
'HIDDEN_USERS_ZERO_TOTAL' => '0 invisible',
'HIDDEN_USERS_ZERO_TOTAL_AND' => '0 invisible et ',
'HIDDEN_USER_ONLINE' => '%d utilisateur invisible en ligne',
'HIDDEN_USER_TOTAL' => '%d invisible',
'HIDDEN_USER_TOTAL_AND' => '%d invisible et ',
'HIDE_GUESTS' => 'Masquer les invités',
'HIDE_ME' => 'Cacher mon statut en ligne pour cette session',
//MOD AT BEGIN
'HISTOIRE' => 'Histoire',
//MOD AT END
'HOURS' => 'Heures',
'HOME' => 'Accueil',
'ICQ' => 'ICQ',
'ICQ_STATUS' => 'Statut ICQ',
'IF' => 'Si',
'IMAGE' => 'Image',
'IMAGE_FILETYPE_INVALID' => 'Le type de fichier image %d pour le type mime %s n’est pas supporté.',
'IMAGE_FILETYPE_MISMATCH' => 'Type de fichier image incorrect: l’extension %1$s était attendue mais l’extension %2$s a été trouvée.',
'IN' => 'dans',
'INDEX' => 'Page d’index',
'INFORMATION' => 'Informations',
'INTERESTS' => 'Centres d’intérêt',
'INVALID_DIGEST_CHALLENGE' => 'Défi invalide.',
'INVALID_EMAIL_LOG' => '<strong>%s</strong> est peut-être une adresse invalide ?',
'IP' => 'IP',
'IP_BLACKLISTED' => 'Votre IP %1$s a été bloquée car elle est dans la liste noire. Pour plus d’informations, consultez <a href="%2$s">%2$s</a>.',
'JABBER' => 'Jabber',
'JOINED' => 'Inscription',
'JUMP_PAGE' => 'Entrer le numéro de page où vous souhaitez aller.',
'JUMP_TO' => 'Aller à',
'JUMP_TO_PAGE' => 'Cliquer pour aller à la page…',
'KB' => 'Ko',
'KIB' => 'Kio',
'LAST_POST' => 'Dernier message',
'LAST_UPDATED' => 'Dernière mise à jour',
'LAST_VISIT' => 'Dernière visite',
'LDAP_NO_LDAP_EXTENSION' => 'Extension LDAP indisponible.',
'LDAP_NO_SERVER_CONNECTION' => 'Impossible de se connecter au serveur LDAP.',
'LDAP_SEARCH_FAILED' => 'Une erreur est survenue pendant la recherche du répertoire LDAP.',
'LEGEND' => 'Légende',
'LOCATION' => 'Localisation',
'LOCK_POST' => 'Verrouiller le message',
'LOCK_POST_EXPLAIN' => 'Empêche l’édition du message',
'LOCK_TOPIC' => 'Verrouiller le sujet',
'LOGIN' => 'Connexion',
'LOGIN_CHECK_PM' => 'Se connecter pour vérifier ses messages privés.',
'LOGIN_CONFIRMATION' => 'Confirmation de connexion',
'LOGIN_CONFIRM_EXPLAIN' => 'Pour éviter une usurpation des comptes, l’administrateur du forum exige que vous entriez un code de confirmation visuelle après un certain nombre d’échecs. Le code est indiqué dans l’image que vous devez voir ci-dessous. Si vous êtes déficient visuel ou que vous ne pouvez pas lire ce code, contactez %sl’administrateur%s du forum.', // unused
'LOGIN_ERROR_ATTEMPTS' => 'Vous avez dépassé le maximum autorisé de tentatives de connexion. En plus de vos nom d’utilisateur et mot de passe, vous devez maintenant résoudre le CAPTCHA ci-dessous.',
'LOGIN_ERROR_EXTERNAL_AUTH_APACHE' => 'Vous n’avez pas été authentifié par Apache.',
'LOGIN_ERROR_PASSWORD' => 'Vous avez indiqué un mot de passe incorrect. Vérifiez votre mot de passe et réessayez. Si vous continuez à rencontrer des problèmes, contactez l’%sadministrateur du forum%s.',
'LOGIN_ERROR_PASSWORD_CONVERT' => 'Il n’a pas été possible de convertir votre mot de passe lors de la mise à jour du forum. %sRedemandez un mot de passe%s. Si le problème persiste, contactez l’%sadministrateur du forum%s.',
'LOGIN_ERROR_USERNAME' => 'Vous avez indiqué un nom d’utilisateur incorrect. Vérifiez votre nom d’utilisateur et réessayez. Si vous continuez à rencontrer des problèmes, contactez l’%sadministrateur du forum%s.',
'LOGIN_FORUM' => 'Pour lire ou poster dans ce forum, vous devez entrer son mot de passe.',
'LOGIN_INFO' => 'Vous devez être enregistré pour vous connecter. L’enregistrement ne prend que quelques secondes et augmente vos possibilités. L’administrateur du forum peut également accorder des permissions additionnelles aux utilisateurs enregistrés. Avant de vous enregistrer, assurez-vous d’avoir pris connaissance de nos conditions d’utilisation et de notre politique de vie privée. Assurez-vous de bien lire tout le règlement du forum.',
'LOGIN_VIEWFORUM' => 'L’administrateur du forum exige que vous soyez enregistré et connecté pour lire ce forum.',
'LOGIN_EXPLAIN_EDIT' => 'Pour éditer des messages dans ce forum, vous devez être enregistré et connecté.',
'LOGIN_EXPLAIN_VIEWONLINE' => 'Pour consulter la liste des utilisateurs en ligne, vous devez être enregistré et connecté.',
'LOGOUT' => 'Déconnexion',
'LOGOUT_USER' => 'Déconnexion [ %s ]',
'LOG_ME_IN' => 'Me connecter automatiquement à chaque visite',
'MARK' => 'Cocher',
'MARK_ALL' => 'Tout cocher',
'MARK_FORUMS_READ' => 'Marquer tous les forums comme lus',
'MARK_SUBFORUMS_READ' => 'Marquer tous les sous-forums comme lus',
'MB' => 'Mo',
'MIB' => 'Mio',
'MCP' => 'Panneau de modération',
'MEMBERLIST' => 'Membres',
'MEMBERLIST_EXPLAIN' => 'Voir la liste complète des membres',
'MERGE' => 'Fusionner',
'MERGE_POSTS' => 'Déplacer les messages',
'MERGE_TOPIC' => 'Fusionner le sujet',
'MESSAGE' => 'Message',
'MESSAGES' => 'Messages',
'MESSAGE_BODY' => 'Corps du message',
'MINUTES' => 'Minutes',
'MODERATE' => 'Modérer',
'MODERATOR' => 'Modérateur',
'MODERATORS' => 'Modérateurs',
'MONTH' => 'Mois',
'MOVE' => 'Déplacer',
'MSNM' => 'WLM',
'NA' => 'N/A',
'NEWEST_USER' => 'L’utilisateur enregistré le plus récent est <strong>%s</strong>',
'NEW_MESSAGE' => 'Nouveau message',
'NEW_MESSAGES' => 'Nouveaux messages',
'NEW_PM' => '<strong>%d</strong> nouveau message privé',
'NEW_PMS' => '<strong>%d</strong> nouveaux messages privés',
'NEW_POST' => 'Nouveau message', // Not used anymore
'NEW_POSTS' => 'Nouveaux messages', // Not used anymore
'NEXT' => 'Suivante', // Used in pagination
'NEXT_STEP' => 'Suivant',
'NEVER' => 'Jamais',
'NO' => 'Non',
'NOT_ALLOWED_MANAGE_GROUP' => 'Vous n’êtes pas autorisé à gérer ce groupe.',
'NOT_AUTHORISED' => 'Vous n’êtes pas autorisé à accéder à cette partie du forum.',
'NOT_WATCHING_FORUM' => 'Vous ne surveillez plus ce forum.',
'NOT_WATCHING_TOPIC' => 'Vous ne surveillez plus ce sujet.',
'NOTIFY_ADMIN' => 'Contactez l’administrateur du forum ou le webmaster.',
'NOTIFY_ADMIN_EMAIL' => 'Contactez l’administrateur du forum ou le webmaster: <a href="mailto:%1$s">%1$s</a>',
'NO_ACCESS_ATTACHMENT' => 'Vous n’êtes pas autorisé à accéder à ce fichier.',
'NO_ACTION' => 'Aucune action indiquée.',
'NO_ADMINISTRATORS' => 'Il n’existe aucun administrateur.',
'NO_AUTH_ADMIN' => 'Vous n’avez pas les permissions d’administration et ne pouvez donc pas accéder au panneau d’administration.',
'NO_AUTH_ADMIN_USER_DIFFER' => 'Vous ne pouvez pas vous ré-authentifier avec un compte différent.',
'NO_AUTH_OPERATION' => 'Vous n’avez pas les permissions nécessaires pour accomplir cette opération.',
'NO_CONNECT_TO_SMTP_HOST' => 'Impossible de se connecter au serveur smtp : %1$s : %2$s',
'NO_BIRTHDAYS' => 'Pas d’anniversaire à fêter aujourd’hui',
'NO_EMAIL_MESSAGE' => 'Le contenu de cet e-mail est vide.',
'NO_EMAIL_RESPONSE_CODE' => 'Impossible de récupérer les codes de réponse du serveur.',
'NO_EMAIL_SUBJECT' => 'Aucun sujet n’a été indiqué.',
'NO_FORUM' => 'Le forum que vous avez tenté d’atteindre n’existe pas.',
'NO_FORUMS' => 'Aucun forum.',
'NO_GROUP' => 'Le groupe demandé n’existe pas.',
'NO_GROUP_MEMBERS' => 'Aucun membre dans ce groupe.',
'NO_IPS_DEFINED' => 'Aucune IP ou nom d’hôte',
'NO_MEMBERS' => 'Aucun membre trouvé pour ce critère de recherche.',
'NO_MESSAGES' => 'Pas de message',
'NO_MODE' => 'Pas de mode indiqué.',
'NO_MODERATORS' => 'Il n’existe aucun modérateur.',
'NO_NEW_MESSAGES' => 'Pas de nouveau message',
'NO_NEW_PM' => '<strong>0</strong> nouveau message privé',
'NO_NEW_POSTS' => 'Pas de nouveau message', // Not used anymore
'NO_ONLINE_USERS' => 'Aucun utilisateur enregistré',
'NO_POSTS' => 'Pas de message',
'NO_POSTS_TIME_FRAME' => 'Aucun message n’a été posté dans ce sujet pour la période indiquée.',
'NO_FEED_ENABLED' => 'Les flux ne sont pas disponibles sur ce forum.',
'NO_FEED' => 'Le flux demandé n’est pas disponible.',
'NO_STYLE_DATA' => 'Impossible de récupérer les données de style',
'NO_SUBJECT' => 'Aucun sujet indiqué', // Used for posts having no subject defined but displayed within management pages.
'NO_SUCH_SEARCH_MODULE' => 'La recherche indiquée n’existe pas.',
'NO_SUPPORTED_AUTH_METHODS' => 'Aucune méthode d’authentification supportée.',
'NO_TOPIC' => 'Le sujet demandé n’existe pas.',
'NO_TOPIC_FORUM' => 'Le sujet ou le forum n’existe plus.',
'NO_TOPICS' => 'Il n’y a aucun sujet ou message dans ce forum.',
'NO_TOPICS_TIME_FRAME' => 'Aucun sujet n’a été posté dans ce forum pour la période indiquée.',
'NO_UNREAD_PM' => '<strong>0</strong> message non lu',
'NO_UNREAD_POSTS' => 'Aucun message non lu',
'NO_UPLOAD_FORM_FOUND' => 'Le chargement a commencé mais aucun fichier valide n’a été trouvé.',
'NO_USER' => 'L’utilisateur demandé n’existe pas.',
'NO_USERS' => 'Les utilisateurs demandés n’existent pas.',
'NO_USER_SPECIFIED' => 'Aucun nom d’utilisateur indiqué.',
// Nullar/Singular/Plural language entry. The key numbers define the number range in which a certain grammatical expression is valid.
'NUM_POSTS_IN_QUEUE' => array(
0 => 'Aucun message en attente', // 0
1 => '1 message en attente', // 1
2 => '%d messages en attente', // 2+
),
'OCCUPATION' => 'Emploi',
'OFFLINE' => 'Hors ligne',
'ONLINE' => 'En ligne',
'ONLINE_BUDDIES' => 'Amis en ligne',
'ONLINE_USERS_TOTAL' => 'Au total il y a <strong>%d</strong> utilisateurs en ligne :: ',
'ONLINE_USERS_ZERO_TOTAL' => 'Au total il y a <strong>0</strong> utilisateur en ligne :: ',
'ONLINE_USER_TOTAL' => 'Au total il y a <strong>%d</strong> utilisateur en ligne :: ',
'OPTIONS' => 'Options',
'PAGE_OF' => 'Page <strong>%1$d</strong> sur <strong>%2$d</strong>',
'PASSWORD' => 'Mot de passe',
'PIXEL' => 'px',
'PLAY_QUICKTIME_FILE' => 'Jouer le fichier Quicktime',
'PM' => 'MP',
'PM_REPORTED' => 'Cliquer pour voir le rapport',
'POSTING_MESSAGE' => 'Poste un message dans %s',
'POSTING_PRIVATE_MESSAGE' => 'Rédige un message privé',
'POST' => 'Message',
'POST_ANNOUNCEMENT' => 'Annonce',
'POST_STICKY' => 'Post-it',
'POSTED' => 'Posté',
'POSTED_IN_FORUM' => 'Dans',
'POSTED_ON_DATE' => 'le',
'POSTS' => 'Messages',
'POSTS_UNAPPROVED' => 'Au moins un message de ce sujet n’a pas été approuvé.',
'POST_BY_AUTHOR' => 'par',
'POST_BY_FOE' => 'Ce message a été rédigé par <strong>%1$s</strong> qui est actuellement sur votre liste de membres ignorés. %2$sAfficher le message%3$s.',
'POST_DAY' => '%.2f messages par jour',
'POST_DETAILS' => 'Détails',
'POST_NEW_TOPIC' => 'Poster un nouveau sujet',
'POST_PCT' => '%.2f%% de tous les messages',
'POST_PCT_ACTIVE' => '%.2f%% des messages de l’utilisateur',
'POST_PCT_ACTIVE_OWN' => '%.2f%% de vos messages',
'POST_REPLY' => 'Répondre',
'POST_REPORTED' => 'Cliquer pour voir le rapport',
'POST_SUBJECT' => 'Sujet du message',
'POST_TIME' => 'Date',
'POST_TOPIC' => 'Écrire un nouveau sujet',
'POST_UNAPPROVED' => 'Ce message est en attente d’approbation',
'POWERED_BY' => 'Développé par %s',
'PREVIEW' => 'Aperçu',
'PREVIOUS' => 'Précédente', // Used in pagination
'PREVIOUS_STEP' => 'Précédente',
'PRIVACY' => 'Politique de vie privée',
'PRIVATE_MESSAGE' => 'Message privé',
'PRIVATE_MESSAGES' => 'Messages privés',
'PRIVATE_MESSAGING' => 'Messagerie privée',
'PROFILE' => 'Panneau de l’utilisateur',
'RANK' => 'Rang',
'READING_FORUM' => 'Consulte les sujets dans %s',
'READING_GLOBAL_ANNOUNCE' => 'Consulte une annonce globale',
'READING_LINK' => 'Consulte le lien du forum %s',
'READING_TOPIC' => 'Consulte un sujet dans %s',
'READ_PROFILE' => 'Profil',
'REASON' => 'Raison',
'RECORD_ONLINE_USERS' => 'Le record du nombre d’utilisateurs en ligne est de <strong>%1$s</strong>, le %2$s',
'REDIRECT' => 'Rediriger',
'REDIRECTS' => 'Nombre de redirections',
'REGISTER' => 'M’enregistrer',
'REGISTERED_USERS' => 'Utilisateurs enregistrés:',
'REG_USERS_ONLINE' => 'Il y a %d utilisateurs enregistrés et ',
'REG_USERS_TOTAL' => '%d enregistrés, ',
'REG_USERS_TOTAL_AND' => '%d enregistrés et ',
'REG_USERS_ZERO_ONLINE' => 'Il y a 0 utilisateur enregistré et ',
'REG_USERS_ZERO_TOTAL' => '0 enregistré, ',
'REG_USERS_ZERO_TOTAL_AND' => '0 enregistré et ',
'REG_USER_ONLINE' => 'Il y a %d utilisateur enregistré et ',
'REG_USER_TOTAL' => '%d enregistré, ',
'REG_USER_TOTAL_AND' => '%d enregistré et ',
'REMOVE' => 'Supprimer',
'REMOVE_INSTALL' => 'Pour finaliser l’installation du forum, supprimez, déplacez ou renommez le dossier install de votre espace FTP. Si ce dossier est toujours présent, seul le panneau d’administration (ACP) sera accessible.',
'REPLIES' => 'Réponses',
'REPLY_WITH_QUOTE' => 'Répondre en citant le message',
'REPLYING_GLOBAL_ANNOUNCE' => 'Répond à une annonce globale',
'REPLYING_MESSAGE' => 'Répond à un message dans %s',
'REPORT_BY' => 'Rapporté par',
'REPORT_POST' => 'Rapporter le message',
'REPORTING_POST' => 'Rapporter un message',
'RESEND_ACTIVATION' => 'Renvoyer l’e-mail de confirmation',
'RESET' => 'Réinitialiser',
'RESTORE_PERMISSIONS' => 'Rétablir les permissions',
//MOD AT BEGIN
'RESUME' => 'Résumé',
//MOD AT END
'RETURN_INDEX' => '%sRetourner à l’index du forum%s',
'RETURN_FORUM' => '%sRetourner au dernier forum visité%s',
'RETURN_PAGE' => '%sRetourner à la page précédente%s',
'RETURN_TOPIC' => '%sRetourner au dernier sujet visité%s',
'RETURN_TO' => 'Retourner vers',
'FEED' => 'Flux',
'FEED_NEWS' => 'Nouvelles informations',
'FEED_TOPICS_ACTIVE' => 'Sujets actifs',
'FEED_TOPICS_NEW' => 'Nouveaux sujets',
//MOD AT BEGIN
'RP_EN_COURS' => 'RP en cours',
'RP_ARCHIVE' => 'RP terminés',
//MOD AT END
'RULES_ATTACH_CAN' => 'Vous <strong>pouvez</strong> joindre des fichiers',
'RULES_ATTACH_CANNOT' => 'Vous <strong>ne pouvez pas</strong> joindre des fichiers',
'RULES_DELETE_CAN' => 'Vous <strong>pouvez</strong> supprimer vos messages',
'RULES_DELETE_CANNOT' => 'Vous <strong>ne pouvez pas</strong> supprimer vos messages',
'RULES_DOWNLOAD_CAN' => 'Vous <strong>pouvez</strong> télécharger des fichiers joints',
'RULES_DOWNLOAD_CANNOT' => 'Vous <strong>ne pouvez pas</strong> télécharger des fichiers joints',
'RULES_EDIT_CAN' => 'Vous <strong>pouvez</strong> éditer vos messages',
'RULES_EDIT_CANNOT' => 'Vous <strong>ne pouvez pas</strong> éditer vos messages',
'RULES_LOCK_CAN' => 'Vous <strong>pouvez</strong> verrouiller vos sujets',
'RULES_LOCK_CANNOT' => 'Vous <strong>ne pouvez pas</strong> verrouiller vos sujets',
'RULES_POST_CAN' => 'Vous <strong>pouvez</strong> poster de nouveaux sujets',
'RULES_POST_CANNOT' => 'Vous <strong>ne pouvez pas</strong> poster de nouveaux sujets',
'RULES_REPLY_CAN' => 'Vous <strong>pouvez</strong> répondre aux sujets',
'RULES_REPLY_CANNOT' => 'Vous <strong>ne pouvez pas</strong> répondre aux sujets',
'RULES_VOTE_CAN' => 'Vous <strong>pouvez</strong> participer aux votes',
'RULES_VOTE_CANNOT' => 'Vous <strong>ne pouvez pas</strong> participer aux votes',
'SEARCH' => 'Rechercher',
'SEARCH_MINI' => 'Recherche…',
'SEARCH_ADV' => 'Recherche avancée',
'SEARCH_ADV_EXPLAIN' => 'Voir les options de recherche avancée',
'SEARCH_KEYWORDS' => 'Recherche par mots-clés',
'SEARCHING_FORUMS' => 'Recherche dans les forums',
'SEARCH_ACTIVE_TOPICS' => 'Voir les sujets actifs',
'SEARCH_FOR' => 'Rechercher',
'SEARCH_FORUM' => 'Dans ce forum…',
'SEARCH_NEW' => 'Voir les nouveaux messages',
//MOD AT BEGIN
'SEARCH_RP' => 'Voir mes RPs',
//MOD AT END
'SEARCH_POSTS_BY' => 'Rechercher les messages de',
'SEARCH_SELF' => 'Voir mes messages',
'SEARCH_TOPIC' => 'Dans ce sujet…',
'SEARCH_UNANSWERED' => 'Voir les messages sans réponses',
'SEARCH_UNREAD' => 'Voir les messages non lus',
'SEARCH_USER_POSTS' => 'Rechercher les messages de l’utilisateur',
//MOD AT BEGIN
'SEARCH_USER_RP' => 'Voir ses RPs en cours',
'SEARCH_USER_RPA' => 'Voir ses RPs terminés',
'SEARCH_USER_RP_ARCHIVE' => 'Rechercher les RPs archivés de ce personnage',
'SEARCH_USER_RP_EN_COURS' => 'Rechercher les RPs en cours de ce personnage',
'SEARCH_USER_RP_ARCHIVE' => 'Rechercher les RPs archivés de ce personnage',
//MOD AT END
'SECONDS' => 'secondes',
'SELECT' => 'Sélectionner',
'SELECT_ALL_CODE' => 'Tout sélectionner',
'SELECT_DESTINATION_FORUM' => 'Choisissez un forum de destination',
'SELECT_FORUM' => 'Sélectionner un forum',
'SEND_EMAIL' => 'Envoyer un e-mail', // Used for submit buttons
'SEND_EMAIL_USER' => 'Envoyer un e-mail à', // Used as: {L_SEND_EMAIL_USER} {USERNAME} -> E-mail UserX
'SEND_PRIVATE_MESSAGE' => 'Envoyer un message privé',
'SETTINGS' => 'Paramètres',
'SIGNATURE' => 'Signature',
'SKIP' => 'Vers le contenu',
'SMTP_NO_AUTH_SUPPORT' => 'Le serveur SMTP ne peut pas vous identifier.',
'SORRY_AUTH_READ' => 'Vous n’êtes pas autorisé à lire ce forum.',
'SORRY_AUTH_VIEW_ATTACH' => 'Vous n’êtes pas autorisé à télécharger ce fichier joint.',
'SORT_BY' => 'Trier par',
'SORT_JOINED' => 'Date d’inscription',
'SORT_LOCATION' => 'Localisation',
'SORT_RANK' => 'Rang',
'SORT_POSTS' => 'Messages',
'SORT_TOPIC_TITLE' => 'Titre du sujet',
'SORT_USERNAME' => 'Nom d’utilisateur',
'SPLIT_TOPIC' => 'Diviser le sujet',
'SQL_ERROR_OCCURRED' => 'Une erreur SQL est arrivée en chargeant cette page. Contactez l’%sadministrateur du forum%s si ce problème persiste.',
'STATISTICS' => 'Statistiques',
'START_WATCHING_FORUM' => 'Surveiller ce forum',
'START_WATCHING_TOPIC' => 'Surveiller ce sujet',
'STOP_WATCHING_FORUM' => 'Arrêter de surveiller ce forum',
'STOP_WATCHING_TOPIC' => 'Arrêter de surveiller ce sujet',
'SUBFORUM' => 'Sous-forum',
'SUBFORUMS' => 'Sous-forums',
'SUBJECT' => 'Sujet',
'SUBMIT' => 'Envoyer',
'TB' => 'To', // téraoctet
'TERMS_USE' => 'Conditions d’utilisation',
'TEST_CONNECTION' => 'Test de connexion',
'THE_TEAM' => 'L’équipe du forum',
'TIB' => 'Tio', // tébioctect
'TIME' => 'Date',
'TOO_LARGE' => 'La valeur saisie est trop grande.',
'TOO_LARGE_MAX_RECIPIENTS' => 'La valeur du réglage <strong>Nombre maximum autorisé de destinataires par message privé</strong> que vous avez saisie est trop grande.',
'TOO_LONG' => 'La valeur saisie est trop longue.',
'TOO_LONG_AIM' => 'Le pseudonyme AIM indiqué est trop long.',
'TOO_LONG_CONFIRM_CODE' => 'Le code de confirmation indiqué est trop long.',
'TOO_LONG_DATEFORMAT' => 'Le format de la date indiquée est trop long.',
'TOO_LONG_ICQ' => 'Le numéro ICQ indiqué est trop long.',
'TOO_LONG_INTERESTS' => 'Les centres d’intérêts indiqués sont trop longs.',
'TOO_LONG_JABBER' => 'Le nom de compte Jabber indiqué est trop long.',
'TOO_LONG_LOCATION' => 'La localisation indiquée est trop longue.',
'TOO_LONG_MSN' => 'Le compte WLM indiqué est trop long.',
'TOO_LONG_NEW_PASSWORD' => 'Le mot de passe indiqué est trop long.',
'TOO_LONG_OCCUPATION' => 'Les loisirs indiqués sont trop longs.',
'TOO_LONG_PASSWORD_CONFIRM' => 'Le mot de passe de confirmation indiqué est trop long.',
'TOO_LONG_USER_PASSWORD' => 'Le mot de passe indiqué est trop long.',
'TOO_LONG_USERNAME' => 'Le nom d’utilisateur indiqué est trop long.',
'TOO_LONG_EMAIL' => 'L’adresse e-mail indiquée est trop longue.',
'TOO_LONG_EMAIL_CONFIRM' => 'L’adresse e-mail de confirmation indiquée est trop longue.',
'TOO_LONG_WEBSITE' => 'L’adresse du site Internet indiquée est trop longue.',
'TOO_LONG_YIM' => 'Le nom Yahoo! Messenger indiqué est trop long.',
'TOO_MANY_VOTE_OPTIONS' => 'Vous avez sélectionné trop d’options de vote.',
'TOO_SHORT' => 'La valeur saisie est trop courte.',
'TOO_SHORT_AIM' => 'Le pseudonyme AIM indiqué est trop court.',
'TOO_SHORT_CONFIRM_CODE' => 'Le code de confirmation indiqué est trop court.',
'TOO_SHORT_DATEFORMAT' => 'Le format de la date indiquée est trop courte.',
'TOO_SHORT_ICQ' => 'Le numéro ICQ indiqué est trop court.',
'TOO_SHORT_INTERESTS' => 'Les centres d’intérêts indiqués sont trop courts.',
'TOO_SHORT_JABBER' => 'Le nom de compte Jabber indiqué est trop court.',
'TOO_SHORT_LOCATION' => 'La localisation indiquée est trop courte.',
'TOO_SHORT_MSN' => 'Le compte WLM indiqué est trop court.',
'TOO_SHORT_NEW_PASSWORD' => 'Le mot de passe indiqué est trop court.',
'TOO_SHORT_OCCUPATION' => 'Les loisirs indiqués sont trop courts.',
'TOO_SHORT_PASSWORD_CONFIRM' => 'Le mot de passe de confirmation indiqué est trop court.',
'TOO_SHORT_USER_PASSWORD' => 'Le mot de passe indiqué est trop court.',
'TOO_SHORT_USERNAME' => 'Le nom d’utilisateur indiqué est trop court.',
'TOO_SHORT_EMAIL' => 'L’adresse e-mail indiquée est trop courte.',
'TOO_SHORT_EMAIL_CONFIRM' => 'L’adresse e-mail de confirmation indiquée est trop courte.',
'TOO_SHORT_WEBSITE' => 'L’adresse du site Internet indiquée est trop courte.',
'TOO_SHORT_YIM' => 'Le nom Yahoo! Messenger indiqué est trop court.',
'TOO_SMALL' => 'La valeur saisie est trop petite.',
'TOO_SMALL_MAX_RECIPIENTS' => 'La valeur du réglage <strong>Nombre maximum autorisé de destinataires par message privé</strong> que vous avez saisie est trop petite.',
'TOPIC' => 'Sujet',
'TOPICS' => 'Sujets',
'TOPICS_UNAPPROVED' => 'Au moins un sujet dans ce forum n’est pas approuvé.',
'TOPIC_ICON' => 'Icône de sujet',
'TOPIC_LOCKED' => 'Ce sujet est verrouillé, vous ne pouvez pas éditer de messages ou poster d’autres réponses.',
'TOPIC_LOCKED_SHORT'=> 'Sujet verrouillé',
'TOPIC_MOVED' => 'Sujet déplacé',
'TOPIC_REVIEW' => 'Revue du sujet',
'TOPIC_TITLE' => 'Titre du sujet',
'TOPIC_UNAPPROVED' => 'Ce sujet n’a pas été approuvé',
'TOTAL_ATTACHMENTS' => 'Fichier(s) joint(s)',
'TOTAL_LOG' => '1 entrée',
'TOTAL_LOGS' => '%d entrées',
'TOTAL_NO_PM' => '0 message privé',
'TOTAL_PERSONNAGES_ZERO' => '<strong>0</strong> survivant',
'TOTAL_PERSONNAGES_OTHER' => '<strong>%d</strong> survivants',
'TOTAL_PM' => '1 message privé',
'TOTAL_PMS' => '%d messages privés',
'TOTAL_POSTS' => 'Messages',
'TOTAL_POSTS_OTHER' => '<strong>%d</strong> messages',
'TOTAL_POSTS_ZERO' => '<strong>0</strong> message',
'TOPIC_REPORTED' => 'Ce sujet a été rapporté',
'TOTAL_TOPICS_OTHER'=> '<strong>%d</strong> sujets',
'TOTAL_TOPICS_ZERO' => '<strong>0</strong> sujet',
'TOTAL_USERS_OTHER' => '<strong>%d</strong> membres',
'TOTAL_USERS_ZERO' => '<strong>0</strong> membre',
'TRACKED_PHP_ERROR' => 'Suivi des erreurs PHP: %s',
'UNABLE_GET_IMAGE_SIZE' => 'Impossible de déterminer les dimensions de l’image.',
'UNABLE_TO_DELIVER_FILE'=> 'Impossible de charger l’image.',
'UNKNOWN_BROWSER' => 'Navigateur inconnu',
'UNMARK_ALL' => 'Tout décocher',
'UNREAD_MESSAGES' => 'Messages non lus',
'UNREAD_PM' => '<strong>%d</strong> message non lu',
'UNREAD_PMS' => '<strong>%d</strong> messages non lus',
'UNREAD_POST' => 'Message non lu',
'UNREAD_POSTS' => 'Messages non lus',
'UNWATCH_FORUM_CONFIRM' => 'Êtes-vous sûr de ne plus vouloir surveiller ce forum ?',
'UNWATCH_FORUM_DETAILED' => 'Êtes-vous sûr de ne plus vouloir surveiller le forum « %s » ?',
'UNWATCH_TOPIC_CONFIRM' => 'Êtes-vous sûr de ne plus vouloir surveiller ce sujet ?',
'UNWATCH_TOPIC_DETAILED' => 'Êtes-vous sûr de ne plus vouloir surveiller le sujet « %s » ?',
'UNWATCHED_FORUMS' => 'Vous ne surveillez plus les forums sélectionnés.',
'UNWATCHED_TOPICS' => 'Vous ne surveillez plus les sujets sélectionnés.',
'UNWATCHED_FORUMS_TOPICS' => 'Vous ne surveillez plus les entrées sélectionnées.',
'UPDATE' => 'Mise à jour',
'UPLOAD_IN_PROGRESS' => 'Le chargement est actuellement en cours.',
'URL_REDIRECT' => 'Si votre navigateur ne vous redirige pas automatiquement dans quelques instants, %scliquez ici pour être redirigé%s.',
'USERGROUPS' => 'Groupes d’utilisateurs',
'USERNAME' => 'Nom d’utilisateur',
'USERNAMES' => 'Noms des utilisateurs',
'USER_AVATAR' => 'Avatar de l’utilisateur',
'USER_CANNOT_READ' => 'Vous ne pouvez pas lire les messages de ce forum.',
'USER_POST' => '%d Message',
'USER_POSTS' => '%d Messages',
'USERS' => 'Utilisateurs',
'USE_PERMISSIONS' => 'Tester les permissions de l’utilisateur',
'USER_NEW_PERMISSION_DISALLOWED' => 'Nous sommes désolés, mais vous n’êtes pas autorisé à utiliser cette fonctionnalité. Vous venez juste de vous inscrire, et il vous est nécessaire de participer plus pour utiliser cette fonctionnalité.',
'VARIANT_DATE_SEPARATOR' => ' / ', // Used in date format dropdown, eg: "Today, 13:37 / 01 Jan 2007, 13:37" ... to join a relative date with calendar date
'VIEWED' => 'Vu',
'VIEWING_FAQ' => 'Consulte la FAQ',
'VIEWING_MEMBERS' => 'Consulte les informations d’un utilisateur',
'VIEWING_ONLINE' => 'Regarde qui est en ligne',
'VIEWING_MCP' => 'Consulte le panneau de modération',
'VIEWING_MEMBER_PROFILE' => 'Consulte le profil d’un utilisateur',
'VIEWING_PRIVATE_MESSAGES' => 'Lit ses messages privés',
'VIEWING_REGISTER' => 'S’enregistre',
'VIEWING_UCP' => 'Consulte son panneau de l’utilisateur',
'VIEWS' => 'Vus',
'VIEW_BOOKMARKS' => 'Afficher les favoris',
'VIEW_FORUM_LOGS' => 'Afficher le journal',
'VIEW_LATEST_POST' => 'Voir le dernier message',
'VIEW_NEWEST_POST' => 'Voir le premier message non lu',
'VIEW_NOTES' => 'Notes sur l’utilisateur',
'VIEW_ONLINE_TIME' => 'd’après le nombre d’utilisateurs actifs cette dernière minute',
'VIEW_ONLINE_TIMES' => 'd’après le nombre d’utilisateurs actifs ces %d dernières minutes',
'VIEW_TOPIC' => 'Afficher le sujet',
'VIEW_TOPIC_ANNOUNCEMENT' => 'Annonce: ',
'VIEW_TOPIC_GLOBAL' => 'Annonce globale: ',
'VIEW_TOPIC_LOCKED' => 'Verrouillé: ',
'VIEW_TOPIC_LOGS' => 'Voir les journaux',
'VIEW_TOPIC_MOVED' => 'Déplacé: ',
'VIEW_TOPIC_POLL' => 'Sondage: ',
'VIEW_TOPIC_STICKY' => 'Post-it: ',
'VISIT_WEBSITE' => 'Visiter le site Internet',
'WARNINGS' => 'Avertissements',
'WARN_USER' => 'Avertir l’utilisateur',
'WATCH_FORUM_CONFIRM' => 'Êtes-vous sûr de vouloir surveiller ce forum ?',
'WATCH_FORUM_DETAILED' => 'Êtes-vous sûr de vouloir surveiller le forum « %s » ?',
'WATCH_TOPIC_CONFIRM' => 'Êtes-vous sûr de vouloir surveiller ce sujet ?',
'WATCH_TOPIC_DETAILED' => 'Êtes-vous sûr de vouloir surveiller le sujet « %s » ?',
'WELCOME_SUBJECT' => 'Bienvenue sur les forums %s',
'WEBSITE' => 'Site Internet',
'WHOIS' => 'Whois',
'WHO_IS_ONLINE' => 'Qui est en ligne',
'WRONG_PASSWORD' => 'Vous avez entré un mot de passe incorrect.',
'WRONG_DATA_COLOUR' => 'La valeur saisie pour la couleur est invalide.',
'WRONG_DATA_ICQ' => 'Le numéro que vous avez entré n’est pas un numéro ICQ valide.',
'WRONG_DATA_JABBER' => 'Le nom que vous avez entré n’est pas un nom de compte Jabber valide.',
'WRONG_DATA_LANG' => 'La langue que vous avez indiquée n’est pas valide.',
'WRONG_DATA_WEBSITE' => 'L’adresse de site Internet doit être une URL valide, incluant le protocole. Par exemple http://www.exemple.com/.',
'WROTE' => 'a écrit',
'YEAR' => 'Année',
'YEAR_MONTH_DAY' => '(AAAA-MM-JJ)',
'YES' => 'Oui',
'YIM' => 'YIM',
'YOU_LAST_VISIT' => 'Dernière visite: %s',
'YOU_NEW_PM' => 'Un nouveau message privé vous attend dans votre boîte de réception.',
'YOU_NEW_PMS' => 'De nouveaux messages privés vous attendent dans votre boîte de réception.',
'YOU_NO_NEW_PM' => 'Aucun nouveau message privé en attente.',
'datetime' => array(
'TODAY' => 'Aujourd’hui',
'TOMORROW' => 'Demain',
'YESTERDAY' => 'Hier',
'AGO' => array(
0 => 'il y a moins d’une minute',
1 => 'il y a %d minute',
2 => 'il y a %d minutes',
60 => 'il y a 1 heure',
),
'Sunday' => 'Dimanche',
'Monday' => 'Lundi',
'Tuesday' => 'Mardi',
'Wednesday' => 'Mercredi',
'Thursday' => 'Jeudi',
'Friday' => 'Vendredi',
'Saturday' => 'Samedi',
'Sun' => 'Dim',
'Mon' => 'Lun',
'Tue' => 'Mar',
'Wed' => 'Mer',
'Thu' => 'Jeu',
'Fri' => 'Ven',
'Sat' => 'Sam',
'January' => 'Janvier',
'February' => 'Février',
'March' => 'Mars',
'April' => 'Avril',
'May' => 'Mai',
'June' => 'Juin',
'July' => 'Juillet',
'August' => 'Août',
'September' => 'Septembre',
'October' => 'Octobre',
'November' => 'Novembre',
'December' => 'Décembre',
'Jan' => 'Jan',
'Feb' => 'Fév',
'Mar' => 'Mar',
'Apr' => 'Avr',
'May_short' => 'Mai', // Short representation of "May". May_short used because in English the short and long date are the same for May.
'Jun' => 'Juin',
'Jul' => 'Juil',
'Aug' => 'Aoû',
'Sep' => 'Sep',
'Oct' => 'Oct',
'Nov' => 'Nov',
'Dec' => 'Déc',
),
'tz' => array(
'-12' => 'UTC - 12 heures',
'-11' => 'UTC - 11 heures',
'-10' => 'UTC - 10 heures',
'-9.5' => 'UTC - 9:30 heures',
'-9' => 'UTC - 9 heures',
'-8' => 'UTC - 8 heures',
'-7' => 'UTC - 7 heures',
'-6' => 'UTC - 6 heures',
'-5' => 'UTC - 5 heures',
'-4.5' => 'UTC - 4:30 heures',
'-4' => 'UTC - 4 heures',
'-3.5' => 'UTC - 3:30 heures',
'-3' => 'UTC - 3 heures',
'-2' => 'UTC - 2 heures',
'-1' => 'UTC - 1 heure',
'0' => 'UTC',
'1' => 'UTC + 1 heure',
'2' => 'UTC + 2 heures',
'3' => 'UTC + 3 heures',
'3.5' => 'UTC + 3:30 heures',
'4' => 'UTC + 4 heures',
'4.5' => 'UTC + 4:30 heures',
'5' => 'UTC + 5 heures',
'5.5' => 'UTC + 5:30 heures',
'5.75' => 'UTC + 5:45 heures',
'6' => 'UTC + 6 heures',
'6.5' => 'UTC + 6:30 heures',
'7' => 'UTC + 7 heures',
'8' => 'UTC + 8 heures',
'8.75' => 'UTC + 8:45 heures',
'9' => 'UTC + 9 heures',
'9.5' => 'UTC + 9:30 heures',
'10' => 'UTC + 10 heures',
'10.5' => 'UTC + 10:30 heures',
'11' => 'UTC + 11 heures',
'11.5' => 'UTC + 11:30 heures',
'12' => 'UTC + 12 heures',
'12.75' => 'UTC + 12:45 heures',
'13' => 'UTC + 13 heures',
'14' => 'UTC + 14 heures',
'dst' => '[ Heure d’été ]',
),
'tz_zones' => array(
'-12' => '[UTC - 12] Île Baker',
'-11' => '[UTC - 11] Niue, Samoa',
'-10' => '[UTC - 10] Hawaii-Aleutian, Île Cook',
'-9.5' => '[UTC - 9:30] Îles Marquises',
'-9' => '[UTC - 9] Alaska, Île Gambier',
'-8' => '[UTC - 8] Pacifique',
'-7' => '[UTC - 7] Montagnes Rocheuses',
'-6' => '[UTC - 6] Centre',
'-5' => '[UTC - 5] Est',
'-4.5' => '[UTC - 4:30] Venezuela',
'-4' => '[UTC - 4] Atlantique',
'-3.5' => '[UTC - 3:30] Terre-Neuve',
'-3' => '[UTC - 3] Amazonie, Groenland Central',
'-2' => '[UTC - 2] Fernando de Noronha, Géorgie du Sud et les Îles Sandwich du Sud',
'-1' => '[UTC - 1] Açores, Cap-Vert, Groenland de l’Est',
'0' => '[UTC] Europe de l’Ouest, Méridien de Greenwich',
'1' => '[UTC + 1] Europe Centrale, Afrique de l’Ouest',
'2' => '[UTC + 2] Europe de l’Est, Afrique Centrale',
'3' => '[UTC + 3] Moscou, Afrique de l’Est',
'3.5' => '[UTC + 3:30] Iran',
'4' => '[UTC + 4] Gulf, Samara',
'4.5' => '[UTC + 4:30] Afghanistan',
'5' => '[UTC + 5] Pakistan, Iekaterinbourg',
'5.5' => '[UTC + 5:30] Inde, Sri Lanka',
'5.75' => '[UTC + 5:45] Népal',
'6' => '[UTC + 6] Bangladesh, Bhoutan, Novosibirsk',
'6.5' => '[UTC + 6:30] Îles Cocos, Myanmar',
'7' => '[UTC + 7] Indochine, Krasnoyarsk',
'8' => '[UTC + 8] Chine, Australie de l’Ouest, Irkutsk',
'8.75' => '[UTC + 8:45] Australie du Sud-Est',
'9' => '[UTC + 9] Japon, Corée, Chita',
'9.5' => '[UTC + 9:30] Australie Centrale',
'10' => '[UTC + 10] Australie de l’Est, Vladivostok',
'10.5' => '[UTC + 10:30] Lord Howe',
'11' => '[UTC + 11] Île Solomon, Magadan',
'11.5' => '[UTC + 11:30] Île Norfolk',
'12' => '[UTC + 12] Nouvelle Zélande, Fiji, Kamchatka',
'12.75' => '[UTC + 12:45] Îles Chatham',
'13' => '[UTC + 13] Tongo, Îles Phoenix',
'14' => '[UTC + 14] Île de Wight',
),
// The value is only an example and will get replaced by the current time on view
'dateformats' => array(
'd M Y, H:i' => '01 Jan 2007, 13:37',
'd M Y H:i' => '01 Jan 2007 13:37',
'M j, \'y, H:i' => 'Jan 10, \'07, 13:37',
'D M d, Y g:i a' => 'Lun Jan 01, 2007 1:37 pm',
'F j, Y, g:i a' => 'Janvier 10, 2007, 1:37 pm',
'|d M Y|, H:i' => '[Jours relatifs], 13:37 / 10 Jan 2007, 13:37',
'|F j, Y|, g:i a' => '[Jours relatifs], 1:37 pm / Janvier 10, 2007, 1:37 pm'
),
// The default dateformat which will be used on new installs in this language
// Translators should change this if a the usual date format is different
'default_dateformat' => 'D j M Y H:i', // Lun 10 Jan 2007 13:37
));
?>
|
gpl-2.0
|
qtproject/qtwebkit
|
Source/WebKit/qt/WebCoreSupport/ProgressTrackerClientQt.cpp
|
3552
|
/*
* Copyright (C) 2016 Konstantin Tokarev <annulen@yandex.ru>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ProgressTrackerClientQt.h"
#include "Document.h"
#include "EventHandler.h"
#include "Frame.h"
#include "FrameLoaderClientQt.h"
#include "HTMLFormElement.h"
#include "ProgressTracker.h"
#include "QWebFrameAdapter.h"
#include "QWebPageAdapter.h"
#include "WebEventConversion.h"
namespace WebCore {
bool ProgressTrackerClientQt::dumpProgressFinishedCallback = false;
ProgressTrackerClientQt::ProgressTrackerClientQt(QWebPageAdapter* webPageAdapter)
: m_webPage(webPageAdapter)
{
connect(this, SIGNAL(loadProgress(int)),
m_webPage->handle(), SIGNAL(loadProgress(int)));
}
void ProgressTrackerClientQt::progressTrackerDestroyed()
{
delete this;
}
void ProgressTrackerClientQt::progressStarted(Frame& originatingProgressFrame)
{
QWebFrameAdapter* frame = QWebFrameAdapter::kit(&originatingProgressFrame);
ASSERT(m_webPage == frame->pageAdapter);
static_cast<FrameLoaderClientQt&>(originatingProgressFrame.loader().client()).originatingLoadStarted();
if (!originatingProgressFrame.tree().parent())
m_webPage->updateNavigationActions();
}
void ProgressTrackerClientQt::progressEstimateChanged(Frame& originatingProgressFrame)
{
ASSERT(m_webPage == QWebFrameAdapter::kit(&originatingProgressFrame)->pageAdapter);
emit loadProgress(qRound(originatingProgressFrame.page()->progress().estimatedProgress() * 100));
}
void ProgressTrackerClientQt::progressFinished(Frame& originatingProgressFrame)
{
if (dumpProgressFinishedCallback)
printf("postProgressFinishedNotification\n");
QWebFrameAdapter* frame = QWebFrameAdapter::kit(&originatingProgressFrame);
ASSERT(m_webPage == frame->pageAdapter);
// Send a mousemove event to:
// (1) update the cursor to change according to whatever is underneath the mouse cursor right now;
// (2) display the tool tip if the mouse hovers a node which has a tool tip.
QPoint localPos;
if (frame->handleProgressFinished(&localPos)) {
QMouseEvent event(QEvent::MouseMove, localPos, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
originatingProgressFrame.eventHandler().mouseMoved(convertMouseEvent(&event, 0));
}
}
}
|
gpl-2.0
|
GreenHunan/aircheck-server
|
app/model/Record.scala
|
1023
|
package model
import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util.Locale
import play.api.libs.json._
import play.api.libs.functional.syntax._
/**
* Created by hadoop on 16-7-24.
*/
case class Record(density:Float,
longitude:Double, latitude: Double,
user_id: Int,
timeString: String){
def toDensityPoint = DensityPoint(lat = latitude, lng = longitude, count = density)
}
object Record{
implicit val jsonWrites:Writes[Record] = (
(JsPath \ "density").write[Float] and
(JsPath \ "lng").write[Double] and
(JsPath \ "lat").write[Double] and
(JsPath \ "user_id").write[Int] and
(JsPath \ "time").write[String]
)(unlift(Record.unapply))
implicit val jsonReads:Reads[Record] = (
(JsPath \ "density").read[Float] and
(JsPath \ "lng").read[Double] and
(JsPath \ "lat").read[Double] and
(JsPath \ "user_id").read[Int] and
(JsPath \ "time").read[String]
)(Record.apply _)
}
|
gpl-2.0
|
utfpr-dv/derdi-dv
|
sigeu/src/br/edu/utfpr/dv/sigeu/config/Config.java
|
3787
|
package br.edu.utfpr.dv.sigeu.config;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import javax.faces.context.FacesContext;
import com.adamiworks.utils.FileUtils;
public class Config {
public static final String APPLICATION_NAME = "Sistema Integrado de Gestão Universitária";
public static final String APPLICATION_CODE = "SIGEU";
public static final String APPLICATION_VERSION = "1.4.8";
public static final String CONFIG_ADMIN = "admin";
public static final String CONFIG_DEBUG = "debug";
public static final String CONFIG_PATH_UPLOAD = "path.upload";
public static final String CONFIG_FILE = "config.properties";
public static final String NOME_GRUPO_EXTERNO = "EXTERNO";
public static final String SEND_MAIL = "sendmail";
//
private static Config self;
//
private Properties config;
private boolean debugMode;
private boolean adminMode;
private int threadMax = 2;
private String url;
private boolean sendMail = false;
static {
self = new Config();
}
private Config() {
// Lê arquivo de configurações
try {
config = FileUtils.getPropertiesFromClasspath(CONFIG_FILE);
} catch (IOException e) {
e.printStackTrace();
}
this.adminMode = false;
try {
System.out.print("Validando modo Admin: [");
String admin = config.getProperty(CONFIG_ADMIN).trim().toLowerCase();
System.out.println(admin + "]");
if (admin != null) {
if (admin.toLowerCase().equals("true")) {
System.out.println("*** SISTEMA ESTÁ EM MANUTENÇÃO ***");
this.adminMode = true;
}
}
} catch (Exception e) {
// ignora
}
this.debugMode = false;
try {
String debug = config.getProperty(CONFIG_DEBUG).trim().toLowerCase();
if (debug != null) {
if (debug.equals("true")) {
this.debugMode = true;
}
}
} catch (Exception e) {
// ignora
}
try {
String thread = config.getProperty("thread.max").trim().toLowerCase();
if (thread != null) {
this.threadMax = Integer.valueOf(thread);
}
} catch (Exception e) {
this.threadMax = 2;
}
try {
url = config.getProperty("url").trim().toLowerCase();
} catch (Exception e) {
// ignora
}
this.sendMail = true;
try {
String sendMailstr = config.getProperty(SEND_MAIL).trim().toLowerCase();
if (sendMailstr != null) {
if (sendMailstr.equals("false")) {
this.sendMail = false;
}
}
} catch (Exception e) {
// ignora
}
}
public static Config getInstance() {
// if (self == null) {
// self = new Config();
// }
return self;
}
/**
* Retorna o valor de uma propriedade do arquivo sigeu.properties. As
* propriedades disponíveis são constantes dessa mesma classe iniciadas por
* <code><b>CONFIG_</b></code>.
*
* @param name
* Constantes desta mesma classe iniciada por
* <code><b>CONFIG_</b></code>.
* @return
*/
public String getConfig(String name) {
return config.getProperty(name);
}
/**
* Insere uma variável de sessão e define seu valor
*
* @param key
* @param value
*/
public void setSessionVariable(String key, Object value) {
Map<String, Object> map = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
map.put(key, value);
}
/**
* Recupera o valor de uma variável de sessão
*
* @param key
* @return
*/
public Object getSessionVariable(String key) {
Map<String, Object> map = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
return map.get(key);
}
public boolean isDebugMode() {
return debugMode;
}
public int getThreadMax() {
return threadMax;
}
public String getUrl() {
return url;
}
public boolean isAdminMode() {
return adminMode;
}
public boolean isSendMail() {
return sendMail;
}
}
|
gpl-2.0
|
livingstoneonline/livingstone_online_theme
|
templates/menu/menu-tree.func.php
|
529
|
<?php
/**
* @file
* Stub file for bootstrap_menu_tree() and suggestion(s).
*/
/**
* Bootstrap theme wrapper function for the primary menu links.
*/
function livingstone_theme_menu_tree__primary(&$variables) {
return '<ul class="menu nav navbar-nav primary">' . $variables['tree'] . '</ul>';
}
/**
* Bootstrap theme wrapper function for the primary menu on the front page.
*/
function livingstone_theme_menu_tree__primary__front(&$variables) {
return '<ul class="menu nav primary">' . $variables['tree'] . '</ul>';
}
|
gpl-2.0
|
gregoiredx/web-letter
|
src/test/java/ggd/webletter/web/LetterResourceTest.java
|
836
|
package ggd.webletter.web;
import ggd.webletter.test.WithServer;
import org.junit.ClassRule;
import org.junit.Test;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
import static org.assertj.core.api.Assertions.assertThat;
public class LetterResourceTest {
@ClassRule
public static WithServer server = new WithServer();
@Test
public void getResponse() {
Form form = new Form();
form.param("closing", "Cordialement");
Entity<Form> entity = Entity.form(form);
Response response = server.getTarget().path(LetterResource.PATH).request().post(entity);
assertThat(response.getStatusInfo().getFamily()).isEqualTo(SUCCESSFUL);
}
}
|
gpl-2.0
|
muromec/qtopia-ezx
|
qtopiacore/qt/tools/designer/src/lib/shared/qdesigner_widgetbox.cpp
|
2630
|
/****************************************************************************
**
** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved.
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** This file may be used under the terms of the GNU General Public
** License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Alternatively you may (at
** your option) use any later version of the GNU General Public
** License if such license has been publicly approved by Trolltech ASA
** (or its successors, if any) and the KDE Free Qt Foundation. In
** addition, as a special exception, Trolltech gives you certain
** additional rights. These rights are described in the Trolltech GPL
** Exception version 1.2, which can be found at
** http://www.trolltech.com/products/qt/gplexception/ and in the file
** GPL_EXCEPTION.txt in this package.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/. If
** you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** In addition, as a special exception, Trolltech, as the sole
** copyright holder for Qt Designer, grants users of the Qt/Eclipse
** Integration plug-in the right for the Qt/Eclipse Integration to
** link to functionality provided by Qt Designer and its related
** libraries.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly
** granted herein.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
/*
TRANSLATOR qdesigner_internal::QDesignerWidgetBox
*/
#include "qdesigner_widgetbox_p.h"
namespace qdesigner_internal {
QDesignerWidgetBox::QDesignerWidgetBox(QWidget *parent, Qt::WindowFlags flags)
: QDesignerWidgetBoxInterface(parent, flags),
m_loadMode(LoadMerge)
{
}
QDesignerWidgetBox::LoadMode QDesignerWidgetBox::loadMode() const
{
return m_loadMode;
}
void QDesignerWidgetBox::setLoadMode(LoadMode lm)
{
m_loadMode = lm;
}
} // namespace qdesigner_internal
|
gpl-2.0
|
akairain/QEMU
|
scripts/qapi.py
|
35102
|
#
# QAPI helper library
#
# Copyright IBM, Corp. 2011
# Copyright (c) 2013-2015 Red Hat Inc.
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
# Markus Armbruster <armbru@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2.
# See the COPYING file in the top-level directory.
import re
from ordereddict import OrderedDict
import os
import sys
builtin_types = {
'str': 'QTYPE_QSTRING',
'int': 'QTYPE_QINT',
'number': 'QTYPE_QFLOAT',
'bool': 'QTYPE_QBOOL',
'int8': 'QTYPE_QINT',
'int16': 'QTYPE_QINT',
'int32': 'QTYPE_QINT',
'int64': 'QTYPE_QINT',
'uint8': 'QTYPE_QINT',
'uint16': 'QTYPE_QINT',
'uint32': 'QTYPE_QINT',
'uint64': 'QTYPE_QINT',
'size': 'QTYPE_QINT',
}
# Whitelist of commands allowed to return a non-dictionary
returns_whitelist = [
# From QMP:
'human-monitor-command',
'query-migrate-cache-size',
'query-tpm-models',
'query-tpm-types',
'ringbuf-read',
# From QGA:
'guest-file-open',
'guest-fsfreeze-freeze',
'guest-fsfreeze-freeze-list',
'guest-fsfreeze-status',
'guest-fsfreeze-thaw',
'guest-get-time',
'guest-set-vcpus',
'guest-sync',
'guest-sync-delimited',
# From qapi-schema-test:
'user_def_cmd3',
]
enum_types = []
struct_types = []
union_types = []
events = []
all_names = {}
def error_path(parent):
res = ""
while parent:
res = ("In file included from %s:%d:\n" % (parent['file'],
parent['line'])) + res
parent = parent['parent']
return res
class QAPISchemaError(Exception):
def __init__(self, schema, msg):
self.input_file = schema.input_file
self.msg = msg
self.col = 1
self.line = schema.line
for ch in schema.src[schema.line_pos:schema.pos]:
if ch == '\t':
self.col = (self.col + 7) % 8 + 1
else:
self.col += 1
self.info = schema.parent_info
def __str__(self):
return error_path(self.info) + \
"%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg)
class QAPIExprError(Exception):
def __init__(self, expr_info, msg):
self.info = expr_info
self.msg = msg
def __str__(self):
return error_path(self.info['parent']) + \
"%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
class QAPISchema:
def __init__(self, fp, input_relname=None, include_hist=[],
previously_included=[], parent_info=None):
""" include_hist is a stack used to detect inclusion cycles
previously_included is a global state used to avoid multiple
inclusions of the same file"""
input_fname = os.path.abspath(fp.name)
if input_relname is None:
input_relname = fp.name
self.input_dir = os.path.dirname(input_fname)
self.input_file = input_relname
self.include_hist = include_hist + [(input_relname, input_fname)]
previously_included.append(input_fname)
self.parent_info = parent_info
self.src = fp.read()
if self.src == '' or self.src[-1] != '\n':
self.src += '\n'
self.cursor = 0
self.line = 1
self.line_pos = 0
self.exprs = []
self.accept()
while self.tok != None:
expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info}
expr = self.get_expr(False)
if isinstance(expr, dict) and "include" in expr:
if len(expr) != 1:
raise QAPIExprError(expr_info, "Invalid 'include' directive")
include = expr["include"]
if not isinstance(include, str):
raise QAPIExprError(expr_info,
'Expected a file name (string), got: %s'
% include)
include_path = os.path.join(self.input_dir, include)
for elem in self.include_hist:
if include_path == elem[1]:
raise QAPIExprError(expr_info, "Inclusion loop for %s"
% include)
# skip multiple include of the same file
if include_path in previously_included:
continue
try:
fobj = open(include_path, 'r')
except IOError, e:
raise QAPIExprError(expr_info,
'%s: %s' % (e.strerror, include))
exprs_include = QAPISchema(fobj, include, self.include_hist,
previously_included, expr_info)
self.exprs.extend(exprs_include.exprs)
else:
expr_elem = {'expr': expr,
'info': expr_info}
self.exprs.append(expr_elem)
def accept(self):
while True:
self.tok = self.src[self.cursor]
self.pos = self.cursor
self.cursor += 1
self.val = None
if self.tok == '#':
self.cursor = self.src.find('\n', self.cursor)
elif self.tok in ['{', '}', ':', ',', '[', ']']:
return
elif self.tok == "'":
string = ''
esc = False
while True:
ch = self.src[self.cursor]
self.cursor += 1
if ch == '\n':
raise QAPISchemaError(self,
'Missing terminating "\'"')
if esc:
if ch == 'b':
string += '\b'
elif ch == 'f':
string += '\f'
elif ch == 'n':
string += '\n'
elif ch == 'r':
string += '\r'
elif ch == 't':
string += '\t'
elif ch == 'u':
value = 0
for x in range(0, 4):
ch = self.src[self.cursor]
self.cursor += 1
if ch not in "0123456789abcdefABCDEF":
raise QAPISchemaError(self,
'\\u escape needs 4 '
'hex digits')
value = (value << 4) + int(ch, 16)
# If Python 2 and 3 didn't disagree so much on
# how to handle Unicode, then we could allow
# Unicode string defaults. But most of QAPI is
# ASCII-only, so we aren't losing much for now.
if not value or value > 0x7f:
raise QAPISchemaError(self,
'For now, \\u escape '
'only supports non-zero '
'values up to \\u007f')
string += chr(value)
elif ch in "\\/'\"":
string += ch
else:
raise QAPISchemaError(self,
"Unknown escape \\%s" %ch)
esc = False
elif ch == "\\":
esc = True
elif ch == "'":
self.val = string
return
else:
string += ch
elif self.tok in "tfn":
val = self.src[self.cursor - 1:]
if val.startswith("true"):
self.val = True
self.cursor += 3
return
elif val.startswith("false"):
self.val = False
self.cursor += 4
return
elif val.startswith("null"):
self.val = None
self.cursor += 3
return
elif self.tok == '\n':
if self.cursor == len(self.src):
self.tok = None
return
self.line += 1
self.line_pos = self.cursor
elif not self.tok.isspace():
raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
def get_members(self):
expr = OrderedDict()
if self.tok == '}':
self.accept()
return expr
if self.tok != "'":
raise QAPISchemaError(self, 'Expected string or "}"')
while True:
key = self.val
self.accept()
if self.tok != ':':
raise QAPISchemaError(self, 'Expected ":"')
self.accept()
if key in expr:
raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
expr[key] = self.get_expr(True)
if self.tok == '}':
self.accept()
return expr
if self.tok != ',':
raise QAPISchemaError(self, 'Expected "," or "}"')
self.accept()
if self.tok != "'":
raise QAPISchemaError(self, 'Expected string')
def get_values(self):
expr = []
if self.tok == ']':
self.accept()
return expr
if not self.tok in "{['tfn":
raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
'boolean or "null"')
while True:
expr.append(self.get_expr(True))
if self.tok == ']':
self.accept()
return expr
if self.tok != ',':
raise QAPISchemaError(self, 'Expected "," or "]"')
self.accept()
def get_expr(self, nested):
if self.tok != '{' and not nested:
raise QAPISchemaError(self, 'Expected "{"')
if self.tok == '{':
self.accept()
expr = self.get_members()
elif self.tok == '[':
self.accept()
expr = self.get_values()
elif self.tok in "'tfn":
expr = self.val
self.accept()
else:
raise QAPISchemaError(self, 'Expected "{", "[" or string')
return expr
def find_base_fields(base):
base_struct_define = find_struct(base)
if not base_struct_define:
return None
return base_struct_define['data']
# Return the qtype of an alternate branch, or None on error.
def find_alternate_member_qtype(qapi_type):
if builtin_types.has_key(qapi_type):
return builtin_types[qapi_type]
elif find_struct(qapi_type):
return "QTYPE_QDICT"
elif find_enum(qapi_type):
return "QTYPE_QSTRING"
elif find_union(qapi_type):
return "QTYPE_QDICT"
return None
# Return the discriminator enum define if discriminator is specified as an
# enum type, otherwise return None.
def discriminator_find_enum_define(expr):
base = expr.get('base')
discriminator = expr.get('discriminator')
if not (discriminator and base):
return None
base_fields = find_base_fields(base)
if not base_fields:
return None
discriminator_type = base_fields.get(discriminator)
if not discriminator_type:
return None
return find_enum(discriminator_type)
valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
def check_name(expr_info, source, name, allow_optional = False,
enum_member = False):
global valid_name
membername = name
if not isinstance(name, str):
raise QAPIExprError(expr_info,
"%s requires a string name" % source)
if name.startswith('*'):
membername = name[1:]
if not allow_optional:
raise QAPIExprError(expr_info,
"%s does not allow optional name '%s'"
% (source, name))
# Enum members can start with a digit, because the generated C
# code always prefixes it with the enum name
if enum_member:
membername = '_' + membername
if not valid_name.match(membername):
raise QAPIExprError(expr_info,
"%s uses invalid name '%s'" % (source, name))
def check_type(expr_info, source, value, allow_array = False,
allow_dict = False, allow_optional = False,
allow_star = False, allow_metas = []):
global all_names
orig_value = value
if value is None:
return
if allow_star and value == '**':
return
# Check if array type for value is okay
if isinstance(value, list):
if not allow_array:
raise QAPIExprError(expr_info,
"%s cannot be an array" % source)
if len(value) != 1 or not isinstance(value[0], str):
raise QAPIExprError(expr_info,
"%s: array type must contain single type name"
% source)
value = value[0]
orig_value = "array of %s" %value
# Check if type name for value is okay
if isinstance(value, str):
if value == '**':
raise QAPIExprError(expr_info,
"%s uses '**' but did not request 'gen':false"
% source)
if not value in all_names:
raise QAPIExprError(expr_info,
"%s uses unknown type '%s'"
% (source, orig_value))
if not all_names[value] in allow_metas:
raise QAPIExprError(expr_info,
"%s cannot use %s type '%s'"
% (source, all_names[value], orig_value))
return
# value is a dictionary, check that each member is okay
if not isinstance(value, OrderedDict):
raise QAPIExprError(expr_info,
"%s should be a dictionary" % source)
if not allow_dict:
raise QAPIExprError(expr_info,
"%s should be a type name" % source)
for (key, arg) in value.items():
check_name(expr_info, "Member of %s" % source, key,
allow_optional=allow_optional)
# Todo: allow dictionaries to represent default values of
# an optional argument.
check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
allow_array=True, allow_star=allow_star,
allow_metas=['built-in', 'union', 'alternate', 'struct',
'enum'])
def check_member_clash(expr_info, base_name, data, source = ""):
base = find_struct(base_name)
assert base
base_members = base['data']
for key in data.keys():
if key.startswith('*'):
key = key[1:]
if key in base_members or "*" + key in base_members:
raise QAPIExprError(expr_info,
"Member name '%s'%s clashes with base '%s'"
% (key, source, base_name))
if base.get('base'):
check_member_clash(expr_info, base['base'], data, source)
def check_command(expr, expr_info):
name = expr['command']
allow_star = expr.has_key('gen')
check_type(expr_info, "'data' for command '%s'" % name,
expr.get('data'), allow_dict=True, allow_optional=True,
allow_metas=['union', 'struct'], allow_star=allow_star)
returns_meta = ['union', 'struct']
if name in returns_whitelist:
returns_meta += ['built-in', 'alternate', 'enum']
check_type(expr_info, "'returns' for command '%s'" % name,
expr.get('returns'), allow_array=True, allow_dict=True,
allow_optional=True, allow_metas=returns_meta,
allow_star=allow_star)
def check_event(expr, expr_info):
global events
name = expr['event']
params = expr.get('data')
if name.upper() == 'MAX':
raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
events.append(name)
check_type(expr_info, "'data' for event '%s'" % name,
expr.get('data'), allow_dict=True, allow_optional=True,
allow_metas=['union', 'struct'])
def check_union(expr, expr_info):
name = expr['union']
base = expr.get('base')
discriminator = expr.get('discriminator')
members = expr['data']
values = { 'MAX': '(automatic)' }
# If the object has a member 'base', its value must name a struct,
# and there must be a discriminator.
if base is not None:
if discriminator is None:
raise QAPIExprError(expr_info,
"Union '%s' requires a discriminator to go "
"along with base" %name)
# Two types of unions, determined by discriminator.
# With no discriminator it is a simple union.
if discriminator is None:
enum_define = None
allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
if base is not None:
raise QAPIExprError(expr_info,
"Simple union '%s' must not have a base"
% name)
# Else, it's a flat union.
else:
# The object must have a string member 'base'.
if not isinstance(base, str):
raise QAPIExprError(expr_info,
"Flat union '%s' must have a string base field"
% name)
base_fields = find_base_fields(base)
if not base_fields:
raise QAPIExprError(expr_info,
"Base '%s' is not a valid struct"
% base)
# The value of member 'discriminator' must name a non-optional
# member of the base struct.
check_name(expr_info, "Discriminator of flat union '%s'" % name,
discriminator)
discriminator_type = base_fields.get(discriminator)
if not discriminator_type:
raise QAPIExprError(expr_info,
"Discriminator '%s' is not a member of base "
"struct '%s'"
% (discriminator, base))
enum_define = find_enum(discriminator_type)
allow_metas=['struct']
# Do not allow string discriminator
if not enum_define:
raise QAPIExprError(expr_info,
"Discriminator '%s' must be of enumeration "
"type" % discriminator)
# Check every branch
for (key, value) in members.items():
check_name(expr_info, "Member of union '%s'" % name, key)
# Each value must name a known type; furthermore, in flat unions,
# branches must be a struct with no overlapping member names
check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
value, allow_array=True, allow_metas=allow_metas)
if base:
branch_struct = find_struct(value)
assert branch_struct
check_member_clash(expr_info, base, branch_struct['data'],
" of branch '%s'" % key)
# If the discriminator names an enum type, then all members
# of 'data' must also be members of the enum type.
if enum_define:
if not key in enum_define['enum_values']:
raise QAPIExprError(expr_info,
"Discriminator value '%s' is not found in "
"enum '%s'" %
(key, enum_define["enum_name"]))
# Otherwise, check for conflicts in the generated enum
else:
c_key = _generate_enum_string(key)
if c_key in values:
raise QAPIExprError(expr_info,
"Union '%s' member '%s' clashes with '%s'"
% (name, key, values[c_key]))
values[c_key] = key
def check_alternate(expr, expr_info):
name = expr['alternate']
members = expr['data']
values = { 'MAX': '(automatic)' }
types_seen = {}
# Check every branch
for (key, value) in members.items():
check_name(expr_info, "Member of alternate '%s'" % name, key)
# Check for conflicts in the generated enum
c_key = _generate_enum_string(key)
if c_key in values:
raise QAPIExprError(expr_info,
"Alternate '%s' member '%s' clashes with '%s'"
% (name, key, values[c_key]))
values[c_key] = key
# Ensure alternates have no type conflicts.
check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
value,
allow_metas=['built-in', 'union', 'struct', 'enum'])
qtype = find_alternate_member_qtype(value)
assert qtype
if qtype in types_seen:
raise QAPIExprError(expr_info,
"Alternate '%s' member '%s' can't "
"be distinguished from member '%s'"
% (name, key, types_seen[qtype]))
types_seen[qtype] = key
def check_enum(expr, expr_info):
name = expr['enum']
members = expr.get('data')
values = { 'MAX': '(automatic)' }
if not isinstance(members, list):
raise QAPIExprError(expr_info,
"Enum '%s' requires an array for 'data'" % name)
for member in members:
check_name(expr_info, "Member of enum '%s'" %name, member,
enum_member=True)
key = _generate_enum_string(member)
if key in values:
raise QAPIExprError(expr_info,
"Enum '%s' member '%s' clashes with '%s'"
% (name, member, values[key]))
values[key] = member
def check_struct(expr, expr_info):
name = expr['struct']
members = expr['data']
check_type(expr_info, "'data' for struct '%s'" % name, members,
allow_dict=True, allow_optional=True)
check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
allow_metas=['struct'])
if expr.get('base'):
check_member_clash(expr_info, expr['base'], expr['data'])
def check_exprs(schema):
for expr_elem in schema.exprs:
expr = expr_elem['expr']
info = expr_elem['info']
if expr.has_key('enum'):
check_enum(expr, info)
elif expr.has_key('union'):
check_union(expr, info)
elif expr.has_key('alternate'):
check_alternate(expr, info)
elif expr.has_key('struct'):
check_struct(expr, info)
elif expr.has_key('command'):
check_command(expr, info)
elif expr.has_key('event'):
check_event(expr, info)
else:
assert False, 'unexpected meta type'
def check_keys(expr_elem, meta, required, optional=[]):
expr = expr_elem['expr']
info = expr_elem['info']
name = expr[meta]
if not isinstance(name, str):
raise QAPIExprError(info,
"'%s' key must have a string value" % meta)
required = required + [ meta ]
for (key, value) in expr.items():
if not key in required and not key in optional:
raise QAPIExprError(info,
"Unknown key '%s' in %s '%s'"
% (key, meta, name))
if (key == 'gen' or key == 'success-response') and value != False:
raise QAPIExprError(info,
"'%s' of %s '%s' should only use false value"
% (key, meta, name))
for key in required:
if not expr.has_key(key):
raise QAPIExprError(info,
"Key '%s' is missing from %s '%s'"
% (key, meta, name))
def parse_schema(input_file):
global all_names
exprs = []
# First pass: read entire file into memory
try:
schema = QAPISchema(open(input_file, "r"))
except (QAPISchemaError, QAPIExprError), e:
print >>sys.stderr, e
exit(1)
try:
# Next pass: learn the types and check for valid expression keys. At
# this point, top-level 'include' has already been flattened.
for builtin in builtin_types.keys():
all_names[builtin] = 'built-in'
for expr_elem in schema.exprs:
expr = expr_elem['expr']
info = expr_elem['info']
if expr.has_key('enum'):
check_keys(expr_elem, 'enum', ['data'])
add_enum(expr['enum'], info, expr['data'])
elif expr.has_key('union'):
check_keys(expr_elem, 'union', ['data'],
['base', 'discriminator'])
add_union(expr, info)
elif expr.has_key('alternate'):
check_keys(expr_elem, 'alternate', ['data'])
add_name(expr['alternate'], info, 'alternate')
elif expr.has_key('struct'):
check_keys(expr_elem, 'struct', ['data'], ['base'])
add_struct(expr, info)
elif expr.has_key('command'):
check_keys(expr_elem, 'command', [],
['data', 'returns', 'gen', 'success-response'])
add_name(expr['command'], info, 'command')
elif expr.has_key('event'):
check_keys(expr_elem, 'event', [], ['data'])
add_name(expr['event'], info, 'event')
else:
raise QAPIExprError(expr_elem['info'],
"Expression is missing metatype")
exprs.append(expr)
# Try again for hidden UnionKind enum
for expr_elem in schema.exprs:
expr = expr_elem['expr']
if expr.has_key('union'):
if not discriminator_find_enum_define(expr):
add_enum('%sKind' % expr['union'], expr_elem['info'],
implicit=True)
elif expr.has_key('alternate'):
add_enum('%sKind' % expr['alternate'], expr_elem['info'],
implicit=True)
# Final pass - validate that exprs make sense
check_exprs(schema)
except QAPIExprError, e:
print >>sys.stderr, e
exit(1)
return exprs
def parse_args(typeinfo):
if isinstance(typeinfo, str):
struct = find_struct(typeinfo)
assert struct != None
typeinfo = struct['data']
for member in typeinfo:
argname = member
argentry = typeinfo[member]
optional = False
if member.startswith('*'):
argname = member[1:]
optional = True
# Todo: allow argentry to be OrderedDict, for providing the
# value of an optional argument.
yield (argname, argentry, optional)
def de_camel_case(name):
new_name = ''
for ch in name:
if ch.isupper() and new_name:
new_name += '_'
if ch == '-':
new_name += '_'
else:
new_name += ch.lower()
return new_name
def camel_case(name):
new_name = ''
first = True
for ch in name:
if ch in ['_', '-']:
first = True
elif first:
new_name += ch.upper()
first = False
else:
new_name += ch.lower()
return new_name
def c_var(name, protect=True):
# ANSI X3J11/88-090, 3.1.1
c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
'for', 'goto', 'if', 'int', 'long', 'register', 'return',
'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
# ISO/IEC 9899:1999, 6.4.1
c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
# ISO/IEC 9899:2011, 6.4.1
c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
'_Static_assert', '_Thread_local'])
# GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
# excluding _.*
gcc_words = set(['asm', 'typeof'])
# C++ ISO/IEC 14882:2003 2.11
cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
'namespace', 'new', 'operator', 'private', 'protected',
'public', 'reinterpret_cast', 'static_cast', 'template',
'this', 'throw', 'true', 'try', 'typeid', 'typename',
'using', 'virtual', 'wchar_t',
# alternative representations
'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
# namespace pollution:
polluted_words = set(['unix', 'errno'])
if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
return "q_" + name
return name.replace('-', '_').lstrip("*")
def c_fun(name, protect=True):
return c_var(name, protect).replace('.', '_')
def c_list_type(name):
return '%sList' % name
def type_name(name):
if type(name) == list:
return c_list_type(name[0])
return name
def add_name(name, info, meta, implicit = False):
global all_names
check_name(info, "'%s'" % meta, name)
if name in all_names:
raise QAPIExprError(info,
"%s '%s' is already defined"
% (all_names[name], name))
if not implicit and name[-4:] == 'Kind':
raise QAPIExprError(info,
"%s '%s' should not end in 'Kind'"
% (meta, name))
all_names[name] = meta
def add_struct(definition, info):
global struct_types
name = definition['struct']
add_name(name, info, 'struct')
struct_types.append(definition)
def find_struct(name):
global struct_types
for struct in struct_types:
if struct['struct'] == name:
return struct
return None
def add_union(definition, info):
global union_types
name = definition['union']
add_name(name, info, 'union')
union_types.append(definition)
def find_union(name):
global union_types
for union in union_types:
if union['union'] == name:
return union
return None
def add_enum(name, info, enum_values = None, implicit = False):
global enum_types
add_name(name, info, 'enum', implicit)
enum_types.append({"enum_name": name, "enum_values": enum_values})
def find_enum(name):
global enum_types
for enum in enum_types:
if enum['enum_name'] == name:
return enum
return None
def is_enum(name):
return find_enum(name) != None
eatspace = '\033EATSPACE.'
# A special suffix is added in c_type() for pointer types, and it's
# stripped in mcgen(). So please notice this when you check the return
# value of c_type() outside mcgen().
def c_type(name, is_param=False):
if name == 'str':
if is_param:
return 'const char *' + eatspace
return 'char *' + eatspace
elif name == 'int':
return 'int64_t'
elif (name == 'int8' or name == 'int16' or name == 'int32' or
name == 'int64' or name == 'uint8' or name == 'uint16' or
name == 'uint32' or name == 'uint64'):
return name + '_t'
elif name == 'size':
return 'uint64_t'
elif name == 'bool':
return 'bool'
elif name == 'number':
return 'double'
elif type(name) == list:
return '%s *%s' % (c_list_type(name[0]), eatspace)
elif is_enum(name):
return name
elif name == None or len(name) == 0:
return 'void'
elif name in events:
return '%sEvent *%s' % (camel_case(name), eatspace)
else:
return '%s *%s' % (name, eatspace)
def is_c_ptr(name):
suffix = "*" + eatspace
return c_type(name).endswith(suffix)
def genindent(count):
ret = ""
for i in range(count):
ret += " "
return ret
indent_level = 0
def push_indent(indent_amount=4):
global indent_level
indent_level += indent_amount
def pop_indent(indent_amount=4):
global indent_level
indent_level -= indent_amount
def cgen(code, **kwds):
indent = genindent(indent_level)
lines = code.split('\n')
lines = map(lambda x: indent + x, lines)
return '\n'.join(lines) % kwds + '\n'
def mcgen(code, **kwds):
raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
return re.sub(re.escape(eatspace) + ' *', '', raw)
def basename(filename):
return filename.split("/")[-1]
def guardname(filename):
guard = basename(filename).rsplit(".", 1)[0]
for substr in [".", " ", "-"]:
guard = guard.replace(substr, "_")
return guard.upper() + '_H'
def guardstart(name):
return mcgen('''
#ifndef %(name)s
#define %(name)s
''',
name=guardname(name))
def guardend(name):
return mcgen('''
#endif /* %(name)s */
''',
name=guardname(name))
# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
# ENUM24_Name -> ENUM24_NAME
def _generate_enum_string(value):
c_fun_str = c_fun(value, False)
if value.isupper():
return c_fun_str
new_name = ''
l = len(c_fun_str)
for i in range(l):
c = c_fun_str[i]
# When c is upper and no "_" appears before, do more checks
if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
# Case 1: next string is lower
# Case 2: previous string is digit
if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
c_fun_str[i - 1].isdigit():
new_name += '_'
new_name += c
return new_name.lstrip('_').upper()
def generate_enum_full_value(enum_name, enum_value):
abbrev_string = _generate_enum_string(enum_name)
value_string = _generate_enum_string(enum_value)
return "%s_%s" % (abbrev_string, value_string)
|
gpl-2.0
|
kenorb/wp_site
|
sites/all/modules/contributions/[content]/[node]/flag/theme/flag.js
|
3082
|
// $Id: flag.js,v 1.1.2.4 2008/10/10 06:52:31 quicksketch Exp $
/**
* Terminology:
*
* "Link" means "Everything which is in flag.tpl.php" --and this may contain
* much more than the <A> element. On the other hand, when we speak
* specifically of the <A> element, we say "element" or "the <A> element".
*/
Drupal.flagLink = function(context) {
/**
* Helper function. Updates a link's HTML with a new one.
*
* @param element
* The <A> element.
* @return
* The new <A> elemenet.
*/
function updateLink(element, newHtml) {
var $newLink = $(newHtml);
// Initially hide the message so we can fade it in.
$('.flag-message', $newLink).css('display', 'none');
// Reattach the behavior to the new <A> element. This element
// is either whithin the wrapper or it is the outer element itself.
var $nucleus = $newLink.is('a') ? $newLink : $('a.flag', $newLink);
$nucleus.addClass('flag-processed').click(flagClick);
// Find the wrapper of the old link.
var $wrapper = $(element).parents('.flag-wrapper:first');
if ($wrapper.length == 0) {
// If no ancestor wrapper was found, or if the 'flag-wrapper' class is
// attached to the <a> element itself, then take the element itself.
$wrapper = $(element);
}
// Replace the old link with the new one.
$wrapper.after($newLink).remove();
// So it won't crash on Drupal 5.
if (Drupal.attachBehaviors) {
Drupal.attachBehaviors($newLink.get(0));
}
$('.flag-message', $newLink).fadeIn();
}
/**
* A click handler that is attached to all <A class="flag"> elements.
*/
function flagClick() {
// 'this' won't point to the element when it's inside the ajax closures,
// so we reference it using a variable.
var element = this;
// While waiting for a server response, the wrapper will have a
// 'flag-waiting' class. Themers are thus able to style the link
// differently, e.g., by displaying a throbber.
var $wrapper = $(element).parents('.flag-wrapper');
if ($wrapper.is('.flag-waiting')) {
// Guard against double-clicks.
return false;
}
$wrapper.addClass('flag-waiting');
// Hide any other active messages.
$('span.flag-message:visible').fadeOut();
// Send POST request
$.ajax({
type: 'POST',
url: element.href,
data: { js: true },
dataType: 'json',
success: function (data) {
if (data.status) {
// Success.
updateLink(element, data.newLink);
}
else {
// Failure.
alert(data.errorMessage);
$wrapper.removeClass('flag-waiting');
}
},
error: function (xmlhttp) {
alert('An HTTP error '+ xmlhttp.status +' occurred.\n'+ element.href);
}
});
return false;
}
$('a.flag:not(.flag-processed)').addClass('flag-processed').click(flagClick);
};
Drupal.behaviors.flagLink = function(context) {
// On load, bind the click behavior for all links on the page.
Drupal.flagLink(context);
};
|
gpl-2.0
|
cuongnd/test_pro
|
administrator/components/com_bookpro/models/tourprice.php
|
2150
|
<?php
/**
* Created by PhpStorm.
* User: THANHTIN
* Date: 5/9/2015
* Time: 2:57 PM
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.modeladmin');
class BookProModelTourPrice extends JModelAdmin {
/**
* (non-PHPdoc)
* @see JModelForm::getForm()
*/
public function getForm($data = array(), $loadData = true) {
$form = $this->loadForm('com_bookpro.tourprice', 'tourprice', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
return false;
return $form;
}
/**
* (non-PHPdoc)
* @see JModelForm::loadFormData()
*/
protected function loadFormData() {
$data = JFactory::getApplication()->getUserState('com_bookpro.edit.tourprice.data', array());
if (empty($data))
$data = $this->getItem();
return $data;
}
public function publish(&$pks, $value = 1) {
$user = JFactory::getUser();
$table = $this->getTable();
$pks = (array) $pks;
// Attempt to change the state of the records.
if (!$table->publish($pks, $value, $user->get('id'))) {
$this->setError($table->getError());
return false;
}
return true;
}
function unpublish($cids) {
return $this->state('state', $cids, 0, 1);
}
public function featured($pks, $value = 0) {
// Sanitize the ids.
$pks = (array) $pks;
JArrayHelper::toInteger($pks);
if (empty($pks)) {
$this->setError(JText::_('COM_CONTENT_NO_ITEM_SELECTED'));
return false;
}
try {
$db = $this->getDbo();
$query = $db->getQuery(true)
->update($db->quoteName('#__bookpro_tourprice'))
->set('featured = ' . (int) $value)
->where('id IN (' . implode(',', $pks) . ')');
$db->setQuery($query);
$db->execute();
} catch (Exception $e) {
$this->setError($e->getMessage());
return false;
}
$this->cleanCache();
return true;
}
}
|
gpl-2.0
|
RUBi-ZA/JMS
|
src/jobs/JMS/helpers.py
|
1226
|
from resource_managers.objects import *
def parse_settings_list(settings_list):
settings = []
for s in settings_list:
s = Setting(s["Key"], s["Value"])
settings.append(s)
return settings
def parse_settings_sections_dict(settings_sections_dict):
settings_sections = []
for section in settings_sections_dict:
ss = SettingsSection(section["SectionHeader"], [])
for setting in section["Settings"]:
s = Setting(setting["Key"], setting["Value"])
ss.Settings.append(s)
settings_sections.append(ss)
return settings_sections
def parse_node_dict(node_dict):
name = node_dict["Name"]
state = node_dict["State"]
num_cores = node_dict["NumCores"]
other = node_dict["Other"]
return Node(name=name, state=state, num_cores=num_cores, busy_cores=None, free_cores=None, other=other)
def parse_admin_dict(admin_dict):
admin = Administrator(admin_dict["AdministratorName"],
parse_settings_sections_dict(admin_dict["SettingsSections"]))
return admin
def parse_queue_dict(queue_dict):
queue = Queue(queue_dict["QueueName"],
parse_settings_sections_dict(queue_dict["SettingsSections"]))
return queue
|
gpl-2.0
|
jqln-0/ar-tabletop
|
src/filter.cpp
|
1841
|
#include "filter.h"
using std::vector;
using aruco::Marker;
using std::unordered_map;
// BoardIgnoringMarkerFilter
BoardIgnoringMarkerFilter::BoardIgnoringMarkerFilter(
const aruco::BoardConfiguration &config) {
// Create a hashset from the board markers for faster lookup later.
vector<int> ids;
config.getIdList(ids, false);
for (auto it = ids.begin(); it != ids.end(); ++it) {
board_markers_.insert(*it);
}
}
void BoardIgnoringMarkerFilter::Filter(vector<Marker> *m) {
// Iterate backwards so we can remove ids as we go.
for (auto it = m->rbegin(); it != m->rend(); ++it) {
if (board_markers_.find(it->id) != board_markers_.end()) {
m->erase(--(it.base()));
}
}
}
// SmoothingMarkerFilter
SmoothingMarkerFilter::SmoothingMarkerFilter(int memory_length)
: memory_length_(memory_length) {}
void SmoothingMarkerFilter::Filter(vector<Marker> *m) {
// Increment the last seen values and forget old markers.
vector<int> to_delete;
for (auto it = last_seen_.begin(); it != last_seen_.end(); ++it) {
last_seen_[it->first] += 1;
if (last_seen_[it->first] > memory_length_) {
to_delete.push_back(it->first);
}
}
// Do the actual forgetting.
for (auto it = to_delete.begin(); it != to_delete.end(); ++it) {
last_seen_.erase(last_seen_.find(*it));
markers_.erase(markers_.find(*it));
}
// Record markers from the current iteration.
for (auto it = m->begin(); it != m->end(); ++it) {
last_seen_[it->id] = 0;
markers_[it->id] = *it;
}
// Any markers with last_seen != 0 are markers which are not in this iteration
// that we have previous seen and remembered. Add them to the list of markers.
for (auto it = last_seen_.begin(); it != last_seen_.end(); ++it) {
if (it->second != 0) {
m->push_back(markers_[it->first]);
}
}
}
|
gpl-2.0
|
ermez3/pokechat
|
components/PokeApp.js
|
157
|
/*
* Module dependencies
*/
import React from 'react';
export default class PokeApp extends React.Component{
render(){
return <h1> Poke Chat</h1>
}
}
|
gpl-2.0
|
hjpotter92/dcplusplus
|
dcpp/AdcHub.cpp
|
32738
|
/*
* Copyright (C) 2001-2013 Jacek Sieka, arnetheduck on gmail point 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.
*/
#include "stdinc.h"
#include "AdcHub.h"
#include <boost/format.hpp>
#include <boost/scoped_array.hpp>
#include "AdcCommand.h"
#include "ChatMessage.h"
#include "ClientManager.h"
#include "ConnectionManager.h"
#include "ConnectivityManager.h"
#include "CryptoManager.h"
#include "format.h"
#include "LogManager.h"
#include "ShareManager.h"
#include "StringTokenizer.h"
#include "ThrottleManager.h"
#include "UploadManager.h"
#include "PluginManager.h"
#include "UserCommand.h"
#include "Util.h"
#include "version.h"
#include <cmath>
namespace dcpp {
using std::make_pair;
const string AdcHub::CLIENT_PROTOCOL("ADC/1.0");
const string AdcHub::SECURE_CLIENT_PROTOCOL_TEST("ADCS/0.10");
const string AdcHub::ADCS_FEATURE("ADC0");
const string AdcHub::TCP4_FEATURE("TCP4");
const string AdcHub::TCP6_FEATURE("TCP6");
const string AdcHub::UDP4_FEATURE("UDP4");
const string AdcHub::UDP6_FEATURE("UDP6");
const string AdcHub::NAT0_FEATURE("NAT0");
const string AdcHub::SEGA_FEATURE("SEGA");
const string AdcHub::CCPM_FEATURE("CCPM");
const string AdcHub::BASE_SUPPORT("ADBASE");
const string AdcHub::BAS0_SUPPORT("ADBAS0");
const string AdcHub::TIGR_SUPPORT("ADTIGR");
const string AdcHub::UCM0_SUPPORT("ADUCM0");
const string AdcHub::BLO0_SUPPORT("ADBLO0");
const string AdcHub::ZLIF_SUPPORT("ADZLIF");
const vector<StringList> AdcHub::searchExts;
AdcHub::AdcHub(const string& aHubURL, bool secure) :
Client(aHubURL, '\n', secure), oldPassword(false), udp(Socket::TYPE_UDP), sid(0) {
TimerManager::getInstance()->addListener(this);
}
AdcHub::~AdcHub() {
TimerManager::getInstance()->removeListener(this);
clearUsers();
}
OnlineUser& AdcHub::getUser(const uint32_t aSID, const CID& aCID) {
OnlineUser* ou = findUser(aSID);
if(ou) {
return *ou;
}
UserPtr p = ClientManager::getInstance()->getUser(aCID);
{
Lock l(cs);
ou = users.emplace(aSID, new OnlineUser(p, *this, aSID)).first->second;
}
if(aSID != AdcCommand::HUB_SID)
ClientManager::getInstance()->putOnline(ou);
return *ou;
}
OnlineUser* AdcHub::findUser(const uint32_t aSID) const {
Lock l(cs);
auto i = users.find(aSID);
return i == users.end() ? NULL : i->second;
}
OnlineUser* AdcHub::findUser(const CID& aCID) const {
Lock l(cs);
for(auto& i: users) {
if(i.second->getUser()->getCID() == aCID) {
return i.second;
}
}
return 0;
}
void AdcHub::putUser(const uint32_t aSID, bool disconnect) {
OnlineUser* ou = 0;
{
Lock l(cs);
auto i = users.find(aSID);
if(i == users.end())
return;
ou = i->second;
users.erase(i);
}
if(aSID != AdcCommand::HUB_SID)
ClientManager::getInstance()->putOffline(ou, disconnect);
fire(ClientListener::UserRemoved(), this, *ou);
delete ou;
}
void AdcHub::clearUsers() {
decltype(users) tmp;
{
Lock l(cs);
users.swap(tmp);
}
for(auto& i: tmp) {
if(i.first != AdcCommand::HUB_SID)
ClientManager::getInstance()->putOffline(i.second);
delete i.second;
}
}
void AdcHub::handle(AdcCommand::INF, AdcCommand& c) noexcept {
if(c.getParameters().empty())
return;
string cid;
OnlineUser* u = 0;
if(c.getParam("ID", 0, cid)) {
u = findUser(CID(cid));
if(u) {
if(u->getIdentity().getSID() != c.getFrom()) {
// Same CID but different SID not allowed - buggy hub?
string nick;
if(!c.getParam("NI", 0, nick)) {
nick = "[nick unknown]";
}
fire(ClientListener::StatusMessage(), this, str(F_("%1% (%2%) has same CID {%3%} as %4% (%5%), ignoring")
% u->getIdentity().getNick() % u->getIdentity().getSIDString() % cid % nick % AdcCommand::fromSID(c.getFrom())),
ClientListener::FLAG_IS_SPAM);
return;
}
} else {
u = &getUser(c.getFrom(), CID(cid));
}
} else if(c.getFrom() == AdcCommand::HUB_SID) {
u = &getUser(c.getFrom(), CID());
} else {
u = findUser(c.getFrom());
}
if(!u) {
dcdebug("AdcHub::INF Unknown user / no ID\n");
return;
}
for(auto& i: c.getParameters()) {
if(i.length() < 2)
continue;
u->getIdentity().set(i.c_str(), i.substr(2));
}
if(u->getIdentity().supports(ADCS_FEATURE)) {
u->getUser()->setFlag(User::TLS);
}
if(u->getUser() == getMyIdentity().getUser()) {
state = STATE_NORMAL;
setAutoReconnect(true);
setMyIdentity(u->getIdentity());
updateCounts(false);
}
if(u->getIdentity().isHub()) {
setHubIdentity(u->getIdentity());
fire(ClientListener::HubUpdated(), this);
} else {
updated(*u);
}
}
void AdcHub::handle(AdcCommand::SUP, AdcCommand& c) noexcept {
if(state != STATE_PROTOCOL) /** @todo SUP changes */
return;
bool baseOk = false;
bool tigrOk = false;
for(auto& i: c.getParameters()) {
if(i == BAS0_SUPPORT) {
baseOk = true;
tigrOk = true;
} else if(i == BASE_SUPPORT) {
baseOk = true;
} else if(i == TIGR_SUPPORT) {
tigrOk = true;
}
}
if(!baseOk) {
fire(ClientListener::StatusMessage(), this, _("Failed to negotiate base protocol"));
disconnect(false);
return;
} else if(!tigrOk) {
oldPassword = true;
// Some hubs fake BASE support without TIGR support =/
fire(ClientListener::StatusMessage(), this, _("Hub probably uses an old version of ADC, please encourage the owner to upgrade"));
}
}
void AdcHub::handle(AdcCommand::SID, AdcCommand& c) noexcept {
if(state != STATE_PROTOCOL) {
dcdebug("Invalid state for SID\n");
return;
}
if(c.getParameters().empty())
return;
sid = AdcCommand::toSID(c.getParam(0));
state = STATE_IDENTIFY;
infoImpl();
}
void AdcHub::handle(AdcCommand::MSG, AdcCommand& c) noexcept {
if(c.getParameters().empty())
return;
auto from = findUser(c.getFrom());
if(!from || from->getIdentity().noChat())
return;
decltype(from) to = nullptr, replyTo = nullptr;
string temp;
string chatMessage = c.getParam(0);
if(c.getParam("PM", 1, temp)) { // add PM<group-cid> as well
to = findUser(c.getTo());
if(!to)
return;
replyTo = findUser(AdcCommand::toSID(temp));
if(!replyTo || PluginManager::getInstance()->runHook(HOOK_CHAT_PM_IN, replyTo, chatMessage))
return;
} else if(PluginManager::getInstance()->runHook(HOOK_CHAT_IN, this, chatMessage))
return;
fire(ClientListener::Message(), this, ChatMessage(chatMessage, from, to, replyTo, c.hasFlag("ME", 1),
c.getParam("TS", 1, temp) ? Util::toInt64(temp) : 0));
}
void AdcHub::handle(AdcCommand::GPA, AdcCommand& c) noexcept {
if(c.getParameters().empty())
return;
salt = c.getParam(0);
state = STATE_VERIFY;
fire(ClientListener::GetPassword(), this);
}
void AdcHub::handle(AdcCommand::QUI, AdcCommand& c) noexcept {
uint32_t s = AdcCommand::toSID(c.getParam(0));
OnlineUser* victim = findUser(s);
if(victim) {
string tmp;
if(c.getParam("MS", 1, tmp)) {
OnlineUser* source = 0;
string tmp2;
if(c.getParam("ID", 1, tmp2)) {
source = findUser(AdcCommand::toSID(tmp2));
}
if(source) {
tmp = str(F_("%1% was kicked by %2%: %3%") % victim->getIdentity().getNick() %
source->getIdentity().getNick() % tmp);
} else {
tmp = str(F_("%1% was kicked: %2%") % victim->getIdentity().getNick() % tmp);
}
fire(ClientListener::StatusMessage(), this, tmp, ClientListener::FLAG_IS_SPAM);
}
putUser(s, c.getParam("DI", 1, tmp));
}
if(s == sid) {
// this QUI is directed to us
string tmp;
if(c.getParam("TL", 1, tmp)) {
if(tmp == "-1") {
setAutoReconnect(false);
} else {
setAutoReconnect(true);
setReconnDelay(Util::toUInt32(tmp));
}
}
if(!victim && c.getParam("MS", 1, tmp)) {
fire(ClientListener::StatusMessage(), this, tmp, ClientListener::FLAG_NORMAL);
}
if(c.getParam("RD", 1, tmp)) {
fire(ClientListener::Redirect(), this, tmp);
}
}
}
void AdcHub::handle(AdcCommand::CTM, AdcCommand& c) noexcept {
if(c.getParameters().size() < 3)
return;
OnlineUser* u = findUser(c.getFrom());
if(!u || u->getUser() == ClientManager::getInstance()->getMe())
return;
const string& protocol = c.getParam(0);
const string& port = c.getParam(1);
const string& token = c.getParam(2);
bool secure = false;
if(protocol == CLIENT_PROTOCOL) {
// Nothing special
} else if(protocol == SECURE_CLIENT_PROTOCOL_TEST && CryptoManager::getInstance()->TLSOk()) {
secure = true;
} else {
unknownProtocol(c.getFrom(), protocol, token);
return;
}
if(!u->getIdentity().isTcpActive()) {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_GENERIC, "IP unknown", AdcCommand::TYPE_DIRECT).setTo(c.getFrom()));
return;
}
ConnectionManager::getInstance()->adcConnect(*u, port, token, secure);
}
void AdcHub::handle(AdcCommand::RCM, AdcCommand& c) noexcept {
if(c.getParameters().size() < 2) {
return;
}
OnlineUser* u = findUser(c.getFrom());
if(!u || u->getUser() == ClientManager::getInstance()->getMe())
return;
const string& protocol = c.getParam(0);
const string& token = c.getParam(1);
bool secure;
if(protocol == CLIENT_PROTOCOL) {
secure = false;
} else if(protocol == SECURE_CLIENT_PROTOCOL_TEST && CryptoManager::getInstance()->TLSOk()) {
secure = true;
} else {
unknownProtocol(c.getFrom(), protocol, token);
return;
}
if(ClientManager::getInstance()->isActive()) {
connect(*u, token, CONNECTION_TYPE_LAST, secure);
return;
}
if (!u->getIdentity().supports(NAT0_FEATURE))
return;
// Attempt to traverse NATs and/or firewalls with TCP.
// If they respond with their own, symmetric, RNT command, both
// clients call ConnectionManager::adcConnect.
send(AdcCommand(AdcCommand::CMD_NAT, u->getIdentity().getSID(), AdcCommand::TYPE_DIRECT).
addParam(protocol).addParam(Util::toString(sock->getLocalPort())).addParam(token));
}
void AdcHub::handle(AdcCommand::CMD, AdcCommand& c) noexcept {
if(c.getParameters().size() < 1)
return;
const string& name = c.getParam(0);
bool rem = c.hasFlag("RM", 1);
if(rem) {
fire(ClientListener::HubUserCommand(), this, (int)UserCommand::TYPE_REMOVE, 0, name, Util::emptyString);
return;
}
bool sep = c.hasFlag("SP", 1);
string sctx;
if(!c.getParam("CT", 1, sctx))
return;
int ctx = Util::toInt(sctx);
if(ctx <= 0)
return;
if(sep) {
fire(ClientListener::HubUserCommand(), this, (int)UserCommand::TYPE_SEPARATOR, ctx, name, Util::emptyString);
return;
}
bool once = c.hasFlag("CO", 1);
string txt;
if(!c.getParam("TT", 1, txt))
return;
fire(ClientListener::HubUserCommand(), this, (int)(once ? UserCommand::TYPE_RAW_ONCE : UserCommand::TYPE_RAW), ctx, name, txt);
}
void AdcHub::sendUDP(const AdcCommand& cmd) noexcept {
string command;
string ip;
string port;
{
Lock l(cs);
auto i = users.find(cmd.getTo());
if(i == users.end()) {
dcdebug("AdcHub::sendUDP: invalid user\n");
return;
}
OnlineUser& ou = *i->second;
if(!ou.getIdentity().isUdpActive()) {
return;
}
ip = ou.getIdentity().getIp();
port = ou.getIdentity().getUdpPort();
command = cmd.toString(ou.getUser()->getCID());
}
try {
udp.writeTo(ip, port, command);
} catch(const SocketException& e) {
dcdebug("AdcHub::sendUDP: write failed: %s\n", e.getError().c_str());
udp.close();
}
}
void AdcHub::handle(AdcCommand::STA, AdcCommand& c) noexcept {
if(c.getParameters().size() < 2)
return;
OnlineUser* u = c.getFrom() == AdcCommand::HUB_SID ? &getUser(c.getFrom(), CID()) : findUser(c.getFrom());
if(!u)
return;
//int severity = Util::toInt(c.getParam(0).substr(0, 1));
if(c.getParam(0).size() != 3) {
return;
}
switch(Util::toInt(c.getParam(0).substr(1))) {
case AdcCommand::ERROR_BAD_PASSWORD:
{
if(c.getType() == AdcCommand::TYPE_INFO) {
setPassword(Util::emptyString);
}
break;
}
case AdcCommand::ERROR_COMMAND_ACCESS:
{
if(c.getType() == AdcCommand::TYPE_INFO) {
string tmp;
if(c.getParam("FC", 1, tmp) && tmp.size() == 4)
forbiddenCommands.insert(AdcCommand::toFourCC(tmp.c_str()));
}
break;
}
case AdcCommand::ERROR_PROTOCOL_UNSUPPORTED:
{
string tmp;
if(c.getParam("PR", 1, tmp)) {
if(tmp == CLIENT_PROTOCOL) {
u->getUser()->setFlag(User::NO_ADC_1_0_PROTOCOL);
} else if(tmp == SECURE_CLIENT_PROTOCOL_TEST) {
u->getUser()->setFlag(User::NO_ADCS_0_10_PROTOCOL);
u->getUser()->unsetFlag(User::TLS);
}
// Try again...
ConnectionManager::getInstance()->force(u->getUser());
}
return;
}
}
fire(ClientListener::Message(), this, ChatMessage(c.getParam(1), u));
}
void AdcHub::handle(AdcCommand::SCH, AdcCommand& c) noexcept {
OnlineUser* ou = findUser(c.getFrom());
if(!ou) {
dcdebug("Invalid user in AdcHub::onSCH\n");
return;
}
fire(ClientListener::AdcSearch(), this, c, *ou);
}
void AdcHub::handle(AdcCommand::RES, AdcCommand& c) noexcept {
OnlineUser* ou = findUser(c.getFrom());
if(!ou) {
dcdebug("Invalid user in AdcHub::onRES\n");
return;
}
SearchManager::getInstance()->onRES(c, ou->getUser());
}
void AdcHub::handle(AdcCommand::GET, AdcCommand& c) noexcept {
if(c.getParameters().size() < 5) {
if(!c.getParameters().empty()) {
if(c.getParam(0) == "blom") {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_GENERIC,
"Too few parameters for blom", AdcCommand::TYPE_HUB));
} else {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_TRANSFER_GENERIC,
"Unknown transfer type", AdcCommand::TYPE_HUB));
}
} else {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_GENERIC,
"Too few parameters for GET", AdcCommand::TYPE_HUB));
}
return;
}
const string& type = c.getParam(0);
string sk, sh;
if(type == "blom" && c.getParam("BK", 4, sk) && c.getParam("BH", 4, sh)) {
ByteVector v;
size_t m = Util::toUInt32(c.getParam(3)) * 8;
size_t k = Util::toUInt32(sk);
size_t h = Util::toUInt32(sh);
if(k > 8 || k < 1) {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_TRANSFER_GENERIC,
"Unsupported k", AdcCommand::TYPE_HUB));
return;
}
if(h > 64 || h < 1) {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_TRANSFER_GENERIC,
"Unsupported h", AdcCommand::TYPE_HUB));
return;
}
size_t n = ShareManager::getInstance()->getSharedFiles();
// Ideal size for m is n * k / ln(2), but we allow some slack
// When h >= 32, m can't go above 2^h anyway since it's stored in a size_t.
if(m > (5 * Util::roundUp((int64_t)(n * k / log(2.)), (int64_t)64)) || (h < 32 && m > static_cast<size_t>(1U << h))) {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_TRANSFER_GENERIC,
"Unsupported m", AdcCommand::TYPE_HUB));
return;
}
if (m > 0) {
ShareManager::getInstance()->getBloom(v, k, m, h);
}
AdcCommand cmd(AdcCommand::CMD_SND, AdcCommand::TYPE_HUB);
cmd.addParam(c.getParam(0));
cmd.addParam(c.getParam(1));
cmd.addParam(c.getParam(2));
cmd.addParam(c.getParam(3));
cmd.addParam(c.getParam(4));
send(cmd);
if (m > 0) {
send((char*)&v[0], v.size());
}
}
}
void AdcHub::handle(AdcCommand::NAT, AdcCommand& c) noexcept {
if(c.getParameters().size() < 3)
return;
OnlineUser* u = findUser(c.getFrom());
if(!u || u->getUser() == ClientManager::getInstance()->getMe())
return;
const string& protocol = c.getParam(0);
const string& port = c.getParam(1);
const string& token = c.getParam(2);
// bool secure = secureAvail(c.getFrom(), protocol, token);
bool secure = false;
if(protocol == CLIENT_PROTOCOL) {
// Nothing special
} else if(protocol == SECURE_CLIENT_PROTOCOL_TEST && CryptoManager::getInstance()->TLSOk()) {
secure = true;
} else {
unknownProtocol(c.getFrom(), protocol, token);
return;
}
// Trigger connection attempt sequence locally ...
auto localPort = Util::toString(sock->getLocalPort());
dcdebug("triggering connecting attempt in NAT: remote port = %s, local port = %d\n", port.c_str(), sock->getLocalPort());
ConnectionManager::getInstance()->adcConnect(*u, port, localPort, BufferedSocket::NAT_CLIENT, token, secure);
// ... and signal other client to do likewise.
send(AdcCommand(AdcCommand::CMD_RNT, u->getIdentity().getSID(), AdcCommand::TYPE_DIRECT).addParam(protocol).
addParam(localPort).addParam(token));
}
void AdcHub::handle(AdcCommand::RNT, AdcCommand& c) noexcept {
if(c.getParameters().size() < 3)
return;
// Sent request for NAT traversal cooperation, which
// was acknowledged (with requisite local port information).
OnlineUser* u = findUser(c.getFrom());
if(!u || u->getUser() == ClientManager::getInstance()->getMe())
return;
const string& protocol = c.getParam(0);
const string& port = c.getParam(1);
const string& token = c.getParam(2);
bool secure = false;
if(protocol == CLIENT_PROTOCOL) {
// Nothing special
} else if(protocol == SECURE_CLIENT_PROTOCOL_TEST && CryptoManager::getInstance()->TLSOk()) {
secure = true;
} else {
unknownProtocol(c.getFrom(), protocol, token);
return;
}
// Trigger connection attempt sequence locally
dcdebug("triggering connecting attempt in RNT: remote port = %s, local port = %d\n", port.c_str(), sock->getLocalPort());
ConnectionManager::getInstance()->adcConnect(*u, port, Util::toString(sock->getLocalPort()), BufferedSocket::NAT_SERVER, token, secure);
}
void AdcHub::handle(AdcCommand::ZON, AdcCommand& c) noexcept {
if(c.getType() == AdcCommand::TYPE_INFO) {
try {
sock->setMode(BufferedSocket::MODE_ZPIPE);
} catch (const Exception& e) {
dcdebug("AdcHub::handleZON failed with error: %s\n", e.getError().c_str());
}
}
}
void AdcHub::handle(AdcCommand::ZOF, AdcCommand& c) noexcept {
if(c.getType() == AdcCommand::TYPE_INFO) {
try {
sock->setMode(BufferedSocket::MODE_LINE);
} catch (const Exception& e) {
dcdebug("AdcHub::handleZOF failed with error: %s\n", e.getError().c_str());
}
}
}
void AdcHub::connect(const OnlineUser& user, const string& token, ConnectionType type) {
connect(user, token, type, CryptoManager::getInstance()->TLSOk() && user.getUser()->isSet(User::TLS));
}
void AdcHub::connect(const OnlineUser& user, const string& token, ConnectionType type, bool secure) {
if(state != STATE_NORMAL)
return;
const string* proto;
if(secure) {
if(user.getUser()->isSet(User::NO_ADCS_0_10_PROTOCOL)) {
/// @todo log
return;
}
proto = &SECURE_CLIENT_PROTOCOL_TEST;
} else {
if(user.getUser()->isSet(User::NO_ADC_1_0_PROTOCOL)) {
/// @todo log
return;
}
proto = &CLIENT_PROTOCOL;
}
ConnectionManager::getInstance()->addToken(token, user, type);
if(ClientManager::getInstance()->isActive()) {
const string& port = secure ? ConnectionManager::getInstance()->getSecurePort() : ConnectionManager::getInstance()->getPort();
if(port.empty()) {
// Oops?
LogManager::getInstance()->message(str(F_("Not listening for connections - please restart %1%") % APPNAME));
return;
}
send(AdcCommand(AdcCommand::CMD_CTM, user.getIdentity().getSID(), AdcCommand::TYPE_DIRECT).addParam(*proto).addParam(port).addParam(token));
} else {
send(AdcCommand(AdcCommand::CMD_RCM, user.getIdentity().getSID(), AdcCommand::TYPE_DIRECT).addParam(*proto).addParam(token));
}
}
void AdcHub::hubMessage(const string& aMessage, bool thirdPerson) {
if(state != STATE_NORMAL)
return;
if(PluginManager::getInstance()->runHook(HOOK_CHAT_OUT, this, aMessage))
return;
AdcCommand c(AdcCommand::CMD_MSG, AdcCommand::TYPE_BROADCAST);
c.addParam(aMessage);
if(thirdPerson)
c.addParam("ME", "1");
send(c);
}
void AdcHub::privateMessage(const OnlineUser& user, const string& aMessage, bool thirdPerson) {
if(state != STATE_NORMAL)
return;
AdcCommand c(AdcCommand::CMD_MSG, user.getIdentity().getSID(), AdcCommand::TYPE_ECHO);
c.addParam(aMessage);
if(thirdPerson)
c.addParam("ME", "1");
c.addParam("PM", getMySID());
send(c);
}
void AdcHub::sendUserCmd(const UserCommand& command, const ParamMap& params) {
if(state != STATE_NORMAL)
return;
string cmd = Util::formatParams(command.getCommand(), params, escape);
if(command.isChat()) {
if(command.getTo().empty()) {
hubMessage(cmd);
} else {
const string& to = command.getTo();
Lock l(cs);
for(auto& i: users) {
if(i.second->getIdentity().getNick() == to) {
privateMessage(*i.second, cmd);
return;
}
}
}
} else {
send(cmd);
}
}
const vector<StringList>& AdcHub::getSearchExts() {
if(!searchExts.empty())
return searchExts;
// the list is always immutable except for this function where it is initially being filled.
auto& xSearchExts = const_cast<vector<StringList>&>(searchExts);
xSearchExts.resize(6);
/// @todo simplify this as searchExts[0] = { "mp3", "etc" } when VC++ supports initializer lists
// these extensions *must* be sorted alphabetically!
{
StringList& l = xSearchExts[0];
l.push_back("ape"); l.push_back("flac"); l.push_back("m4a"); l.push_back("mid");
l.push_back("mp3"); l.push_back("mpc"); l.push_back("ogg"); l.push_back("ra");
l.push_back("wav"); l.push_back("wma");
}
{
StringList& l = xSearchExts[1];
l.push_back("7z"); l.push_back("ace"); l.push_back("arj"); l.push_back("bz2");
l.push_back("gz"); l.push_back("lha"); l.push_back("lzh"); l.push_back("rar");
l.push_back("tar"); l.push_back("z"); l.push_back("zip");
}
{
StringList& l = xSearchExts[2];
l.push_back("doc"); l.push_back("docx"); l.push_back("htm"); l.push_back("html");
l.push_back("nfo"); l.push_back("odf"); l.push_back("odp"); l.push_back("ods");
l.push_back("odt"); l.push_back("pdf"); l.push_back("ppt"); l.push_back("pptx");
l.push_back("rtf"); l.push_back("txt"); l.push_back("xls"); l.push_back("xlsx");
l.push_back("xml"); l.push_back("xps");
}
{
StringList& l = xSearchExts[3];
l.push_back("app"); l.push_back("bat"); l.push_back("cmd"); l.push_back("com");
l.push_back("dll"); l.push_back("exe"); l.push_back("jar"); l.push_back("msi");
l.push_back("ps1"); l.push_back("vbs"); l.push_back("wsf");
}
{
StringList& l = xSearchExts[4];
l.push_back("bmp"); l.push_back("cdr"); l.push_back("eps"); l.push_back("gif");
l.push_back("ico"); l.push_back("img"); l.push_back("jpeg"); l.push_back("jpg");
l.push_back("png"); l.push_back("ps"); l.push_back("psd"); l.push_back("sfw");
l.push_back("tga"); l.push_back("tif"); l.push_back("webp");
}
{
StringList& l = xSearchExts[5];
l.push_back("3gp"); l.push_back("asf"); l.push_back("asx"); l.push_back("avi");
l.push_back("divx"); l.push_back("flv"); l.push_back("mkv"); l.push_back("mov");
l.push_back("mp4"); l.push_back("mpeg"); l.push_back("mpg"); l.push_back("ogm");
l.push_back("pxp"); l.push_back("qt"); l.push_back("rm"); l.push_back("rmvb");
l.push_back("swf"); l.push_back("vob"); l.push_back("webm"); l.push_back("wmv");
}
return searchExts;
}
StringList AdcHub::parseSearchExts(int flag) {
StringList ret;
const auto& searchExts = getSearchExts();
for(auto i = searchExts.cbegin(), ibegin = i, iend = searchExts.cend(); i != iend; ++i) {
if(flag & (1 << (i - ibegin))) {
ret.insert(ret.begin(), i->begin(), i->end());
}
}
return ret;
}
void AdcHub::search(int aSizeMode, int64_t aSize, int aFileType, const string& aString, const string& aToken, const StringList& aExtList) {
if(state != STATE_NORMAL)
return;
AdcCommand c(AdcCommand::CMD_SCH, AdcCommand::TYPE_BROADCAST);
/* token format: [per-hub unique id] "/" [per-search actual token]
this allows easily knowing which hub a search was sent on when parsing a search result,
whithout having to bother maintaining a list of sent tokens. */
c.addParam("TO", Util::toString(getUniqueId()) + "/" + aToken);
if(aFileType == SearchManager::TYPE_TTH) {
c.addParam("TR", aString);
} else {
if(aSizeMode == SearchManager::SIZE_ATLEAST) {
c.addParam("GE", Util::toString(aSize));
} else if(aSizeMode == SearchManager::SIZE_ATMOST) {
c.addParam("LE", Util::toString(aSize));
}
StringTokenizer<string> st(aString, ' ');
for(auto& i: st.getTokens()) {
c.addParam("AN", i);
}
if(aFileType == SearchManager::TYPE_DIRECTORY) {
c.addParam("TY", "2");
}
if(aExtList.size() > 2) {
StringList exts = aExtList;
sort(exts.begin(), exts.end());
uint8_t gr = 0;
StringList rx;
const auto& searchExts = getSearchExts();
for(auto i = searchExts.cbegin(), ibegin = i, iend = searchExts.cend(); i != iend; ++i) {
const StringList& def = *i;
// gather the exts not present in any of the lists
StringList temp(def.size() + exts.size());
temp = StringList(temp.begin(), set_symmetric_difference(def.begin(), def.end(),
exts.begin(), exts.end(), temp.begin()));
// figure out whether the remaining exts have to be added or removed from the set
StringList rx_;
bool ok = true;
for(auto diff = temp.begin(); diff != temp.end();) {
if(find(def.cbegin(), def.cend(), *diff) == def.cend()) {
++diff; // will be added further below as an "EX"
} else {
if(rx_.size() == 2) {
ok = false;
break;
}
rx_.push_back(*diff);
diff = temp.erase(diff);
}
}
if(!ok) // too many "RX"s necessary - disregard this group
continue;
// let's include this group!
gr += 1 << (i - ibegin);
exts = temp; // the exts to still add (that were not defined in the group)
rx.insert(rx.begin(), rx_.begin(), rx_.end());
if(exts.size() <= 2)
break;
// keep looping to see if there are more exts that can be grouped
}
if(gr) {
// some extensions can be grouped; let's send a command with grouped exts.
AdcCommand c_gr(AdcCommand::CMD_SCH, AdcCommand::TYPE_FEATURE);
c_gr.setFeatures('+' + SEGA_FEATURE);
const auto& params = c.getParameters();
for(auto& i: params)
c_gr.addParam(i);
for(auto& i: exts)
c_gr.addParam("EX", i);
c_gr.addParam("GR", Util::toString(gr));
for(auto& i: rx)
c_gr.addParam("RX", i);
sendSearch(c_gr);
// make sure users with the feature don't receive the search twice.
c.setType(AdcCommand::TYPE_FEATURE);
c.setFeatures('-' + SEGA_FEATURE);
}
}
for(auto& i: aExtList)
c.addParam("EX", i);
}
sendSearch(c);
}
void AdcHub::sendSearch(AdcCommand& c) {
if(ClientManager::getInstance()->isActive()) {
send(c);
} else {
c.setType(AdcCommand::TYPE_FEATURE);
string features = c.getFeatures();
c.setFeatures(features + '+' + TCP4_FEATURE + '-' + NAT0_FEATURE);
send(c);
c.setFeatures(features + '+' + NAT0_FEATURE);
send(c);
}
}
void AdcHub::password(const string& pwd) {
if(state != STATE_VERIFY)
return;
if(!salt.empty()) {
size_t saltBytes = salt.size() * 5 / 8;
boost::scoped_array<uint8_t> buf(new uint8_t[saltBytes]);
Encoder::fromBase32(salt.c_str(), &buf[0], saltBytes);
TigerHash th;
if(oldPassword) {
CID cid = getMyIdentity().getUser()->getCID();
th.update(cid.data(), CID::SIZE);
}
th.update(pwd.data(), pwd.length());
th.update(&buf[0], saltBytes);
send(AdcCommand(AdcCommand::CMD_PAS, AdcCommand::TYPE_HUB).addParam(Encoder::toBase32(th.finalize(), TigerHash::BYTES)));
salt.clear();
}
}
static void addParam(StringMap& lastInfoMap, AdcCommand& c, const string& var, const string& value) {
auto i = lastInfoMap.find(var);
if(i != lastInfoMap.end()) {
if(i->second != value) {
if(value.empty()) {
lastInfoMap.erase(i);
} else {
i->second = value;
}
c.addParam(var, value);
}
} else if(!value.empty()) {
lastInfoMap.emplace(var, value);
c.addParam(var, value);
}
}
void AdcHub::infoImpl() {
if(state != STATE_IDENTIFY && state != STATE_NORMAL)
return;
reloadSettings(false);
AdcCommand c(AdcCommand::CMD_INF, AdcCommand::TYPE_BROADCAST);
if (state == STATE_NORMAL) {
updateCounts(false);
}
addParam(lastInfoMap, c, "ID", ClientManager::getInstance()->getMyCID().toBase32());
addParam(lastInfoMap, c, "PD", ClientManager::getInstance()->getMyPID().toBase32());
addParam(lastInfoMap, c, "NI", get(Nick));
addParam(lastInfoMap, c, "DE", get(Description));
addParam(lastInfoMap, c, "SL", Util::toString(SETTING(SLOTS)));
addParam(lastInfoMap, c, "FS", Util::toString(UploadManager::getInstance()->getFreeSlots()));
addParam(lastInfoMap, c, "SS", ShareManager::getInstance()->getShareSizeString());
addParam(lastInfoMap, c, "SF", Util::toString(ShareManager::getInstance()->getSharedFiles()));
addParam(lastInfoMap, c, "EM", get(Email));
addParam(lastInfoMap, c, "HN", Util::toString(counts[COUNT_NORMAL]));
addParam(lastInfoMap, c, "HR", Util::toString(counts[COUNT_REGISTERED]));
addParam(lastInfoMap, c, "HO", Util::toString(counts[COUNT_OP]));
addParam(lastInfoMap, c, "AP", "++");
addParam(lastInfoMap, c, "VE", VERSIONSTRING);
addParam(lastInfoMap, c, "AW", Util::getAway() ? "1" : Util::emptyString);
int limit = ThrottleManager::getInstance()->getDownLimit();
if (limit > 0) {
addParam(lastInfoMap, c, "DS", Util::toString(limit * 1024));
} else {
addParam(lastInfoMap, c, "DS", Util::emptyString);
}
limit = ThrottleManager::getInstance()->getUpLimit();
if (limit > 0) {
addParam(lastInfoMap, c, "US", Util::toString(limit * 1024));
} else {
addParam(lastInfoMap, c, "US", Util::toString((long)(Util::toDouble(SETTING(UPLOAD_SPEED))*1024*1024/8)));
}
addParam(lastInfoMap, c, "LC", Util::getIETFLang());
string su(SEGA_FEATURE);
if(CryptoManager::getInstance()->TLSOk()) {
su += "," + ADCS_FEATURE;
if(SETTING(ENABLE_CCPM)) {
su += "," + CCPM_FEATURE;
}
auto &kp = CryptoManager::getInstance()->getKeyprint();
addParam(lastInfoMap, c, "KP", "SHA256/" + Encoder::toBase32(&kp[0], kp.size()));
}
if(CONNSETTING(NO_IP_OVERRIDE) && !getUserIp().empty()) {
addParam(lastInfoMap, c, "I4", Socket::resolve(getUserIp(), AF_INET));
} else {
addParam(lastInfoMap, c, "I4", "0.0.0.0");
}
if(ClientManager::getInstance()->isActive()) {
addParam(lastInfoMap, c, "U4", SearchManager::getInstance()->getPort());
su += "," + TCP4_FEATURE;
su += "," + UDP4_FEATURE;
} else {
addParam(lastInfoMap, c, "U4", "");
su += "," + NAT0_FEATURE;
}
addParam(lastInfoMap, c, "SU", su);
if(!c.getParameters().empty()) {
send(c);
}
}
int64_t AdcHub::getAvailable() const {
Lock l(cs);
int64_t x = 0;
for(auto& i: users) {
x += i.second->getIdentity().getBytesShared();
}
return x;
}
void AdcHub::checkNick(string& nick) {
for(size_t i = 0, n = nick.size(); i < n; ++i) {
if(static_cast<uint8_t>(nick[i]) <= 32) {
nick[i] = '_';
}
}
}
void AdcHub::send(const AdcCommand& cmd) {
if(forbiddenCommands.find(AdcCommand::toFourCC(cmd.getFourCC().c_str())) == forbiddenCommands.end()) {
if(cmd.getType() == AdcCommand::TYPE_UDP)
sendUDP(cmd);
send(cmd.toString(sid));
}
}
void AdcHub::unknownProtocol(uint32_t target, const string& protocol, const string& token) {
AdcCommand cmd(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_UNSUPPORTED, "Protocol unknown", AdcCommand::TYPE_DIRECT);
cmd.setTo(target);
cmd.addParam("PR", protocol);
cmd.addParam("TO", token);
send(cmd);
}
void AdcHub::on(Connected c) noexcept {
Client::on(c);
if(state != STATE_PROTOCOL) {
return;
}
lastInfoMap.clear();
sid = 0;
forbiddenCommands.clear();
AdcCommand cmd(AdcCommand::CMD_SUP, AdcCommand::TYPE_HUB);
cmd.addParam(BAS0_SUPPORT).addParam(BASE_SUPPORT).addParam(TIGR_SUPPORT);
if(SETTING(HUB_USER_COMMANDS)) {
cmd.addParam(UCM0_SUPPORT);
}
if(SETTING(SEND_BLOOM)) {
cmd.addParam(BLO0_SUPPORT);
}
cmd.addParam(ZLIF_SUPPORT);
send(cmd);
}
void AdcHub::on(Line l, const string& aLine) noexcept {
Client::on(l, aLine);
if(!Text::validateUtf8(aLine)) {
// @todo report to user?
return;
}
if(PluginManager::getInstance()->runHook(HOOK_NETWORK_HUB_IN, this, aLine))
return;
dispatch(aLine);
}
void AdcHub::on(Failed f, const string& aLine) noexcept {
clearUsers();
Client::on(f, aLine);
}
void AdcHub::on(Second s, uint64_t aTick) noexcept {
Client::on(s, aTick);
if(state == STATE_NORMAL && (aTick > (getLastActivity() + 120*1000))) {
send("\n", 1);
}
}
OnlineUserList AdcHub::getUsers() const {
Lock l(cs);
OnlineUserList ret;
ret.reserve(users.size());
for(auto& i: users)
ret.push_back(i.second);
return ret;
}
} // namespace dcpp
|
gpl-2.0
|
NationalLibraryOfNorway/Bibliotekstatistikk
|
old-and-depricated/annualstatistic/src/main/java/no/abmu/abmstatistikk/annualstatistic/finders/report/ReportFinderSpecification.java
|
2848
|
/*$Id: ReportFinderSpecification.java 12340 2008-12-16 14:47:26Z jens $*/
/*
****************************************************************************
* *
* (c) Copyright 2008 ABM-utvikling *
* *
* 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. http://www.gnu.org/licenses/gpl.html *
* *
****************************************************************************
*/
package no.abmu.abmstatistikk.annualstatistic.finders.report;
import java.util.Date;
import no.abmu.util.test.Assert;
/**
* This is a finder for returning ....
* annualstatistic.
*
* @author Jens Vindvad, Jens.Vindvad@abm-utvikling.no
* @author $Author: jens $
* @version $Rev: 12340 $
* $Date: 2008-12-16 15:47:26 +0100 (Tue, 16 Dec 2008) $
* copyright ABM-Utvikling
* @since 2008-10-03
*/
public class ReportFinderSpecification extends
AbstractH2ReportFinderSpecification {
public static final String HQL_SELECT = "SELECT report,field ";
public static final String CACHE_REGION = "fromReportAnnualstatisticCache";
public ReportFinderSpecification() {
this(new ReportFinderSpecificationBean());
}
public ReportFinderSpecification(Long organisationUnitId, String schemaShortName, Date startDate, Date stopDate) {
this(new ReportFinderSpecificationBean());
Assert.checkRequiredArgument("organisationUnitId", organisationUnitId);
Assert.checkRequiredArgument("schemaShortName", schemaShortName);
Assert.checkRequiredArgument("startDate", startDate);
Assert.checkRequiredArgument("stopDate", stopDate);
setOrganisationUnitId(organisationUnitId);
setSchemaShortName(schemaShortName);
setStartDate(startDate);
setStopDate(stopDate);
}
public ReportFinderSpecification(ReportFinderSpecificationBean reportFinderSpecificationBean) {
super(reportFinderSpecificationBean);
setSelect(HQL_SELECT);
setCacheRegion(CACHE_REGION);
}
}
|
gpl-2.0
|
RyMarq/Zero-K
|
gamedata/modularcomms/weapons/missilelauncher.lua
|
1384
|
local name = "commweapon_missilelauncher"
local weaponDef = {
name = [[Missile Launcher]],
areaOfEffect = 48,
avoidFeature = true,
cegTag = [[missiletrailyellow]],
craterBoost = 1,
craterMult = 2,
customParams = {
is_unit_weapon = 1,
slot = [[5]],
muzzleEffectFire = [[custom:SLASHMUZZLE]],
light_camera_height = 2000,
light_radius = 200,
reaim_time = 1,
},
damage = {
default = 80,
subs = 4,
},
explosionGenerator = [[custom:FLASH2]],
fireStarter = 70,
flightTime = 3,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 2,
model = [[wep_m_frostshard.s3o]],
noSelfDamage = true,
range = 415,
reloadtime = 1,
smokeTrail = true,
soundHit = [[explosion/ex_med17]],
soundStart = [[weapon/missile/missile_fire11]],
startVelocity = 450,
texture2 = [[lightsmoketrail]],
tolerance = 8000,
tracks = true,
turnRate = 33000,
turret = true,
weaponAcceleration = 109,
weaponType = [[MissileLauncher]],
weaponVelocity = 545,
}
return name, weaponDef
|
gpl-2.0
|
ePubViet/epubweb
|
plugins/system/juxcomingsoon/elements/assets/js/juxoptions.js
|
4971
|
/**
* @version $id: $
* @author JoomlaUX!
* @package Joomla!
* @subpackage plg_system_juxcomingsoon
* @copyright Copyright (C) 2012 - 2014 by Joomlaux. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL version 3, See LICENSE.txt
*/
/**
* Toggle show/hide sub fields of a field list.
*
*/
function jux_ToggleOptions(field_list) {
if(field_list == undefined || (/^\s*$/).test(field_list)) {
return;
}
var fields = field_list.split(',');
fields = jux_CleanArray(fields);
for(var i = 0; i < fields.length; i ++){
if((/^\s*$/).test(fields[i])) {
continue;
}
jux_ToggleOption(fields[i]);
}
}
/**
* Function of jux radio field for toggle show/hide sub fields.
*
* @param string field_id The id of the control field.
*/
function jux_ToggleOption(field_id) {
if((/^\s*$/).test(field_id)) {
return;
}
var control_field = jux_GetField(field_id);
if(control_field == undefined) {
return;
}
// Check is hiding
if(jux_IsHidding(control_field)) {
return;
}
// Hide all sub fields, sub-fields of sub-fields are included.
var all_sub_fields = control_field.data('all_sub_fields');
jux_HideOptions(all_sub_fields);
// Get active sub fields
var active_sub_fields = jux_GetActiveSubfields(control_field);
jux_ShowOptions(active_sub_fields);
// repeate toggle option with sub-fields
jux_ToggleOptions(active_sub_fields)
}
/**
* Get the active option from a control field.
*/
function jux_GetActiveSubfields(control_field) {
var active_option = undefined;
// Check if it's radio list
if(control_field.is("fieldset")) {
active_option = control_field.find('input:radio:checked');
}
// Check if it's dropdown list
if (control_field.is("select")) {
active_option = control_field.find("option:selected");
}
if(active_option == undefined || active_option == null) {
return '';
}
var active_sub_fields = [];
active_option.each(function() {
var $this = jQuery(this);
var sub_field = $this.data('sub_fields');
if(sub_field != undefined && sub_field != null && sub_field != '') {
active_sub_fields.push(sub_field);
}
});
return active_sub_fields.join(",");
}
/**
* Function for hide options.
*
* @param array sub_fields The list of fields to Hide.
*/
function jux_HideOptions(sub_fields) {
if(sub_fields == undefined || (/^\s*$/).test(sub_fields)) {
return;
}
var fields = sub_fields.split(',');
fields = jux_CleanArray(fields);
for(var i = 0; i < fields.length; i ++){
jux_HideOption(fields[i]);
}
}
/**
* Function for show options.
*
* @param array sub_fields The list of fields to Show.
*/
function jux_ShowOptions(sub_fields) {
if(sub_fields == undefined || (/^\s*$/).test(sub_fields)) {
return;
}
var fields = sub_fields.split(',');
fields = jux_CleanArray(fields);
for(var i = 0; i < fields.length; i ++){
if((/^\s*$/).test(fields[i])) {
continue;
}
jux_ShowOption(fields[i]);
}
}
/**
* Function for Show one options
*
* @param string field_name Name of Field to show.
*/
function jux_ShowOption(field_id) {
var field = jux_GetField(field_id);
if(field == undefined || field == null) {
return;
}
// Check if it is already shown
if(!jux_IsHidding(field)) {
return;
}
// Get wrapper control
var control = jux_GetWrapperControl(field);
// Show
if(control !== undefined && control != null) {
control.removeClass('hide');
}
}
/**
* Function for Hide one options
*
* @param field_id Name of Field to hide.
*/
function jux_HideOption(field_id) {
var field = jux_GetField(field_id);
if(field == undefined || field == null) {
return;
}
// Check if it is already hidden
if(jux_IsHidding(field)) {
return;
}
// Get wrapper control
var control = jux_GetWrapperControl(field);
// Hide
if(control !== undefined && control != null) {
control.addClass('hide');
// Also hide all sub-fields
jux_HideOptions(field.data('all_sub_fields'));
}
}
/**
* Get wrapper control
*
* @param field Current field.
*/
function jux_GetWrapperControl (field) {
// Joomla 3.0
var control = field.closest('div.control-group');
// Joomla 2.5 field
if(control == undefined || control == null || control.length == 0) {
control = field.closest('li');
}
return control;
}
/**
* Check if current field is hidding or not.
*
* @param field Current field
*/
function jux_IsHidding(field) {
var wrapper = jux_GetWrapperControl(field);
if(wrapper == undefined || wrapper == null || wrapper.hasClass("hide")) {
return true;
}
return false;
}
function jux_GetField(field_id) {
var field = jQuery('#' + field_id);
if(field == undefined || field == null) {
field = jQuery('#' + field_id + '-lbl');
}
return field;
}
function jux_CleanArray(arrayObjects) {
var uniqueObjects = [];
jQuery.each(arrayObjects, function(i, el){
if(jQuery.inArray(el, uniqueObjects) === -1 && !(/^\s*$/).test(el)) uniqueObjects.push(el);
});
return uniqueObjects;
}
|
gpl-2.0
|
iucn-whp/world-heritage-outlook
|
portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/model/flagship_species_lkpClp.java
|
6361
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.iucn.whp.dbservice.model;
import com.iucn.whp.dbservice.service.flagship_species_lkpLocalServiceUtil;
import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.model.BaseModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import java.io.Serializable;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
/**
* @author alok.sen
*/
public class flagship_species_lkpClp extends BaseModelImpl<flagship_species_lkp>
implements flagship_species_lkp {
public flagship_species_lkpClp() {
}
public Class<?> getModelClass() {
return flagship_species_lkp.class;
}
public String getModelClassName() {
return flagship_species_lkp.class.getName();
}
public int getPrimaryKey() {
return _flagship_species_id;
}
public void setPrimaryKey(int primaryKey) {
setFlagship_species_id(primaryKey);
}
public Serializable getPrimaryKeyObj() {
return new Integer(_flagship_species_id);
}
public void setPrimaryKeyObj(Serializable primaryKeyObj) {
setPrimaryKey(((Integer)primaryKeyObj).intValue());
}
@Override
public Map<String, Object> getModelAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("flagship_species_id", getFlagship_species_id());
attributes.put("flagship_species_name", getFlagship_species_name());
attributes.put("redlist_url", getRedlist_url());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
Integer flagship_species_id = (Integer)attributes.get(
"flagship_species_id");
if (flagship_species_id != null) {
setFlagship_species_id(flagship_species_id);
}
String flagship_species_name = (String)attributes.get(
"flagship_species_name");
if (flagship_species_name != null) {
setFlagship_species_name(flagship_species_name);
}
String redlist_url = (String)attributes.get("redlist_url");
if (redlist_url != null) {
setRedlist_url(redlist_url);
}
}
public int getFlagship_species_id() {
return _flagship_species_id;
}
public void setFlagship_species_id(int flagship_species_id) {
_flagship_species_id = flagship_species_id;
}
public String getFlagship_species_name() {
return _flagship_species_name;
}
public void setFlagship_species_name(String flagship_species_name) {
_flagship_species_name = flagship_species_name;
}
public String getRedlist_url() {
return _redlist_url;
}
public void setRedlist_url(String redlist_url) {
_redlist_url = redlist_url;
}
public BaseModel<?> getflagship_species_lkpRemoteModel() {
return _flagship_species_lkpRemoteModel;
}
public void setflagship_species_lkpRemoteModel(
BaseModel<?> flagship_species_lkpRemoteModel) {
_flagship_species_lkpRemoteModel = flagship_species_lkpRemoteModel;
}
public void persist() throws SystemException {
if (this.isNew()) {
flagship_species_lkpLocalServiceUtil.addflagship_species_lkp(this);
}
else {
flagship_species_lkpLocalServiceUtil.updateflagship_species_lkp(this);
}
}
@Override
public flagship_species_lkp toEscapedModel() {
return (flagship_species_lkp)Proxy.newProxyInstance(flagship_species_lkp.class.getClassLoader(),
new Class[] { flagship_species_lkp.class },
new AutoEscapeBeanHandler(this));
}
@Override
public Object clone() {
flagship_species_lkpClp clone = new flagship_species_lkpClp();
clone.setFlagship_species_id(getFlagship_species_id());
clone.setFlagship_species_name(getFlagship_species_name());
clone.setRedlist_url(getRedlist_url());
return clone;
}
public int compareTo(flagship_species_lkp flagship_species_lkp) {
int primaryKey = flagship_species_lkp.getPrimaryKey();
if (getPrimaryKey() < primaryKey) {
return -1;
}
else if (getPrimaryKey() > primaryKey) {
return 1;
}
else {
return 0;
}
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
flagship_species_lkpClp flagship_species_lkp = null;
try {
flagship_species_lkp = (flagship_species_lkpClp)obj;
}
catch (ClassCastException cce) {
return false;
}
int primaryKey = flagship_species_lkp.getPrimaryKey();
if (getPrimaryKey() == primaryKey) {
return true;
}
else {
return false;
}
}
@Override
public int hashCode() {
return getPrimaryKey();
}
@Override
public String toString() {
StringBundler sb = new StringBundler(7);
sb.append("{flagship_species_id=");
sb.append(getFlagship_species_id());
sb.append(", flagship_species_name=");
sb.append(getFlagship_species_name());
sb.append(", redlist_url=");
sb.append(getRedlist_url());
sb.append("}");
return sb.toString();
}
public String toXmlString() {
StringBundler sb = new StringBundler(13);
sb.append("<model><model-name>");
sb.append("com.iucn.whp.dbservice.model.flagship_species_lkp");
sb.append("</model-name>");
sb.append(
"<column><column-name>flagship_species_id</column-name><column-value><![CDATA[");
sb.append(getFlagship_species_id());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>flagship_species_name</column-name><column-value><![CDATA[");
sb.append(getFlagship_species_name());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>redlist_url</column-name><column-value><![CDATA[");
sb.append(getRedlist_url());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
private int _flagship_species_id;
private String _flagship_species_name;
private String _redlist_url;
private BaseModel<?> _flagship_species_lkpRemoteModel;
}
|
gpl-2.0
|
dlitz/resin
|
modules/kernel/src/com/caucho/config/gen/CacheGenerator.java
|
4720
|
/*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.config.gen;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import javax.cache.annotation.CacheResult;
import javax.ejb.MessageDriven;
import javax.ejb.SessionSynchronization;
import javax.ejb.Singleton;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import com.caucho.inject.Module;
import com.caucho.java.JavaWriter;
/**
* Represents the XA interception
*/
@Module
public class CacheGenerator<X> extends AbstractAspectGenerator<X> {
private CacheResult _cache;
private String _cacheName;
private String _cacheInstance;
public CacheGenerator(CacheFactory<X> factory,
AnnotatedMethod<? super X> method,
AspectGenerator<X> next,
CacheResult cache)
{
super(factory, method, next);
_cache = cache;
_cacheName = _cache.cacheName();
if ("".equals(_cacheName)) {
Method javaMethod = method.getJavaMember();
_cacheName = (javaMethod.getDeclaringClass().getName()
+ "." + javaMethod.getName());
}
}
//
// bean prologue generation
//
/**
* Generates the static class prologue
*/
@Override
public void generateMethodPrologue(JavaWriter out, HashMap<String, Object> map)
throws IOException
{
super.generateMethodPrologue(out, map);
if (map.get("caucho.candi.cachemanager") == null) {
map.put("caucho.candi.cachemanager", "done");
out.println();
out.println("private static final com.caucho.distcache.ClusterCacheManagerDelegate _cacheManager");
out.println(" = com.caucho.distcache.ClusterCacheManagerDelegate.create();");
}
_cacheInstance = "__caucho_cache_" + out.generateId();
out.println();
out.println("private static final javax.cache.Cache " + _cacheInstance);
out.print(" = _cacheManager.getCache(\"");
out.printJavaString(_cacheName);
out.print("\");");
}
//
// method generation code
//
/**
* Generates the interceptor code after the try-block and before the call.
*
* <code><pre>
* retType myMethod(...)
* {
* try {
* [pre-call]
* retValue = super.myMethod(...);
* }
* </pre></code>
*/
@Override
public void generatePreCall(JavaWriter out) throws IOException
{
out.println();
out.println("com.caucho.config.util.CacheKey candiCacheKey");
out.print(" = new com.caucho.config.util.CacheKey(");
List params = getMethod().getParameters();
for (int i = 0; i < params.size(); i++) {
if (i != 0)
out.print(", ");
out.print("a" + i);
}
out.println(");");
out.println("Object cacheValue = " + _cacheInstance + ".get(candiCacheKey);");
out.println("if (cacheValue != null) {");
out.print("return (");
out.printClass(getJavaMethod().getReturnType());
out.print(") cacheValue;");
out.println("}");
super.generatePreCall(out);
}
/**
* Generates the interceptor code after invocation and before the call.
*
* <code><pre>
* retType myMethod(...)
* {
* try {
* retValue = super.myMethod(...);
* [post-call]
* return retValue;
* } finally {
* ...
* }
* }
* </pre></code>
*/
@Override
public void generatePostCall(JavaWriter out) throws IOException
{
super.generatePostCall(out);
out.println(_cacheInstance + ".put(candiCacheKey, result);");
}
}
|
gpl-2.0
|
BruceWayneLin/mittag
|
admin/language/zh-TW/extension/module/store.php
|
367
|
<?php
// Heading
$_['heading_title'] = '多商店切換';
// Text
$_['text_extension'] = '模組';
$_['text_success'] = '更新成功';
$_['text_edit'] = '編輯';
// Entry
$_['entry_admin'] = '僅適用於後台管理員';
$_['entry_status'] = '狀態';
// Error
$_['error_permission'] = '您沒有權限更改此模組的設置!';
|
gpl-2.0
|
LaurentLeeJS/Laurent.Lee.Framework
|
Laurent.Lee.CLB.Ex/Win32/SafeHandles/TmphSafeMemoryMappedFileHandle.cs
|
2545
|
/*
-------------------------------------------------- -----------------------------------------
The frame content is protected by copyright law. In order to facilitate individual learning,
allows to download the program source information, but does not allow individuals or a third
party for profit, the commercial use of the source information. Without consent,
does not allow any form (even if partial, or modified) database storage,
copy the source of information. If the source content provided by third parties,
which corresponds to the third party content is also protected by copyright.
If you are found to have infringed copyright behavior, please give me a hint. THX!
Here in particular it emphasized that the third party is not allowed to contact addresses
published in this "version copyright statement" to send advertising material.
I will take legal means to resist sending spam.
-------------------------------------------------- ----------------------------------------
The framework under the GNU agreement, Detail View GNU License.
If you think about this item affection join the development team,
Please contact me: LaurentLeeJS@gmail.com
-------------------------------------------------- ----------------------------------------
Laurent.Lee.Framework Coded by Laurent Lee
*/
using Microsoft.Win32.SafeHandles;
using System;
using System.Security.Permissions;
namespace Laurent.Lee.CLB.Win32.SafeHandles
{
/// <summary>
/// 内存映射文件
/// </summary>
//[SecurityCritical(SecurityCriticalScope.Everything)]
public sealed class TmphSafeMemoryMappedFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// 内存映射文件
/// </summary>
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public TmphSafeMemoryMappedFileHandle() : base(true) { }
/// <summary>
/// 内存映射文件
/// </summary>
/// <param name="existingHandle">内存句柄</param>
/// <param name="ownsHandle">是否拥有句柄</param>
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public TmphSafeMemoryMappedFileHandle(IntPtr handle, bool ownsHandle)
: base(ownsHandle)
{ base.SetHandle(handle); }
/// <summary>
/// 释放句柄
/// </summary>
/// <returns>是否成功</returns>
protected override bool ReleaseHandle()
{
return TmphKernel32.CloseHandle(base.handle);
}
}
}
|
gpl-2.0
|
knowlp/CoreNLP
|
src/edu/stanford/nlp/ling/tokensregex/CoreMapExpressionExtractor.java
|
19137
|
package edu.stanford.nlp.ling.tokensregex;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.tokensregex.parser.ParseException;
import edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser;
import edu.stanford.nlp.ling.tokensregex.types.Expression;
import edu.stanford.nlp.ling.tokensregex.types.Tags;
import edu.stanford.nlp.ling.tokensregex.types.Value;
import edu.stanford.nlp.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <p>Represents a list of assignment and extraction rules over sequence patterns.
* See {@link SequenceMatchRules} for syntax of rules.
* </p>
*
* <p>Assignment rules are used to assign a value to a variable for later use in
* extraction rules or for expansions in patterns.</p>
* <p>Extraction rules are used to extract text/tokens matching regular expressions.
* Extraction rules are grouped into stages, with each stage consisting of the following:
* <ol>
* <li>Matching of rules over <b>text</b> and <b>tokens</b>. These rules are applied directly on the <b>text</b> and <b>tokens</b> fields of the <code>CoreMap</code>.</li>
* <li>Matching of <b>composite</b> rules. Matched expression are merged, and composite rules
* are applied recursively until no more changes to the matched expressions are detected.</li>
* <li><b>Filtering</b> of an invalid expression. In the final phase, a final filtering stage filters out invalid expressions.</li>
* </ol>
* The different stages are numbered and are applied in numeric order.
* </p>
*
* @author Angel Chang
* @see SequenceMatchRules
*/
public class CoreMapExpressionExtractor<T extends MatchedExpression> {
// TODO: Remove templating of MatchedExpressions<?> (keep for now until TimeExpression rules can be decoupled)
private Logger logger = Logger.getLogger(CoreMapExpressionExtractor.class.getName());
private final Env env;
/* Keeps temporary tags created by extractor */
private boolean keepTags = false;
private final Class tokensAnnotationKey;
private final Map<Integer, Stage<T>> stages;
/**
* Describes one stage of extraction.
* @param <T>
*/
public static class Stage<T> {
/** Whether to clear matched expressions from previous stages or not */
boolean clearMatched = false;
/**
* Limit the number of iterations for which the composite rules are applied
* (prevents badly formed rules from iterating forever)
*/
int limitIters = 50;
/**
* Stage id (stages are applied in numeric order from low to high)
*/
int stageId;
/** Rules to extract matched expressions directly from tokens */
SequenceMatchRules.ExtractRule<CoreMap, T> basicExtractRule;
/** Rules to extract composite expressions (grouped in stages) */
SequenceMatchRules.ExtractRule<List<? extends CoreMap>, T> compositeExtractRule;
/** Filtering rule */
Predicate<T> filterRule;
private static <I,O> SequenceMatchRules.ExtractRule<I,O> addRule(SequenceMatchRules.ExtractRule<I, O> origRule,
SequenceMatchRules.ExtractRule<I, O> rule)
{
SequenceMatchRules.ListExtractRule<I,O> r;
if (origRule instanceof SequenceMatchRules.ListExtractRule) {
r = (SequenceMatchRules.ListExtractRule<I,O>) origRule;
} else {
r = new SequenceMatchRules.ListExtractRule<I,O>();
if (origRule != null)
r.addRules(origRule);
}
r.addRules(rule);
return r;
}
private void addCompositeRule(SequenceMatchRules.ExtractRule<List<? extends CoreMap>, T> rule)
{
compositeExtractRule = addRule(compositeExtractRule, rule);
}
private void addBasicRule(SequenceMatchRules.ExtractRule<CoreMap, T> rule)
{
basicExtractRule = addRule(basicExtractRule, rule);
}
private void addFilterRule(Predicate<T> rule)
{
Filters.DisjFilter<T> r;
if (filterRule instanceof Filters.DisjFilter) {
r = (Filters.DisjFilter<T>) filterRule;
r.addFilter(rule);
} else {
if (filterRule == null) {
r = new Filters.DisjFilter<T>(rule);
} else {
r = new Filters.DisjFilter<T>(filterRule, rule);
}
filterRule = r;
}
}
}
/**
* Creates an empty instance with no rules.
*/
public CoreMapExpressionExtractor() {
this(null);
}
/**
* Creates a default instance with the specified environment.
* (use the default tokens annotation key as specified in the environment)
* @param env Environment to use for binding variables and applying rules
*/
public CoreMapExpressionExtractor(Env env) {
this.stages = new HashMap<Integer, Stage<T>>();//Generics.newHashMap();
this.env = env;
this.tokensAnnotationKey = EnvLookup.getDefaultTokensAnnotationKey(env);
}
/**
* Creates an instance with the specified environment and list of rules
* @param env Environment to use for binding variables and applying rules
* @param rules List of rules for this extractor
*/
public CoreMapExpressionExtractor(Env env, List<SequenceMatchRules.Rule> rules) {
this(env);
appendRules(rules);
}
/**
* Add specified rules to this extractor
* @param rules
*/
public void appendRules(List<SequenceMatchRules.Rule> rules)
{
// Put rules into stages
for (SequenceMatchRules.Rule r:rules) {
if (r instanceof SequenceMatchRules.AssignmentRule) {
// Nothing to do
// Assignments are added to environment as they are parsed
((SequenceMatchRules.AssignmentRule) r).evaluate(env);
} else if (r instanceof SequenceMatchRules.AnnotationExtractRule) {
SequenceMatchRules.AnnotationExtractRule aer = (SequenceMatchRules.AnnotationExtractRule) r;
Stage<T> stage = stages.get(aer.stage);
if (stage == null) {
stages.put(aer.stage, stage = new Stage<T>());
stage.stageId = aer.stage;
Boolean clearMatched = (Boolean) env.getDefaults().get("stage.clearMatched");
if (clearMatched != null) {
stage.clearMatched = clearMatched;
}
Integer limitIters = (Integer) env.getDefaults().get("stage.limitIters");
if (limitIters != null) {
stage.limitIters = limitIters;
}
}
if (aer.active) {
if (SequenceMatchRules.FILTER_RULE_TYPE.equals(aer.ruleType)) {
stage.addFilterRule(aer);
} else {
if (aer.isComposite) {
// if (SequenceMatchRules.COMPOSITE_RULE_TYPE.equals(aer.ruleType)) {
stage.addCompositeRule(aer);
} else {
stage.addBasicRule(aer);
}
}
} else {
logger.log(Level.INFO, "Ignoring inactive rule: " + aer.name);
}
}
}
}
public Env getEnv() {
return env;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
public void setExtractRules(SequenceMatchRules.ExtractRule<CoreMap, T> basicExtractRule,
SequenceMatchRules.ExtractRule<List<? extends CoreMap>, T> compositeExtractRule,
Predicate<T> filterRule)
{
Stage<T> stage = new Stage<T>();
stage.basicExtractRule = basicExtractRule;
stage.compositeExtractRule = compositeExtractRule;
stage.filterRule = filterRule;
this.stages.clear();
this.stages.put(1, stage);
}
/**
* Creates an extractor using the specified environment, and reading the rules from the given filenames
* @param env
* @param filenames
* @throws RuntimeException
*/
public static CoreMapExpressionExtractor createExtractorFromFiles(Env env, String... filenames) throws RuntimeException {
return createExtractorFromFiles(env, Arrays.asList(filenames));
}
/**
* Creates an extractor using the specified environment, and reading the rules from the given filenames.
* @param env
* @param filenames
* @throws RuntimeException
*/
public static CoreMapExpressionExtractor createExtractorFromFiles(Env env, List<String> filenames) throws RuntimeException {
CoreMapExpressionExtractor extractor = new CoreMapExpressionExtractor(env);
for (String filename:filenames) {
try {
System.err.println("Reading TokensRegex rules from " + filename);
BufferedReader br = IOUtils.getBufferedReaderFromClasspathOrFileSystem(filename);
TokenSequenceParser parser = new TokenSequenceParser();
parser.updateExpressionExtractor(extractor, br);
IOUtils.closeIgnoringExceptions(br);
} catch (Exception ex) {
throw new RuntimeException("Error parsing file: " + filename, ex);
}
}
return extractor;
}
/**
* Creates an extractor using the specified environment, and reading the rules from the given filename.
* @param env
* @param filename
* @throws RuntimeException
*/
public static CoreMapExpressionExtractor createExtractorFromFile(Env env, String filename) throws RuntimeException {
try {
System.err.println("Reading TokensRegex rules from " + filename);
BufferedReader br = IOUtils.getBufferedReaderFromClasspathOrFileSystem(filename);
TokenSequenceParser parser = new TokenSequenceParser();
CoreMapExpressionExtractor extractor = parser.getExpressionExtractor(env, br);
IOUtils.closeIgnoringExceptions(br);
return extractor;
} catch (Exception ex) {
throw new RuntimeException("Error parsing file: " + filename, ex);
}
}
/**
* Creates an extractor using the specified environment, and reading the rules from the given string
* @param env
* @param str
* @throws IOException, ParseException
*/
public static CoreMapExpressionExtractor createExtractorFromString(Env env, String str) throws IOException, ParseException {
TokenSequenceParser parser = new TokenSequenceParser();
CoreMapExpressionExtractor extractor = parser.getExpressionExtractor(env, new StringReader(str));
return extractor;
}
public Value getValue(String varname)
{
Expression expr = (Expression) env.get(varname);
if (expr != null) {
return expr.evaluate(env);
} else {
throw new RuntimeException("Unable get expression for variable " + varname);
}
}
public List<CoreMap> extractCoreMapsToList(List<CoreMap> res, CoreMap annotation)
{
List<T> exprs = extractExpressions(annotation);
for (T expr:exprs) {
res.add(expr.getAnnotation());
}
return res;
}
/**
* Returns list of coremaps that matches the specified rules
* @param annotation
*/
public List<CoreMap> extractCoreMaps(CoreMap annotation)
{
List<CoreMap> res = new ArrayList<CoreMap>();
return extractCoreMapsToList(res, annotation);
}
/**
* Returns list of merged tokens and original tokens
* @param annotation
*/
public List<CoreMap> extractCoreMapsMergedWithTokens(CoreMap annotation)
{
List<CoreMap> res = extractCoreMaps(annotation);
Integer startTokenOffset = annotation.get(CoreAnnotations.TokenBeginAnnotation.class);
if (startTokenOffset == null) {
startTokenOffset = 0;
}
final Integer startTokenOffsetFinal = startTokenOffset;
List<CoreMap> merged = CollectionUtils.mergeListWithSortedMatchedPreAggregated(
(List<CoreMap>) annotation.get(tokensAnnotationKey), res, in -> Interval.toInterval(in.get(CoreAnnotations.TokenBeginAnnotation.class) - startTokenOffsetFinal,
in.get(CoreAnnotations.TokenEndAnnotation.class) - startTokenOffsetFinal)
);
return merged;
}
public List<CoreMap> flatten(List<CoreMap> cms) {
return flatten(cms, tokensAnnotationKey);
}
static List<CoreMap> flatten(List<CoreMap> cms, Class key) {
List<CoreMap> res = new ArrayList<CoreMap>();
for (CoreMap cm:cms) {
if (cm.get(key) != null) {
res.addAll( (List<CoreMap>) cm.get(key));
} else {
res.add(cm);
}
}
return res;
}
private void cleanupTags(Collection objs, Map<Object, Boolean> cleaned) {
for (Object obj:objs) {
if (!cleaned.containsKey(obj)) {
cleaned.put(obj, false);
if (obj instanceof CoreMap) {
cleanupTags((CoreMap) obj, cleaned);
} else if (obj instanceof Collection) {
cleanupTags((Collection) obj, cleaned);
}
cleaned.put(obj, true);
}
}
}
private void cleanupTags(CoreMap cm) {
cleanupTags(cm, new IdentityHashMap<Object, Boolean>());
}
private void cleanupTags(CoreMap cm, Map<Object, Boolean> cleaned) {
cm.remove(Tags.TagsAnnotation.class);
for (Class key:cm.keySet()) {
Object obj = cm.get(key);
if (!cleaned.containsKey(obj)) {
cleaned.put(obj, false);
if (obj instanceof CoreMap) {
cleanupTags((CoreMap) obj, cleaned);
} else if (obj instanceof Collection) {
cleanupTags((Collection) obj, cleaned);
}
cleaned.put(obj, true);
}
}
}
public Pair<List<? extends CoreMap>, List<T>> applyCompositeRule(
SequenceMatchRules.ExtractRule<List<? extends CoreMap>, T> compositeExtractRule,
List<? extends CoreMap> merged,
List<T> matchedExpressions, int limit)
{
// Apply higher order rules
boolean done = false;
// Limit of number of times rules are applied just in case
int maxIters = limit;
int iters = 0;
while (!done) {
List<T> newExprs = new ArrayList<T>();
boolean extracted = compositeExtractRule.extract(merged, newExprs);
if (extracted) {
annotateExpressions(merged, newExprs);
newExprs = MatchedExpression.removeNullValues(newExprs);
if (newExprs.size() > 0) {
newExprs = MatchedExpression.removeNested(newExprs);
newExprs = MatchedExpression.removeOverlapping(newExprs);
merged = MatchedExpression.replaceMerged(merged, newExprs);
// Favor newly matched expressions over older ones
newExprs.addAll(matchedExpressions);
matchedExpressions = MatchedExpression.removeNested(newExprs);
matchedExpressions = MatchedExpression.removeOverlapping(matchedExpressions);
} else {
extracted = false;
}
}
done = !extracted;
iters++;
if (maxIters > 0 && iters >= maxIters) {
logger.warning("Aborting application of composite rules: Maximum iteration " + maxIters + " reached");
break;
}
}
return new Pair<List<? extends CoreMap>, List<T>>(merged, matchedExpressions);
}
private static class CompositeMatchState<T> {
List<? extends CoreMap> merged;
List<T> matched;
int iters;
private CompositeMatchState(List<? extends CoreMap> merged, List<T> matched, int iters) {
this.merged = merged;
this.matched = matched;
this.iters = iters;
}
}
public List<T> extractExpressions(CoreMap annotation)
{
// Extract potential expressions
List<T> matchedExpressions = new ArrayList<T>();
List<Integer> stageIds = new ArrayList<Integer>(stages.keySet());
Collections.sort(stageIds);
for (int stageId:stageIds) {
Stage<T> stage = stages.get(stageId);
SequenceMatchRules.ExtractRule<CoreMap, T> basicExtractRule = stage.basicExtractRule;
if (stage.clearMatched) {
matchedExpressions.clear();
}
if (basicExtractRule != null) {
basicExtractRule.extract(annotation, matchedExpressions);
annotateExpressions(annotation, matchedExpressions);
matchedExpressions = MatchedExpression.removeNullValues(matchedExpressions);
matchedExpressions = MatchedExpression.removeNested(matchedExpressions);
matchedExpressions = MatchedExpression.removeOverlapping(matchedExpressions);
}
List<? extends CoreMap> merged = MatchedExpression.replaceMergedUsingTokenOffsets((List<? extends CoreMap>) annotation.get(tokensAnnotationKey), matchedExpressions);
SequenceMatchRules.ExtractRule<List<? extends CoreMap>, T> compositeExtractRule = stage.compositeExtractRule;
if (compositeExtractRule != null) {
Pair<List<? extends CoreMap>, List<T>> p = applyCompositeRule(
compositeExtractRule, merged, matchedExpressions, stage.limitIters);
merged = p.first();
matchedExpressions = p.second();
}
matchedExpressions = filterInvalidExpressions(stage.filterRule, matchedExpressions);
}
Collections.sort(matchedExpressions, MatchedExpression.EXPR_TOKEN_OFFSETS_NESTED_FIRST_COMPARATOR);
if (!keepTags) {
cleanupTags(annotation);
}
return matchedExpressions;
}
private void annotateExpressions(CoreMap annotation, List<T> expressions)
{
// TODO: Logging can be excessive
List<MatchedExpression> toDiscard = new ArrayList<MatchedExpression>();
for (MatchedExpression te:expressions) {
// Add attributes and all
if (te.annotation == null) {
try {
boolean extrackOkay = te.extractAnnotation(env, annotation);
if (!extrackOkay) {
// Things didn't turn out so well
toDiscard.add(te);
logger.log(Level.WARNING, "Error extracting annotation from " + te /*+ ", " + te.getExtractErrorMessage() */);
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Error extracting annotation from " + te, ex);
}
}
}
expressions.removeAll(toDiscard);
}
private void annotateExpressions(List<? extends CoreMap> chunks, List<T> expressions)
{
// TODO: Logging can be excessive
List<MatchedExpression> toDiscard = new ArrayList<MatchedExpression>();
for (MatchedExpression te:expressions) {
// Add attributes and all
try {
boolean extractOkay = te.extractAnnotation(env, chunks);
if (!extractOkay) {
// Things didn't turn out so well
toDiscard.add(te);
logger.log(Level.WARNING, "Error extracting annotation from " + te /*+ ", " + te.getExtractErrorMessage() */);
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Error extracting annotation from " + te, ex);
}
}
expressions.removeAll(toDiscard);
}
private List<T> filterInvalidExpressions(Predicate<T> filterRule, List<T> expressions)
{
if (filterRule == null) return expressions;
if (expressions.size() == 0) return expressions;
int nfiltered = 0;
List<T> kept = new ArrayList<T>(expressions.size()); // Approximate size
for (T expr:expressions) {
if (!filterRule.test(expr)) {
kept.add(expr);
} else {
nfiltered++;
// logger.warning("Filtering out " + expr.getText());
}
}
if (nfiltered > 0) {
logger.finest("Filtered " + nfiltered);
}
return kept;
}
}
|
gpl-2.0
|
damirkusar/jvoicebridge
|
voicelib/src/com/sun/mpk20/voicelib/impl/service/voice/work/audiogroup/SetSpeakingWork.java
|
1305
|
/*
* Copyright 2007 Sun Microsystems, Inc.
*
* This file is part of jVoiceBridge.
*
* jVoiceBridge is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation and distributed hereunder
* to you.
*
* jVoiceBridge 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/>.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied this
* code.
*/
package com.sun.mpk20.voicelib.impl.service.voice.work.audiogroup;
import com.sun.mpk20.voicelib.app.AudioGroup;
import com.sun.mpk20.voicelib.app.Player;
public class SetSpeakingWork extends AudioGroupWork {
public Player player;
public boolean isSpeaking;
public SetSpeakingWork(AudioGroup audioGroup, Player player, boolean isSpeaking) {
super(audioGroup);
this.player = player;
this.isSpeaking = isSpeaking;
}
}
|
gpl-2.0
|
LoDoMa/Lime
|
src/net/lodoma/lime/rui/RUIProgressBar.java
|
3323
|
package net.lodoma.lime.rui;
import net.lodoma.lime.client.window.Window;
import net.lodoma.lime.util.Vector2;
public class RUIProgressBar extends RUIButton
{
protected float progress_c;
protected final Vector2 progressDimensions = new Vector2();
protected RUIBorder progressBorder;
private String oldState_m;
private float stateTimeTotal_m;
private float stateTime_m;
private float oldProgress_m = Float.NaN;
private float deltaProgressDimensionsX_m;
public RUIProgressBar(RUIElement parent)
{
super(parent);
}
@Override
protected void loadDefaultValues()
{
super.loadDefaultValues();
values.set("default", "progress", RUIValue.SIZE_0);
values.set("default", "progress-show", RUIValue.BOOLEAN_FALSE);
progressBorder = new RUIBorder();
progressBorder.loadDefaultValues(values, "progress-");
}
@Override
public void loadData(RUIParserData data)
{
synchronized (treeLock)
{
super.loadData(data);
data.copy("progress", RUIValueType.SIZE, values);
data.copy("progress-show", RUIValueType.BOOLEAN, values);
progressBorder.loadData(data, values, "progress-");
}
}
@Override
public void update(double timeDelta)
{
synchronized (treeLock)
{
super.update(timeDelta);
progressBorder.update(timeDelta, this, "progress-");
boolean show = values.get(state, "progress-show").toBoolean();
float progress_t = values.get(state, "progress").toSize();
if (show)
values.set("default", "text", new RUIValue((int) (progress_t * 100) + "%"));
progress_t *= (progress_t < 0) ? (-1.0f / Window.viewportWidth) : dimensions_c.x;
progress_c = progress_t;
if (!Float.isNaN(oldProgress_m) && oldProgress_m != progress_c)
{
if (oldState_m != null)
{
stateTimeTotal_m = values.get(state, "enter-state-time").toSize();
if (stateTimeTotal_m < 0)
throw new IllegalStateException();
stateTime_m = stateTimeTotal_m;
deltaProgressDimensionsX_m = progress_c - oldProgress_m;
}
oldState_m = state;
}
oldProgress_m = progress_c;
if (stateTime_m != 0)
{
stateTime_m -= timeDelta;
if (stateTime_m < 0)
stateTime_m = 0;
else
{
float fract = 1.0f - stateTime_m / stateTimeTotal_m;
progress_t = (progress_t - deltaProgressDimensionsX_m) + deltaProgressDimensionsX_m * fract;
}
}
progressDimensions.set(progress_t, dimensions_c.y);
}
}
@Override
protected void renderBackground()
{
super.renderBackground();
progressBorder.fillBackground(progressDimensions);
progressBorder.fillGradient(progressDimensions);
progressBorder.renderBorder(progressDimensions);
}
}
|
gpl-2.0
|
Jacksson/mywms
|
rich.client/los.clientsuite/LOS Common/src/de/linogistix/common/preferences/AppPreferencesController.java
|
4222
|
/*
* Copyright (c) 2006 LinogistiX GmbH. All rights reserved.
*
*<a href="http://www.linogistix.com/">browse for licence information</a>
*
*/
package de.linogistix.common.preferences;
import de.linogistix.common.exception.InternalErrorException;
import de.linogistix.common.util.ExceptionAnnotator;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Properties;
import javax.swing.JComponent;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
/**
* AppPreferencesController controls preference settings.
*
*
* Preferences are stored
* in and read from properties file in Settings folder under build\testuserdir\config\.
*
* Fallback is loading properties from class path as resource.
*
* Using this controller externally (i.e. it is not called from Option Dialog infrastructure)
* needs a call to update() for initialisation.
*/
public final class AppPreferencesController extends OptionsPanelController implements PropertyChangeListener {
private AppPreferencesPanel panel;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private boolean changed;
private AppPreferences prefs;
private AppPreferencesNode aNode;
private String propertyFileBaseName;
Lookup lookup;
private String[] noStoreProps = new String[0];
public AppPreferencesController(String propertyFileBaseName) {
this.propertyFileBaseName = propertyFileBaseName;
}
/**
*
* @param propertyFileBaseName
* @param noStoreProps won't be stored in file (e.g. password information)
*/
public AppPreferencesController(String propertyFileBaseName, String[] noStoreProps) {
this.propertyFileBaseName = propertyFileBaseName;
this.noStoreProps = noStoreProps;
}
public void update() {
Properties p = new Properties();
try {
//Just Fallback for default settings
// p = AppPreferences.loadFromClasspath(propertyFileBaseName + ".properties");
if (prefs == null) {
// Retreieve from file or new with default settings
prefs = AppPreferences.getSettings(propertyFileBaseName, p);
aNode = new AppPreferencesNode(prefs, propertyFileBaseName);
aNode.addPropertyChangeListener(this);
getPanel().update();
} else {
prefs.load(p);
}
} catch (Exception ex) {
// ex.printStackTrace();
ExceptionAnnotator.annotate(new InternalErrorException(ex));
}
//panel.load
getPanel().update();
changed = false;
}
public void applyChanges() {
prefs.setNoStoreProps(this.noStoreProps);
// The setting must be read from config-file. The only thing one can do here,
// is to prevent the next start. So do not store changes.
// prefs.store();
//panel.store
changed = false;
}
public void cancel() {
// need not do anything special, if no changes have been persisted yet
}
public boolean isValid() {
return prefs.valid();
}
public boolean isChanged() {
return changed;
}
public HelpCtx getHelpCtx() {
return null; // new HelpCtx("...ID") if you have a help set
}
public JComponent getComponent(Lookup masterLookup) {
lookup = masterLookup;
return getPanel();
}
public void addPropertyChangeListener(PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
pcs.removePropertyChangeListener(l);
}
private AppPreferencesPanel getPanel() {
if (panel == null) {
panel = new AppPreferencesPanel(this);
}
return panel;
}
void changed() {
if (!changed) {
changed = true;
pcs.firePropertyChange(OptionsPanelController.PROP_CHANGED, false, true);
}
pcs.firePropertyChange(OptionsPanelController.PROP_VALID, null, null);
}
public void propertyChange(PropertyChangeEvent evt) {
changed();
}
public AppPreferences getPrefs() {
return prefs;
}
public AppPreferencesNode getANode() {
return aNode;
}
public String getPropertyFileBaseName() {
return propertyFileBaseName;
}
}
|
gpl-2.0
|
BuddhaLabs/DeD-OSX
|
soot/soot-2.3.0/src/soot/jimple/spark/ondemand/DemandCSPointsTo.java
|
68652
|
/* Soot - a J*va Optimization Framework
* Copyright (C) 2007 Manu Sridharan
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.jimple.spark.ondemand;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.AnySubType;
import soot.ArrayType;
import soot.Context;
import soot.G;
import soot.Local;
import soot.PointsToAnalysis;
import soot.PointsToSet;
import soot.RefType;
import soot.Scene;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.jimple.spark.ondemand.genericutil.ArraySet;
import soot.jimple.spark.ondemand.genericutil.HashSetMultiMap;
import soot.jimple.spark.ondemand.genericutil.ImmutableStack;
import soot.jimple.spark.ondemand.genericutil.Predicate;
import soot.jimple.spark.ondemand.genericutil.Propagator;
import soot.jimple.spark.ondemand.genericutil.Stack;
import soot.jimple.spark.ondemand.pautil.AssignEdge;
import soot.jimple.spark.ondemand.pautil.ContextSensitiveInfo;
import soot.jimple.spark.ondemand.pautil.OTFMethodSCCManager;
import soot.jimple.spark.ondemand.pautil.SootUtil;
import soot.jimple.spark.ondemand.pautil.ValidMatches;
import soot.jimple.spark.ondemand.pautil.SootUtil.FieldToEdgesMap;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.FieldRefNode;
import soot.jimple.spark.pag.GlobalVarNode;
import soot.jimple.spark.pag.LocalVarNode;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.jimple.spark.pag.SparkField;
import soot.jimple.spark.pag.VarNode;
import soot.jimple.spark.sets.EmptyPointsToSet;
import soot.jimple.spark.sets.EqualsSupportingPointsToSet;
import soot.jimple.spark.sets.HybridPointsToSet;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetEqualsWrapper;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.jimple.toolkits.callgraph.VirtualCalls;
import soot.toolkits.scalar.Pair;
import soot.util.NumberedString;
/**
* Tries to find imprecision in points-to sets from a previously run analysis.
* Requires that all sub-results of previous analysis were cached.
*
* @author Manu Sridharan
*
*/
public final class DemandCSPointsTo implements PointsToAnalysis {
@SuppressWarnings("serial")
protected static final class AllocAndContextCache extends
HashMap<AllocAndContext, Map<VarNode, CallingContextSet>> {
}
protected static final class CallingContextSet extends
ArraySet<ImmutableStack<Integer>> {
}
protected final static class CallSiteAndContext extends
Pair<Integer, ImmutableStack<Integer>> {
public CallSiteAndContext(Integer callSite,
ImmutableStack<Integer> callingContext) {
super(callSite, callingContext);
}
}
protected static final class CallSiteToTargetsMap extends
HashSetMultiMap<CallSiteAndContext, SootMethod> {
}
protected static abstract class IncomingEdgeHandler {
public abstract void handleAlloc(AllocNode allocNode,
VarAndContext origVarAndContext);
public abstract void handleMatchSrc(VarNode matchSrc,
PointsToSetInternal intersection, VarNode loadBase,
VarNode storeBase, VarAndContext origVarAndContext,
SparkField field, boolean refine);
abstract Object getResult();
abstract void handleAssignSrc(VarAndContext newVarAndContext,
VarAndContext origVarAndContext, AssignEdge assignEdge);
abstract boolean shouldHandleSrc(VarNode src);
boolean terminate() {
return false;
}
}
protected static class VarAndContext {
final ImmutableStack<Integer> context;
final VarNode var;
public VarAndContext(VarNode var, ImmutableStack<Integer> context) {
assert var != null;
assert context != null;
this.var = var;
this.context = context;
}
public boolean equals(Object o) {
if (o != null && o.getClass() == VarAndContext.class) {
VarAndContext other = (VarAndContext) o;
return var.equals(other.var) && context.equals(other.context);
}
return false;
}
public int hashCode() {
return var.hashCode() + context.hashCode();
}
public String toString() {
return var + " " + context;
}
}
protected final static class VarContextAndUp extends VarAndContext {
final ImmutableStack<Integer> upContext;
public VarContextAndUp(VarNode var, ImmutableStack<Integer> context,
ImmutableStack<Integer> upContext) {
super(var, context);
this.upContext = upContext;
}
public boolean equals(Object o) {
if (o != null && o.getClass() == VarContextAndUp.class) {
VarContextAndUp other = (VarContextAndUp) o;
return var.equals(other.var) && context.equals(other.context)
&& upContext.equals(other.upContext);
}
return false;
}
public int hashCode() {
return var.hashCode() + context.hashCode() + upContext.hashCode();
}
public String toString() {
return var + " " + context + " up " + upContext;
}
}
public static boolean DEBUG = false;
protected static final int DEBUG_NESTING = 15;
protected static final int DEBUG_PASS = -1;
protected static final boolean DEBUG_VIRT = DEBUG && true;
protected static final int DEFAULT_MAX_PASSES = 10;
protected static final int DEFAULT_MAX_TRAVERSAL = 75000;
/**
* if <code>true</code>, refine the pre-computed call graph
*/
private boolean refineCallGraph = true;
protected static final ImmutableStack<Integer> EMPTY_CALLSTACK = ImmutableStack.<Integer> emptyStack();
/**
* Make a default analysis. Assumes Spark has already run.
*
* @return
*/
public static DemandCSPointsTo makeDefault() {
return makeWithBudget(DEFAULT_MAX_TRAVERSAL, DEFAULT_MAX_PASSES);
}
public static DemandCSPointsTo makeWithBudget(int maxTraversal,
int maxPasses) {
PAG pag = (PAG) Scene.v().getPointsToAnalysis();
ContextSensitiveInfo csInfo = new ContextSensitiveInfo(pag);
return new DemandCSPointsTo(csInfo, pag, maxTraversal, maxPasses);
}
protected final AllocAndContextCache allocAndContextCache = new AllocAndContextCache();
protected Stack<Pair<Integer, ImmutableStack<Integer>>> callGraphStack = new Stack<Pair<Integer, ImmutableStack<Integer>>>();
protected final CallSiteToTargetsMap callSiteToResolvedTargets = new CallSiteToTargetsMap();
protected HashMap<List<Object>, Set<SootMethod>> callTargetsArgCache = new HashMap<List<Object>, Set<SootMethod>>();
protected final Stack<VarAndContext> contextForAllocsStack = new Stack<VarAndContext>();
protected Map<VarAndContext, Pair<PointsToSetInternal, AllocAndContextSet>> contextsForAllocsCache = new HashMap<VarAndContext, Pair<PointsToSetInternal, AllocAndContextSet>>();
protected final ContextSensitiveInfo csInfo;
/**
* if <code>true</code>, compute full points-to set for queried
* variable
*/
protected boolean doPointsTo;
protected FieldCheckHeuristic fieldCheckHeuristic;
protected HeuristicType heuristicType;
protected final FieldToEdgesMap fieldToLoads;
protected final FieldToEdgesMap fieldToStores;
protected final int maxNodesPerPass;
protected final int maxPasses;
protected int nesting = 0;
protected int numNodesTraversed;
protected int numPasses = 0;
protected final PAG pag;
protected AllocAndContextSet pointsTo = null;
protected final Set<CallSiteAndContext> queriedCallSites = new HashSet<CallSiteAndContext>();
protected int recursionDepth = -1;
protected boolean refiningCallSite = false;
protected OTFMethodSCCManager sccManager;
protected Map<VarContextAndUp, Map<AllocAndContext, CallingContextSet>> upContextCache = new HashMap<VarContextAndUp, Map<AllocAndContext, CallingContextSet>>();
protected final ValidMatches vMatches;
protected Map<Local,PointsToSet> reachingObjectsCache, reachingObjectsCacheNoCGRefinement;
protected boolean useCache;
public DemandCSPointsTo(ContextSensitiveInfo csInfo, PAG pag) {
this(csInfo, pag, DEFAULT_MAX_TRAVERSAL, DEFAULT_MAX_PASSES);
}
public DemandCSPointsTo(ContextSensitiveInfo csInfo, PAG pag,
int maxTraversal, int maxPasses) {
this.csInfo = csInfo;
this.pag = pag;
this.fieldToStores = SootUtil.storesOnField(pag);
this.fieldToLoads = SootUtil.loadsOnField(pag);
this.vMatches = new ValidMatches(pag, fieldToStores);
this.maxPasses = maxPasses;
this.maxNodesPerPass = maxTraversal / maxPasses;
this.heuristicType = HeuristicType.INCR;
this.reachingObjectsCache = new HashMap<Local, PointsToSet>();
this.reachingObjectsCacheNoCGRefinement = new HashMap<Local, PointsToSet>();
this.useCache = true;
}
/**
* {@inheritDoc}
*/
public PointsToSet reachingObjects(Local l) {
PointsToSet result;
Map<Local, PointsToSet> cache;
if(refineCallGraph) { //we use different caches for different settings
cache = reachingObjectsCache;
} else {
cache = reachingObjectsCacheNoCGRefinement;
}
result = cache.get(l);
if(result==null) {
result = computeReachingObjects(l);
if(useCache) {
cache.put(l, result);
}
}
assert consistentResult(l,result);
return result;
}
/**
* Returns <code>false</code> if an inconsistent computation occurred, i.e. if result
* differs from the result computed by {@link #computeReachingObjects(Local)} on l.
*/
private boolean consistentResult(Local l, PointsToSet result) {
PointsToSet result2 = computeReachingObjects(l);
if(!(result instanceof EqualsSupportingPointsToSet) || !(result2 instanceof EqualsSupportingPointsToSet)) {
//cannot compare, assume everything is fine
return true;
}
EqualsSupportingPointsToSet eq1 = (EqualsSupportingPointsToSet) result;
EqualsSupportingPointsToSet eq2 = (EqualsSupportingPointsToSet) result2;
return new PointsToSetEqualsWrapper(eq1).equals(new PointsToSetEqualsWrapper(eq2));
}
/**
* Computes the possibly refined set of reaching objects for l.
*/
protected PointsToSet computeReachingObjects(Local l) {
VarNode v = pag.findLocalVarNode(l);
if (v == null) {
//no reaching objects
return EmptyPointsToSet.v();
}
PointsToSet contextSensitiveResult = computeRefinedReachingObjects(v);
if(contextSensitiveResult == null ) {
//had to abort; return Spark's points-to set in a wrapper
return new WrappedPointsToSet(v.getP2Set());
} else {
return contextSensitiveResult;
}
}
/**
* Computes the refined set of reaching objects for l.
* Returns <code>null</code> if refinement failed.
*/
protected PointsToSet computeRefinedReachingObjects(VarNode v) {
// must reset the refinement heuristic for each query
this.fieldCheckHeuristic = HeuristicType.getHeuristic(
heuristicType, pag.getTypeManager(), getMaxPasses());
doPointsTo = true;
numPasses = 0;
PointsToSet contextSensitiveResult = null;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
break;
}
if (numPasses > maxPasses) {
break;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
pointsTo = new AllocAndContextSet();
try {
refineP2Set(new VarAndContext(v, EMPTY_CALLSTACK), null);
contextSensitiveResult = pointsTo;
} catch (TerminateEarlyException e) {
}
if (!fieldCheckHeuristic.runNewPass()) {
break;
}
}
return contextSensitiveResult;
}
protected boolean callEdgeInSCC(AssignEdge assignEdge) {
boolean sameSCCAlready = false;
assert assignEdge.isCallEdge();
// assert assignEdge.getSrc() instanceof LocalVarNode :
// assignEdge.getSrc() + " not LocalVarNode";
if (!(assignEdge.getSrc() instanceof LocalVarNode)
|| !(assignEdge.getDst() instanceof LocalVarNode)) {
return false;
}
LocalVarNode src = (LocalVarNode) assignEdge.getSrc();
LocalVarNode dst = (LocalVarNode) assignEdge.getDst();
if (sccManager.inSameSCC(src.getMethod(), dst.getMethod())) {
sameSCCAlready = true;
}
return sameSCCAlready;
}
protected CallingContextSet checkAllocAndContextCache(
AllocAndContext allocAndContext, VarNode targetVar) {
if (allocAndContextCache.containsKey(allocAndContext)) {
Map<VarNode, CallingContextSet> m = allocAndContextCache
.get(allocAndContext);
if (m.containsKey(targetVar)) {
return m.get(targetVar);
}
} else {
allocAndContextCache.put(allocAndContext,
new HashMap<VarNode, CallingContextSet>());
}
return null;
}
protected PointsToSetInternal checkContextsForAllocsCache(
VarAndContext varAndContext, AllocAndContextSet ret,
PointsToSetInternal locs) {
PointsToSetInternal retSet = null;
if (contextsForAllocsCache.containsKey(varAndContext)) {
for (AllocAndContext allocAndContext : contextsForAllocsCache.get(
varAndContext).getO2()) {
if (locs.contains(allocAndContext.alloc)) {
ret.add(allocAndContext);
}
}
final PointsToSetInternal oldLocs = contextsForAllocsCache.get(
varAndContext).getO1();
final PointsToSetInternal tmpSet = new HybridPointsToSet(locs
.getType(), pag);
locs.forall(new P2SetVisitor() {
@Override
public void visit(Node n) {
if (!oldLocs.contains(n)) {
tmpSet.add(n);
}
}
});
retSet = tmpSet;
oldLocs.addAll(tmpSet, null);
} else {
PointsToSetInternal storedSet = new HybridPointsToSet(locs
.getType(), pag);
storedSet.addAll(locs, null);
contextsForAllocsCache.put(varAndContext,
new Pair<PointsToSetInternal, AllocAndContextSet>(
storedSet, new AllocAndContextSet()));
retSet = locs;
}
return retSet;
}
/**
* check the computed points-to set of a variable against some predicate
*
* @param v
* the variable
* @param heuristic
* how to refine match edges
* @param p2setPred
* the predicate on the points-to set
* @return true if the p2setPred holds for the computed points-to set, or if
* a points-to set cannot be computed in the budget; false otherwise
*/
protected boolean checkP2Set(VarNode v, HeuristicType heuristic,
Predicate<Set<AllocAndContext>> p2setPred) {
doPointsTo = true;
// DEBUG = v.getNumber() == 150;
this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag
.getTypeManager(), getMaxPasses());
numPasses = 0;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
return true;
}
if (numPasses > maxPasses) {
return true;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
pointsTo = new AllocAndContextSet();
boolean success = false;
try {
success = refineP2Set(new VarAndContext(v, EMPTY_CALLSTACK),
null);
} catch (TerminateEarlyException e) {
success = false;
}
if (success) {
if (p2setPred.test(pointsTo)) {
return false;
}
} else {
if (!fieldCheckHeuristic.runNewPass()) {
return true;
}
}
}
}
// protected boolean upContextsSane(CallingContextSet ret, AllocAndContext
// allocAndContext, VarContextAndUp varContextAndUp) {
// for (ImmutableStack<Integer> context : ret) {
// ImmutableStack<Integer> fixedContext = fixUpContext(context,
// allocAndContext, varContextAndUp);
// if (!context.equals(fixedContext)) {
// return false;
// }
// }
// return true;
// }
//
// protected CallingContextSet fixAllUpContexts(CallingContextSet contexts,
// AllocAndContext allocAndContext, VarContextAndUp varContextAndUp) {
// if (DEBUG) {
// debugPrint("fixing up contexts");
// }
// CallingContextSet ret = new CallingContextSet();
// for (ImmutableStack<Integer> context : contexts) {
// ret.add(fixUpContext(context, allocAndContext, varContextAndUp));
// }
// return ret;
// }
//
// protected ImmutableStack<Integer> fixUpContext(ImmutableStack<Integer>
// context, AllocAndContext allocAndContext, VarContextAndUp
// varContextAndUp) {
//
// return null;
// }
protected CallingContextSet checkUpContextCache(
VarContextAndUp varContextAndUp, AllocAndContext allocAndContext) {
if (upContextCache.containsKey(varContextAndUp)) {
Map<AllocAndContext, CallingContextSet> allocAndContextMap = upContextCache
.get(varContextAndUp);
if (allocAndContextMap.containsKey(allocAndContext)) {
return allocAndContextMap.get(allocAndContext);
}
} else {
upContextCache.put(varContextAndUp,
new HashMap<AllocAndContext, CallingContextSet>());
}
return null;
}
protected void clearState() {
allocAndContextCache.clear();
callGraphStack.clear();
callSiteToResolvedTargets.clear();
queriedCallSites.clear();
contextsForAllocsCache.clear();
contextForAllocsStack.clear();
upContextCache.clear();
callTargetsArgCache.clear();
sccManager = new OTFMethodSCCManager();
numNodesTraversed = 0;
nesting = 0;
recursionDepth = -1;
}
/**
* compute a flows-to set for an allocation site. for now, we use a simple
* refinement strategy; just refine as much as possible, maintaining the
* smallest set of flows-to vars
*
* @param alloc
* @param heuristic
* @return
*/
protected Set<VarNode> computeFlowsTo(AllocNode alloc,
HeuristicType heuristic) {
this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag
.getTypeManager(), getMaxPasses());
numPasses = 0;
Set<VarNode> smallest = null;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
return smallest;
}
if (numPasses > maxPasses) {
return smallest;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
Set<VarNode> result = null;
try {
result = getFlowsToHelper(new AllocAndContext(alloc,
EMPTY_CALLSTACK));
} catch (TerminateEarlyException e) {
}
if (result != null) {
if (smallest == null || result.size() < smallest.size()) {
smallest = result;
}
}
if (!fieldCheckHeuristic.runNewPass()) {
return smallest;
}
}
}
protected void debugPrint(String str) {
if (nesting <= DEBUG_NESTING) {
if (DEBUG_PASS == -1 || DEBUG_PASS == numPasses) {
G.v().out.println(":" + nesting + " " + str);
}
}
}
/*
* (non-Javadoc)
*
* @see AAA.summary.Refiner#dumpPathForBadLoc(soot.jimple.spark.pag.VarNode,
* soot.jimple.spark.pag.AllocNode)
*/
protected void dumpPathForLoc(VarNode v, final AllocNode badLoc,
String filePrefix) {
final HashSet<VarNode> visited = new HashSet<VarNode>();
final DotPointerGraph dotGraph = new DotPointerGraph();
final class Helper {
boolean handle(VarNode curNode) {
assert curNode.getP2Set().contains(badLoc);
visited.add(curNode);
Node[] newEdges = pag.allocInvLookup(curNode);
for (int i = 0; i < newEdges.length; i++) {
AllocNode alloc = (AllocNode) newEdges[i];
if (alloc.equals(badLoc)) {
dotGraph.addNew(alloc, curNode);
return true;
}
}
for (AssignEdge assignEdge : csInfo.getAssignEdges(curNode)) {
VarNode other = assignEdge.getSrc();
if (other.getP2Set().contains(badLoc)
&& !visited.contains(other) && handle(other)) {
if (assignEdge.isCallEdge()) {
dotGraph.addCall(other, curNode, assignEdge
.getCallSite());
} else {
dotGraph.addAssign(other, curNode);
}
return true;
}
}
Node[] loadEdges = pag.loadInvLookup(curNode);
for (int i = 0; i < loadEdges.length; i++) {
FieldRefNode frNode = (FieldRefNode) loadEdges[i];
SparkField field = frNode.getField();
VarNode base = frNode.getBase();
PointsToSetInternal baseP2Set = base.getP2Set();
for (Pair<VarNode, VarNode> store : fieldToStores
.get(field)) {
if (store.getO2().getP2Set().hasNonEmptyIntersection(
baseP2Set)) {
VarNode matchSrc = store.getO1();
if (matchSrc.getP2Set().contains(badLoc)
&& !visited.contains(matchSrc)
&& handle(matchSrc)) {
dotGraph.addMatch(matchSrc, curNode);
return true;
}
}
}
}
return false;
}
}
Helper h = new Helper();
h.handle(v);
// G.v().out.println(dotGraph.numEdges() + " edges on path");
dotGraph.dump("tmp/" + filePrefix + v.getNumber() + "_"
+ badLoc.getNumber() + ".dot");
}
protected Collection<AssignEdge> filterAssigns(final VarNode v,
final ImmutableStack<Integer> callingContext, boolean forward,
boolean refineVirtCalls) {
Set<AssignEdge> assigns = forward ? csInfo.getAssignEdges(v) : csInfo
.getAssignBarEdges(v);
Collection<AssignEdge> realAssigns;
boolean exitNode = forward ? SootUtil.isParamNode(v) : SootUtil
.isRetNode(v);
final boolean backward = !forward;
if (exitNode && !callingContext.isEmpty()) {
Integer topCallSite = callingContext.peek();
realAssigns = new ArrayList<AssignEdge>();
for (AssignEdge assignEdge : assigns) {
assert (forward && assignEdge.isParamEdge())
|| (backward && assignEdge.isReturnEdge()) : assignEdge;
Integer assignEdgeCallSite = assignEdge.getCallSite();
assert csInfo.getCallSiteTargets(assignEdgeCallSite).contains(
((LocalVarNode) v).getMethod()) : assignEdge;
if (topCallSite.equals(assignEdgeCallSite)
|| callEdgeInSCC(assignEdge)) {
realAssigns.add(assignEdge);
}
}
// assert realAssigns.size() == 1;
} else {
if (assigns.size() > 1) {
realAssigns = new ArrayList<AssignEdge>();
for (AssignEdge assignEdge : assigns) {
boolean enteringCall = forward ? assignEdge.isReturnEdge()
: assignEdge.isParamEdge();
if (enteringCall) {
Integer callSite = assignEdge.getCallSite();
if (csInfo.isVirtCall(callSite) && refineVirtCalls) {
Set<SootMethod> targets = refineCallSite(assignEdge
.getCallSite(), callingContext);
LocalVarNode nodeInTargetMethod = forward ? (LocalVarNode) assignEdge
.getSrc()
: (LocalVarNode) assignEdge.getDst();
if (targets
.contains(nodeInTargetMethod.getMethod())) {
realAssigns.add(assignEdge);
}
} else {
realAssigns.add(assignEdge);
}
} else {
realAssigns.add(assignEdge);
}
}
} else {
realAssigns = assigns;
}
}
return realAssigns;
}
protected AllocAndContextSet findContextsForAllocs(
final VarAndContext varAndContext, PointsToSetInternal locs) {
if (contextForAllocsStack.contains(varAndContext)) {
// recursion; check depth
// we're fine for x = x.next
int oldIndex = contextForAllocsStack.indexOf(varAndContext);
if (oldIndex != contextForAllocsStack.size() - 1) {
if (recursionDepth == -1) {
recursionDepth = oldIndex + 1;
if (DEBUG) {
debugPrint("RECURSION depth = " + recursionDepth);
}
} else if (contextForAllocsStack.size() - oldIndex > 5) {
// just give up
throw new TerminateEarlyException();
}
}
}
contextForAllocsStack.push(varAndContext);
final AllocAndContextSet ret = new AllocAndContextSet();
final PointsToSetInternal realLocs = checkContextsForAllocsCache(
varAndContext, ret, locs);
if (realLocs.isEmpty()) {
if (DEBUG) {
debugPrint("cached result " + ret);
}
contextForAllocsStack.pop();
return ret;
}
nesting++;
if (DEBUG) {
debugPrint("finding alloc contexts for " + varAndContext);
}
try {
final Set<VarAndContext> marked = new HashSet<VarAndContext>();
final Stack<VarAndContext> worklist = new Stack<VarAndContext>();
final Propagator<VarAndContext> p = new Propagator<VarAndContext>(
marked, worklist);
p.prop(varAndContext);
IncomingEdgeHandler edgeHandler = new IncomingEdgeHandler() {
@Override
public void handleAlloc(AllocNode allocNode,
VarAndContext origVarAndContext) {
if (realLocs.contains(allocNode)) {
if (DEBUG) {
debugPrint("found alloc " + allocNode);
}
ret.add(new AllocAndContext(allocNode,
origVarAndContext.context));
}
}
@Override
public void handleMatchSrc(final VarNode matchSrc,
PointsToSetInternal intersection, VarNode loadBase,
VarNode storeBase, VarAndContext origVarAndContext,
SparkField field, boolean refine) {
if (DEBUG) {
debugPrint("handling src " + matchSrc);
debugPrint("intersection " + intersection);
}
if (!refine) {
p.prop(new VarAndContext(matchSrc, EMPTY_CALLSTACK));
return;
}
AllocAndContextSet allocContexts = findContextsForAllocs(
new VarAndContext(loadBase,
origVarAndContext.context), intersection);
if (DEBUG) {
debugPrint("alloc contexts " + allocContexts);
}
for (AllocAndContext allocAndContext : allocContexts) {
if (DEBUG) {
debugPrint("alloc and context " + allocAndContext);
}
CallingContextSet matchSrcContexts;
if (fieldCheckHeuristic.validFromBothEnds(field)) {
matchSrcContexts = findUpContextsForVar(
allocAndContext, new VarContextAndUp(
storeBase, EMPTY_CALLSTACK,
EMPTY_CALLSTACK));
} else {
matchSrcContexts = findVarContextsFromAlloc(
allocAndContext, storeBase);
}
for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) {
// ret
// .add(new Pair<AllocNode,
// ImmutableStack<Integer>>(
// (AllocNode) n,
// matchSrcContext));
// ret.addAll(findContextsForAllocs(matchSrc,
// matchSrcContext, locs));
p
.prop(new VarAndContext(matchSrc,
matchSrcContext));
}
}
}
@Override
Object getResult() {
return ret;
}
@Override
void handleAssignSrc(VarAndContext newVarAndContext,
VarAndContext origVarAndContext, AssignEdge assignEdge) {
p.prop(newVarAndContext);
}
@Override
boolean shouldHandleSrc(VarNode src) {
return realLocs.hasNonEmptyIntersection(src.getP2Set());
}
};
processIncomingEdges(edgeHandler, worklist);
// update the cache
if (recursionDepth != -1) {
// if we're beyond recursion, don't cache anything
if (contextForAllocsStack.size() > recursionDepth) {
if (DEBUG) {
debugPrint("REMOVING " + varAndContext);
debugPrint(contextForAllocsStack.toString());
}
contextsForAllocsCache.remove(varAndContext);
} else {
assert contextForAllocsStack.size() == recursionDepth : recursionDepth
+ " " + contextForAllocsStack;
recursionDepth = -1;
if (contextsForAllocsCache.containsKey(varAndContext)) {
contextsForAllocsCache.get(varAndContext).getO2()
.addAll(ret);
} else {
PointsToSetInternal storedSet = new HybridPointsToSet(
locs.getType(), pag);
storedSet.addAll(locs, null);
contextsForAllocsCache
.put(
varAndContext,
new Pair<PointsToSetInternal, AllocAndContextSet>(
storedSet, ret));
}
}
} else {
if (contextsForAllocsCache.containsKey(varAndContext)) {
contextsForAllocsCache.get(varAndContext).getO2().addAll(
ret);
} else {
PointsToSetInternal storedSet = new HybridPointsToSet(locs
.getType(), pag);
storedSet.addAll(locs, null);
contextsForAllocsCache.put(varAndContext,
new Pair<PointsToSetInternal, AllocAndContextSet>(
storedSet, ret));
}
}
nesting--;
return ret;
} catch (CallSiteException e) {
contextsForAllocsCache.remove(varAndContext);
throw e;
} finally {
contextForAllocsStack.pop();
}
}
protected CallingContextSet findUpContextsForVar(
AllocAndContext allocAndContext, VarContextAndUp varContextAndUp) {
final AllocNode alloc = allocAndContext.alloc;
final ImmutableStack<Integer> allocContext = allocAndContext.context;
CallingContextSet tmpSet = checkUpContextCache(varContextAndUp,
allocAndContext);
if (tmpSet != null) {
return tmpSet;
}
final CallingContextSet ret = new CallingContextSet();
upContextCache.get(varContextAndUp).put(allocAndContext, ret);
nesting++;
if (DEBUG) {
debugPrint("finding up context for " + varContextAndUp + " to "
+ alloc + " " + allocContext);
}
try {
final Set<VarAndContext> marked = new HashSet<VarAndContext>();
final Stack<VarAndContext> worklist = new Stack<VarAndContext>();
final Propagator<VarAndContext> p = new Propagator<VarAndContext>(
marked, worklist);
p.prop(varContextAndUp);
class UpContextEdgeHandler extends IncomingEdgeHandler {
@Override
public void handleAlloc(AllocNode allocNode,
VarAndContext origVarAndContext) {
VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext;
if (allocNode == alloc) {
if (allocContext.topMatches(contextAndUp.context)) {
ImmutableStack<Integer> reverse = contextAndUp.upContext
.reverse();
ImmutableStack<Integer> toAdd = allocContext
.popAll(contextAndUp.context).pushAll(
reverse);
if (DEBUG) {
debugPrint("found up context " + toAdd);
}
ret.add(toAdd);
} else if (contextAndUp.context
.topMatches(allocContext)) {
ImmutableStack<Integer> toAdd = contextAndUp.upContext
.reverse();
if (DEBUG) {
debugPrint("found up context " + toAdd);
}
ret.add(toAdd);
}
}
}
@Override
public void handleMatchSrc(VarNode matchSrc,
PointsToSetInternal intersection, VarNode loadBase,
VarNode storeBase, VarAndContext origVarAndContext,
SparkField field, boolean refine) {
VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext;
if (DEBUG) {
debugPrint("CHECKING " + alloc);
}
PointsToSetInternal tmp = new HybridPointsToSet(alloc
.getType(), pag);
tmp.add(alloc);
AllocAndContextSet allocContexts = findContextsForAllocs(
new VarAndContext(matchSrc, EMPTY_CALLSTACK), tmp);
// Set allocContexts = Collections.singleton(new Object());
if (!refine) {
if (!allocContexts.isEmpty()) {
ret.add(contextAndUp.upContext.reverse());
}
} else {
if (!allocContexts.isEmpty()) {
for (AllocAndContext t : allocContexts) {
ImmutableStack<Integer> discoveredAllocContext = t.context;
if (!allocContext
.topMatches(discoveredAllocContext)) {
continue;
}
ImmutableStack<Integer> trueAllocContext = allocContext
.popAll(discoveredAllocContext);
AllocAndContextSet allocAndContexts = findContextsForAllocs(
new VarAndContext(storeBase,
trueAllocContext), intersection);
for (AllocAndContext allocAndContext : allocAndContexts) {
// if (DEBUG)
// G.v().out.println("alloc context "
// + newAllocContext);
// CallingContextSet upContexts;
if (fieldCheckHeuristic
.validFromBothEnds(field)) {
ret
.addAll(findUpContextsForVar(
allocAndContext,
new VarContextAndUp(
loadBase,
contextAndUp.context,
contextAndUp.upContext)));
} else {
CallingContextSet tmpContexts = findVarContextsFromAlloc(
allocAndContext, loadBase);
// upContexts = new CallingContextSet();
for (ImmutableStack<Integer> tmpContext : tmpContexts) {
if (tmpContext
.topMatches(contextAndUp.context)) {
ImmutableStack<Integer> reverse = contextAndUp.upContext
.reverse();
ImmutableStack<Integer> toAdd = tmpContext
.popAll(
contextAndUp.context)
.pushAll(reverse);
ret.add(toAdd);
}
}
}
}
}
}
}
}
@Override
Object getResult() {
return ret;
}
@Override
void handleAssignSrc(VarAndContext newVarAndContext,
VarAndContext origVarAndContext, AssignEdge assignEdge) {
VarContextAndUp contextAndUp = (VarContextAndUp) origVarAndContext;
ImmutableStack<Integer> upContext = contextAndUp.upContext;
ImmutableStack<Integer> newUpContext = upContext;
if (assignEdge.isParamEdge()
&& contextAndUp.context.isEmpty()) {
if (upContext.size() < ImmutableStack.getMaxSize()) {
newUpContext = pushWithRecursionCheck(upContext,
assignEdge);
}
;
}
p.prop(new VarContextAndUp(newVarAndContext.var,
newVarAndContext.context, newUpContext));
}
@Override
boolean shouldHandleSrc(VarNode src) {
if (src instanceof GlobalVarNode) {
// TODO properly handle case of global here; rare
// but possible
// reachedGlobal = true;
// // for now, just give up
throw new TerminateEarlyException();
}
return src.getP2Set().contains(alloc);
}
}
;
UpContextEdgeHandler edgeHandler = new UpContextEdgeHandler();
processIncomingEdges(edgeHandler, worklist);
nesting--;
// if (edgeHandler.reachedGlobal) {
// return fixAllUpContexts(ret, allocAndContext, varContextAndUp);
// } else {
// assert upContextsSane(ret, allocAndContext, varContextAndUp);
// return ret;
// }
return ret;
} catch (CallSiteException e) {
upContextCache.remove(varContextAndUp);
throw e;
}
}
protected CallingContextSet findVarContextsFromAlloc(
AllocAndContext allocAndContext, VarNode targetVar) {
CallingContextSet tmpSet = checkAllocAndContextCache(allocAndContext,
targetVar);
if (tmpSet != null) {
return tmpSet;
}
CallingContextSet ret = new CallingContextSet();
allocAndContextCache.get(allocAndContext).put(targetVar, ret);
try {
HashSet<VarAndContext> marked = new HashSet<VarAndContext>();
Stack<VarAndContext> worklist = new Stack<VarAndContext>();
Propagator<VarAndContext> p = new Propagator<VarAndContext>(marked,
worklist);
AllocNode alloc = allocAndContext.alloc;
ImmutableStack<Integer> allocContext = allocAndContext.context;
Node[] newBarNodes = pag.allocLookup(alloc);
for (int i = 0; i < newBarNodes.length; i++) {
VarNode v = (VarNode) newBarNodes[i];
p.prop(new VarAndContext(v, allocContext));
}
while (!worklist.isEmpty()) {
incrementNodesTraversed();
VarAndContext curVarAndContext = worklist.pop();
if (DEBUG) {
debugPrint("looking at " + curVarAndContext);
}
VarNode curVar = curVarAndContext.var;
ImmutableStack<Integer> curContext = curVarAndContext.context;
if (curVar == targetVar) {
ret.add(curContext);
}
// assign
Collection<AssignEdge> assignEdges = filterAssigns(curVar,
curContext, false, true);
for (AssignEdge assignEdge : assignEdges) {
VarNode dst = assignEdge.getDst();
ImmutableStack<Integer> newContext = curContext;
if (assignEdge.isReturnEdge()) {
if (!curContext.isEmpty()) {
if (!callEdgeInSCC(assignEdge)) {
assert assignEdge.getCallSite().equals(
curContext.peek()) : assignEdge + " "
+ curContext;
newContext = curContext.pop();
} else {
newContext = popRecursiveCallSites(curContext);
}
}
} else if (assignEdge.isParamEdge()) {
if (DEBUG)
debugPrint("entering call site "
+ assignEdge.getCallSite());
// if (!isRecursive(curContext, assignEdge)) {
// newContext = curContext.push(assignEdge
// .getCallSite());
// }
newContext = pushWithRecursionCheck(curContext,
assignEdge);
}
if (assignEdge.isReturnEdge() && curContext.isEmpty()
&& csInfo.isVirtCall(assignEdge.getCallSite())) {
Set<SootMethod> targets = refineCallSite(assignEdge
.getCallSite(), newContext);
if (!targets.contains(((LocalVarNode) assignEdge
.getDst()).getMethod())) {
continue;
}
}
if (dst instanceof GlobalVarNode) {
newContext = EMPTY_CALLSTACK;
}
p.prop(new VarAndContext(dst, newContext));
}
// putfield_bars
Set<VarNode> matchTargets = vMatches.vMatchLookup(curVar);
Node[] pfTargets = pag.storeLookup(curVar);
for (int i = 0; i < pfTargets.length; i++) {
FieldRefNode frNode = (FieldRefNode) pfTargets[i];
final VarNode storeBase = frNode.getBase();
SparkField field = frNode.getField();
// Pair<VarNode, FieldRefNode> putfield = new Pair<VarNode,
// FieldRefNode>(curVar, frNode);
for (Pair<VarNode, VarNode> load : fieldToLoads.get(field)) {
final VarNode loadBase = load.getO2();
final PointsToSetInternal loadBaseP2Set = loadBase
.getP2Set();
final PointsToSetInternal storeBaseP2Set = storeBase
.getP2Set();
final VarNode matchTgt = load.getO1();
if (matchTargets.contains(matchTgt)) {
if (DEBUG) {
debugPrint("match source " + matchTgt);
}
PointsToSetInternal intersection = SootUtil
.constructIntersection(storeBaseP2Set,
loadBaseP2Set, pag);
boolean checkField = fieldCheckHeuristic
.validateMatchesForField(field);
if (checkField) {
AllocAndContextSet sharedAllocContexts = findContextsForAllocs(
new VarAndContext(storeBase, curContext),
intersection);
for (AllocAndContext curAllocAndContext : sharedAllocContexts) {
CallingContextSet upContexts;
if (fieldCheckHeuristic
.validFromBothEnds(field)) {
upContexts = findUpContextsForVar(
curAllocAndContext,
new VarContextAndUp(loadBase,
EMPTY_CALLSTACK,
EMPTY_CALLSTACK));
} else {
upContexts = findVarContextsFromAlloc(
curAllocAndContext, loadBase);
}
for (ImmutableStack<Integer> upContext : upContexts) {
p.prop(new VarAndContext(matchTgt,
upContext));
}
}
} else {
p.prop(new VarAndContext(matchTgt,
EMPTY_CALLSTACK));
}
// h.handleMatchSrc(matchSrc, intersection,
// storeBase,
// loadBase, varAndContext, checkGetfield);
// if (h.terminate())
// return;
}
}
}
}
return ret;
} catch (CallSiteException e) {
allocAndContextCache.remove(allocAndContext);
throw e;
}
}
@SuppressWarnings("unchecked")
protected Set<SootMethod> getCallTargets(PointsToSetInternal p2Set,
NumberedString methodStr, Type receiverType,
Set<SootMethod> possibleTargets) {
List<Object> args = Arrays.asList(p2Set, methodStr, receiverType,
possibleTargets);
if (callTargetsArgCache.containsKey(args)) {
return callTargetsArgCache.get(args);
}
Set<Type> types = p2Set.possibleTypes();
Set<SootMethod> ret = new HashSet<SootMethod>();
for (Type type : types) {
ret.addAll(getCallTargetsForType(type, methodStr, receiverType,
possibleTargets));
}
callTargetsArgCache.put(args, ret);
return ret;
}
protected Set<SootMethod> getCallTargetsForType(Type type,
NumberedString methodStr, Type receiverType,
Set<SootMethod> possibleTargets) {
if (!pag.getTypeManager().castNeverFails(type, receiverType))
return Collections.<SootMethod> emptySet();
if (type instanceof AnySubType) {
AnySubType any = (AnySubType) type;
RefType refType = any.getBase();
if (pag.getTypeManager().getFastHierarchy().canStoreType(
receiverType, refType)
|| pag.getTypeManager().getFastHierarchy().canStoreType(
refType, receiverType)) {
return possibleTargets;
} else {
return Collections.<SootMethod> emptySet();
}
}
if (type instanceof ArrayType) {
// we'll invoke the java.lang.Object method in this
// case
// Assert.chk(varNodeType.toString().equals("java.lang.Object"));
type = Scene.v().getSootClass("java.lang.Object").getType();
}
RefType refType = (RefType) type;
SootMethod targetMethod = null;
targetMethod = VirtualCalls.v().resolveNonSpecial(refType, methodStr);
return Collections.<SootMethod> singleton(targetMethod);
}
protected Set<VarNode> getFlowsToHelper(AllocAndContext allocAndContext) {
Set<VarNode> ret = new ArraySet<VarNode>();
try {
HashSet<VarAndContext> marked = new HashSet<VarAndContext>();
Stack<VarAndContext> worklist = new Stack<VarAndContext>();
Propagator<VarAndContext> p = new Propagator<VarAndContext>(marked,
worklist);
AllocNode alloc = allocAndContext.alloc;
ImmutableStack<Integer> allocContext = allocAndContext.context;
Node[] newBarNodes = pag.allocLookup(alloc);
for (int i = 0; i < newBarNodes.length; i++) {
VarNode v = (VarNode) newBarNodes[i];
ret.add(v);
p.prop(new VarAndContext(v, allocContext));
}
while (!worklist.isEmpty()) {
incrementNodesTraversed();
VarAndContext curVarAndContext = worklist.pop();
if (DEBUG) {
debugPrint("looking at " + curVarAndContext);
}
VarNode curVar = curVarAndContext.var;
ImmutableStack<Integer> curContext = curVarAndContext.context;
ret.add(curVar);
// assign
Collection<AssignEdge> assignEdges = filterAssigns(curVar,
curContext, false, true);
for (AssignEdge assignEdge : assignEdges) {
VarNode dst = assignEdge.getDst();
ImmutableStack<Integer> newContext = curContext;
if (assignEdge.isReturnEdge()) {
if (!curContext.isEmpty()) {
if (!callEdgeInSCC(assignEdge)) {
assert assignEdge.getCallSite().equals(
curContext.peek()) : assignEdge + " "
+ curContext;
newContext = curContext.pop();
} else {
newContext = popRecursiveCallSites(curContext);
}
}
} else if (assignEdge.isParamEdge()) {
if (DEBUG)
debugPrint("entering call site "
+ assignEdge.getCallSite());
// if (!isRecursive(curContext, assignEdge)) {
// newContext = curContext.push(assignEdge
// .getCallSite());
// }
newContext = pushWithRecursionCheck(curContext,
assignEdge);
}
if (assignEdge.isReturnEdge() && curContext.isEmpty()
&& csInfo.isVirtCall(assignEdge.getCallSite())) {
Set<SootMethod> targets = refineCallSite(assignEdge
.getCallSite(), newContext);
if (!targets.contains(((LocalVarNode) assignEdge
.getDst()).getMethod())) {
continue;
}
}
if (dst instanceof GlobalVarNode) {
newContext = EMPTY_CALLSTACK;
}
p.prop(new VarAndContext(dst, newContext));
}
// putfield_bars
Set<VarNode> matchTargets = vMatches.vMatchLookup(curVar);
Node[] pfTargets = pag.storeLookup(curVar);
for (int i = 0; i < pfTargets.length; i++) {
FieldRefNode frNode = (FieldRefNode) pfTargets[i];
final VarNode storeBase = frNode.getBase();
SparkField field = frNode.getField();
// Pair<VarNode, FieldRefNode> putfield = new Pair<VarNode,
// FieldRefNode>(curVar, frNode);
for (Pair<VarNode, VarNode> load : fieldToLoads.get(field)) {
final VarNode loadBase = load.getO2();
final PointsToSetInternal loadBaseP2Set = loadBase
.getP2Set();
final PointsToSetInternal storeBaseP2Set = storeBase
.getP2Set();
final VarNode matchTgt = load.getO1();
if (matchTargets.contains(matchTgt)) {
if (DEBUG) {
debugPrint("match source " + matchTgt);
}
PointsToSetInternal intersection = SootUtil
.constructIntersection(storeBaseP2Set,
loadBaseP2Set, pag);
boolean checkField = fieldCheckHeuristic
.validateMatchesForField(field);
if (checkField) {
AllocAndContextSet sharedAllocContexts = findContextsForAllocs(
new VarAndContext(storeBase, curContext),
intersection);
for (AllocAndContext curAllocAndContext : sharedAllocContexts) {
CallingContextSet upContexts;
if (fieldCheckHeuristic
.validFromBothEnds(field)) {
upContexts = findUpContextsForVar(
curAllocAndContext,
new VarContextAndUp(loadBase,
EMPTY_CALLSTACK,
EMPTY_CALLSTACK));
} else {
upContexts = findVarContextsFromAlloc(
curAllocAndContext, loadBase);
}
for (ImmutableStack<Integer> upContext : upContexts) {
p.prop(new VarAndContext(matchTgt,
upContext));
}
}
} else {
p.prop(new VarAndContext(matchTgt,
EMPTY_CALLSTACK));
}
// h.handleMatchSrc(matchSrc, intersection,
// storeBase,
// loadBase, varAndContext, checkGetfield);
// if (h.terminate())
// return;
}
}
}
}
return ret;
} catch (CallSiteException e) {
allocAndContextCache.remove(allocAndContext);
throw e;
}
}
protected int getMaxPasses() {
return maxPasses;
}
protected void incrementNodesTraversed() {
numNodesTraversed++;
if (numNodesTraversed > maxNodesPerPass) {
throw new TerminateEarlyException();
}
}
@SuppressWarnings("unused")
protected boolean isRecursive(ImmutableStack<Integer> context,
AssignEdge assignEdge) {
boolean sameSCCAlready = callEdgeInSCC(assignEdge);
if (sameSCCAlready) {
return true;
}
Integer callSite = assignEdge.getCallSite();
if (context.contains(callSite)) {
Set<SootMethod> toBeCollapsed = new ArraySet<SootMethod>();
int callSiteInd = 0;
for (; callSiteInd < context.size()
&& !context.get(callSiteInd).equals(callSite); callSiteInd++)
;
for (; callSiteInd < context.size(); callSiteInd++) {
toBeCollapsed.add(csInfo.getInvokingMethod(context
.get(callSiteInd)));
}
sccManager.makeSameSCC(toBeCollapsed);
return true;
}
return false;
}
protected boolean isRecursiveCallSite(Integer callSite) {
SootMethod invokingMethod = csInfo.getInvokingMethod(callSite);
SootMethod invokedMethod = csInfo.getInvokedMethod(callSite);
return sccManager.inSameSCC(invokingMethod, invokedMethod);
}
@SuppressWarnings("unused")
protected Set<VarNode> nodesPropagatedThrough(final VarNode source,
final PointsToSetInternal allocs) {
final Set<VarNode> marked = new HashSet<VarNode>();
final Stack<VarNode> worklist = new Stack<VarNode>();
Propagator<VarNode> p = new Propagator<VarNode>(marked, worklist);
p.prop(source);
while (!worklist.isEmpty()) {
VarNode curNode = worklist.pop();
Node[] assignSources = pag.simpleInvLookup(curNode);
for (int i = 0; i < assignSources.length; i++) {
VarNode assignSrc = (VarNode) assignSources[i];
if (assignSrc.getP2Set().hasNonEmptyIntersection(allocs)) {
p.prop(assignSrc);
}
}
Set<VarNode> matchSources = vMatches.vMatchInvLookup(curNode);
for (VarNode matchSrc : matchSources) {
if (matchSrc.getP2Set().hasNonEmptyIntersection(allocs)) {
p.prop(matchSrc);
}
}
}
return marked;
}
protected ImmutableStack<Integer> popRecursiveCallSites(
ImmutableStack<Integer> context) {
ImmutableStack<Integer> ret = context;
while (!ret.isEmpty() && isRecursiveCallSite(ret.peek())) {
ret = ret.pop();
}
return ret;
}
protected void processIncomingEdges(IncomingEdgeHandler h,
Stack<VarAndContext> worklist) {
while (!worklist.isEmpty()) {
incrementNodesTraversed();
VarAndContext varAndContext = worklist.pop();
if (DEBUG) {
debugPrint("looking at " + varAndContext);
}
VarNode v = varAndContext.var;
ImmutableStack<Integer> callingContext = varAndContext.context;
Node[] newEdges = pag.allocInvLookup(v);
for (int i = 0; i < newEdges.length; i++) {
AllocNode allocNode = (AllocNode) newEdges[i];
h.handleAlloc(allocNode, varAndContext);
if (h.terminate()) {
return;
}
}
Collection<AssignEdge> assigns = filterAssigns(v, callingContext,
true, true);
for (AssignEdge assignEdge : assigns) {
VarNode src = assignEdge.getSrc();
// if (DEBUG) {
// G.v().out.println("assign src " + src);
// }
if (h.shouldHandleSrc(src)) {
ImmutableStack<Integer> newContext = callingContext;
if (assignEdge.isParamEdge()) {
if (!callingContext.isEmpty()) {
if (!callEdgeInSCC(assignEdge)) {
assert assignEdge.getCallSite().equals(
callingContext.peek()) : assignEdge
+ " " + callingContext;
newContext = callingContext.pop();
} else {
newContext = popRecursiveCallSites(callingContext);
}
}
// } else if (refiningCallSite) {
// if (!fieldCheckHeuristic.aggressiveVirtCallRefine())
// {
// // throw new CallSiteException();
// }
// }
} else if (assignEdge.isReturnEdge()) {
if (DEBUG)
debugPrint("entering call site "
+ assignEdge.getCallSite());
// if (!isRecursive(callingContext, assignEdge)) {
// newContext = callingContext.push(assignEdge
// .getCallSite());
// }
newContext = pushWithRecursionCheck(callingContext,
assignEdge);
}
if (assignEdge.isParamEdge()) {
Integer callSite = assignEdge.getCallSite();
if (csInfo.isVirtCall(callSite) && !weirdCall(callSite)) {
Set<SootMethod> targets = refineCallSite(callSite,
newContext);
if (DEBUG) {
debugPrint(targets.toString());
}
SootMethod targetMethod = ((LocalVarNode) assignEdge
.getDst()).getMethod();
if (!targets.contains(targetMethod)) {
if (DEBUG) {
debugPrint("skipping call because of call graph");
}
continue;
}
}
}
if (src instanceof GlobalVarNode) {
newContext = EMPTY_CALLSTACK;
}
h.handleAssignSrc(new VarAndContext(src, newContext),
varAndContext, assignEdge);
if (h.terminate()) {
return;
}
}
}
Set<VarNode> matchSources = vMatches.vMatchInvLookup(v);
Node[] loads = pag.loadInvLookup(v);
for (int i = 0; i < loads.length; i++) {
FieldRefNode frNode = (FieldRefNode) loads[i];
final VarNode loadBase = frNode.getBase();
SparkField field = frNode.getField();
// Pair<VarNode, FieldRefNode> getfield = new Pair<VarNode,
// FieldRefNode>(v, frNode);
for (Pair<VarNode, VarNode> store : fieldToStores.get(field)) {
final VarNode storeBase = store.getO2();
final PointsToSetInternal storeBaseP2Set = storeBase
.getP2Set();
final PointsToSetInternal loadBaseP2Set = loadBase
.getP2Set();
final VarNode matchSrc = store.getO1();
if (matchSources.contains(matchSrc)) {
if (h.shouldHandleSrc(matchSrc)) {
if (DEBUG) {
debugPrint("match source " + matchSrc);
}
PointsToSetInternal intersection = SootUtil
.constructIntersection(storeBaseP2Set,
loadBaseP2Set, pag);
boolean checkGetfield = fieldCheckHeuristic
.validateMatchesForField(field);
h.handleMatchSrc(matchSrc, intersection, loadBase,
storeBase, varAndContext, field,
checkGetfield);
if (h.terminate())
return;
}
}
}
}
}
}
protected ImmutableStack<Integer> pushWithRecursionCheck(
ImmutableStack<Integer> context, AssignEdge assignEdge) {
boolean foundRecursion = callEdgeInSCC(assignEdge);
if (!foundRecursion) {
Integer callSite = assignEdge.getCallSite();
if (context.contains(callSite)) {
foundRecursion = true;
if (DEBUG) {
debugPrint("RECURSION!!!");
}
// TODO properly collapse recursive methods
if (true) {
throw new TerminateEarlyException();
}
Set<SootMethod> toBeCollapsed = new ArraySet<SootMethod>();
int callSiteInd = 0;
for (; callSiteInd < context.size()
&& !context.get(callSiteInd).equals(callSite); callSiteInd++)
;
// int numToPop = 0;
for (; callSiteInd < context.size(); callSiteInd++) {
toBeCollapsed.add(csInfo.getInvokingMethod(context
.get(callSiteInd)));
// numToPop++;
}
sccManager.makeSameSCC(toBeCollapsed);
// ImmutableStack<Integer> poppedContext = context;
// for (int i = 0; i < numToPop; i++) {
// poppedContext = poppedContext.pop();
// }
// if (DEBUG) {
// debugPrint("new stack " + poppedContext);
// }
// return poppedContext;
}
}
if (foundRecursion) {
ImmutableStack<Integer> popped = popRecursiveCallSites(context);
if (DEBUG) {
debugPrint("popped stack " + popped);
}
return popped;
} else {
return context.push(assignEdge.getCallSite());
}
}
protected boolean refineAlias(VarNode v1, VarNode v2,
PointsToSetInternal intersection, HeuristicType heuristic) {
if (refineAliasInternal(v1, v2, intersection, heuristic))
return true;
if (refineAliasInternal(v2, v1, intersection, heuristic))
return true;
return false;
}
protected boolean refineAliasInternal(VarNode v1, VarNode v2,
PointsToSetInternal intersection, HeuristicType heuristic) {
this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag
.getTypeManager(), getMaxPasses());
numPasses = 0;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
return false;
}
if (numPasses > maxPasses) {
return false;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
boolean success = false;
try {
AllocAndContextSet allocAndContexts = findContextsForAllocs(
new VarAndContext(v1, EMPTY_CALLSTACK), intersection);
boolean emptyIntersection = true;
for (AllocAndContext allocAndContext : allocAndContexts) {
CallingContextSet upContexts = findUpContextsForVar(
allocAndContext, new VarContextAndUp(v2,
EMPTY_CALLSTACK, EMPTY_CALLSTACK));
if (!upContexts.isEmpty()) {
emptyIntersection = false;
break;
}
}
success = emptyIntersection;
} catch (TerminateEarlyException e) {
success = false;
}
if (success) {
G.v().out.println("took " + numPasses + " passes");
return true;
} else {
if (!fieldCheckHeuristic.runNewPass()) {
return false;
}
}
}
}
protected Set<SootMethod> refineCallSite(Integer callSite,
ImmutableStack<Integer> origContext) {
CallSiteAndContext callSiteAndContext = new CallSiteAndContext(
callSite, origContext);
if (queriedCallSites.contains(callSiteAndContext)) {
// if (DEBUG_VIRT) {
// final SootMethod invokedMethod =
// csInfo.getInvokedMethod(callSite);
// final VarNode receiver =
// csInfo.getReceiverForVirtCallSite(callSite);
// debugPrint("call of " + invokedMethod + " on " + receiver + " "
// + origContext + " goes to "
// + callSiteToResolvedTargets.get(callSiteAndContext));
// }
return callSiteToResolvedTargets.get(callSiteAndContext);
}
if (callGraphStack.contains(callSiteAndContext)) {
return Collections.<SootMethod> emptySet();
} else {
callGraphStack.push(callSiteAndContext);
}
final VarNode receiver = csInfo.getReceiverForVirtCallSite(callSite);
final Type receiverType = receiver.getType();
final SootMethod invokedMethod = csInfo.getInvokedMethod(callSite);
final NumberedString methodSig = invokedMethod
.getNumberedSubSignature();
final Set<SootMethod> allTargets = csInfo.getCallSiteTargets(callSite);
if (!refineCallGraph) {
callGraphStack.pop();
return allTargets;
}
if (DEBUG_VIRT) {
debugPrint("refining call to " + invokedMethod + " on " + receiver
+ " " + origContext);
}
final HashSet<VarAndContext> marked = new HashSet<VarAndContext>();
final Stack<VarAndContext> worklist = new Stack<VarAndContext>();
final class Helper {
void prop(VarAndContext varAndContext) {
if (marked.add(varAndContext)) {
worklist.push(varAndContext);
}
}
}
;
final Helper h = new Helper();
h.prop(new VarAndContext(receiver, origContext));
while (!worklist.isEmpty()) {
incrementNodesTraversed();
VarAndContext curVarAndContext = worklist.pop();
if (DEBUG_VIRT) {
debugPrint("virt looking at " + curVarAndContext);
}
VarNode curVar = curVarAndContext.var;
ImmutableStack<Integer> curContext = curVarAndContext.context;
// Set<SootMethod> curVarTargets = getCallTargets(curVar.getP2Set(),
// methodSig, receiverType, allTargets);
// if (curVarTargets.size() <= 1) {
// for (SootMethod method : curVarTargets) {
// callSiteToResolvedTargets.put(callSiteAndContext, method);
// }
// continue;
// }
Node[] newNodes = pag.allocInvLookup(curVar);
for (int i = 0; i < newNodes.length; i++) {
AllocNode allocNode = (AllocNode) newNodes[i];
for (SootMethod method : getCallTargetsForType(allocNode
.getType(), methodSig, receiverType, allTargets)) {
callSiteToResolvedTargets.put(callSiteAndContext, method);
}
}
Collection<AssignEdge> assigns = filterAssigns(curVar, curContext,
true, true);
for (AssignEdge assignEdge : assigns) {
VarNode src = assignEdge.getSrc();
ImmutableStack<Integer> newContext = curContext;
if (assignEdge.isParamEdge()) {
if (!curContext.isEmpty()) {
if (!callEdgeInSCC(assignEdge)) {
assert assignEdge.getCallSite().equals(
curContext.peek());
newContext = curContext.pop();
} else {
newContext = popRecursiveCallSites(curContext);
}
} else {
callSiteToResolvedTargets.putAll(callSiteAndContext,
allTargets);
// if (DEBUG) {
// debugPrint("giving up on virt");
// }
continue;
}
} else if (assignEdge.isReturnEdge()) {
// if (DEBUG)
// G.v().out.println("entering call site "
// + assignEdge.getCallSite());
// if (!isRecursive(curContext, assignEdge)) {
// newContext = curContext.push(assignEdge.getCallSite());
// }
newContext = pushWithRecursionCheck(curContext, assignEdge);
} else if (src instanceof GlobalVarNode) {
newContext = EMPTY_CALLSTACK;
}
h.prop(new VarAndContext(src, newContext));
}
// TODO respect heuristic
Set<VarNode> matchSources = vMatches.vMatchInvLookup(curVar);
final boolean oneMatch = matchSources.size() == 1;
Node[] loads = pag.loadInvLookup(curVar);
for (int i = 0; i < loads.length; i++) {
FieldRefNode frNode = (FieldRefNode) loads[i];
final VarNode loadBase = frNode.getBase();
SparkField field = frNode.getField();
for (Pair<VarNode, VarNode> store : fieldToStores.get(field)) {
final VarNode storeBase = store.getO2();
final PointsToSetInternal storeBaseP2Set = storeBase
.getP2Set();
final PointsToSetInternal loadBaseP2Set = loadBase
.getP2Set();
final VarNode matchSrc = store.getO1();
if (matchSources.contains(matchSrc)) {
// optimize for common case of constructor init
boolean skipMatch = false;
if (oneMatch) {
PointsToSetInternal matchSrcPTo = matchSrc
.getP2Set();
Set<SootMethod> matchSrcCallTargets = getCallTargets(
matchSrcPTo, methodSig, receiverType,
allTargets);
if (matchSrcCallTargets.size() <= 1) {
skipMatch = true;
for (SootMethod method : matchSrcCallTargets) {
callSiteToResolvedTargets.put(
callSiteAndContext, method);
}
}
}
if (!skipMatch) {
final PointsToSetInternal intersection = SootUtil
.constructIntersection(storeBaseP2Set,
loadBaseP2Set, pag);
AllocAndContextSet allocContexts = null;
boolean oldRefining = refiningCallSite;
int oldNesting = nesting;
try {
refiningCallSite = true;
allocContexts = findContextsForAllocs(
new VarAndContext(loadBase, curContext),
intersection);
} catch (CallSiteException e) {
callSiteToResolvedTargets.putAll(
callSiteAndContext, allTargets);
continue;
} finally {
refiningCallSite = oldRefining;
nesting = oldNesting;
}
for (AllocAndContext allocAndContext : allocContexts) {
CallingContextSet matchSrcContexts;
if (fieldCheckHeuristic
.validFromBothEnds(field)) {
matchSrcContexts = findUpContextsForVar(
allocAndContext,
new VarContextAndUp(storeBase,
EMPTY_CALLSTACK,
EMPTY_CALLSTACK));
} else {
matchSrcContexts = findVarContextsFromAlloc(
allocAndContext, storeBase);
}
for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) {
VarAndContext newVarAndContext = new VarAndContext(
matchSrc, matchSrcContext);
h.prop(newVarAndContext);
}
}
}
}
}
}
}
if (DEBUG_VIRT) {
debugPrint("call of " + invokedMethod + " on " + receiver + " "
+ origContext + " goes to "
+ callSiteToResolvedTargets.get(callSiteAndContext));
}
callGraphStack.pop();
queriedCallSites.add(callSiteAndContext);
return callSiteToResolvedTargets.get(callSiteAndContext);
}
protected boolean refineP2Set(VarAndContext varAndContext,
final PointsToSetInternal badLocs) {
nesting++;
if (DEBUG) {
debugPrint("refining " + varAndContext);
}
final Set<VarAndContext> marked = new HashSet<VarAndContext>();
final Stack<VarAndContext> worklist = new Stack<VarAndContext>();
final Propagator<VarAndContext> p = new Propagator<VarAndContext>(
marked, worklist);
p.prop(varAndContext);
IncomingEdgeHandler edgeHandler = new IncomingEdgeHandler() {
boolean success = true;
@Override
public void handleAlloc(AllocNode allocNode,
VarAndContext origVarAndContext) {
if (doPointsTo && pointsTo != null) {
pointsTo.add(new AllocAndContext(allocNode,
origVarAndContext.context));
} else {
if (badLocs.contains(allocNode)) {
success = false;
}
}
}
@Override
public void handleMatchSrc(VarNode matchSrc,
PointsToSetInternal intersection, VarNode loadBase,
VarNode storeBase, VarAndContext origVarAndContext,
SparkField field, boolean refine) {
AllocAndContextSet allocContexts = findContextsForAllocs(
new VarAndContext(loadBase, origVarAndContext.context),
intersection);
for (AllocAndContext allocAndContext : allocContexts) {
if (DEBUG) {
debugPrint("alloc and context " + allocAndContext);
}
CallingContextSet matchSrcContexts;
if (fieldCheckHeuristic.validFromBothEnds(field)) {
matchSrcContexts = findUpContextsForVar(
allocAndContext, new VarContextAndUp(storeBase,
EMPTY_CALLSTACK, EMPTY_CALLSTACK));
} else {
matchSrcContexts = findVarContextsFromAlloc(
allocAndContext, storeBase);
}
for (ImmutableStack<Integer> matchSrcContext : matchSrcContexts) {
if (DEBUG)
debugPrint("match source context "
+ matchSrcContext);
VarAndContext newVarAndContext = new VarAndContext(
matchSrc, matchSrcContext);
p.prop(newVarAndContext);
}
}
}
Object getResult() {
return Boolean.valueOf(success);
}
@Override
void handleAssignSrc(VarAndContext newVarAndContext,
VarAndContext origVarAndContext, AssignEdge assignEdge) {
p.prop(newVarAndContext);
}
@Override
boolean shouldHandleSrc(VarNode src) {
if (doPointsTo) {
return true;
} else {
return src.getP2Set().hasNonEmptyIntersection(badLocs);
}
}
boolean terminate() {
return !success;
}
};
processIncomingEdges(edgeHandler, worklist);
nesting--;
return (Boolean) edgeHandler.getResult();
}
/*
* (non-Javadoc)
*
* @see AAA.summary.Refiner#refineP2Set(soot.jimple.spark.pag.VarNode,
* soot.jimple.spark.sets.PointsToSetInternal)
*/
protected boolean refineP2Set(VarNode v, PointsToSetInternal badLocs,
HeuristicType heuristic) {
// G.v().out.println(badLocs);
this.doPointsTo = false;
this.fieldCheckHeuristic = HeuristicType.getHeuristic(heuristic, pag
.getTypeManager(), getMaxPasses());
try {
numPasses = 0;
while (true) {
numPasses++;
if (DEBUG_PASS != -1 && numPasses > DEBUG_PASS) {
return false;
}
if (numPasses > maxPasses) {
return false;
}
if (DEBUG) {
G.v().out.println("PASS " + numPasses);
G.v().out.println(fieldCheckHeuristic);
}
clearState();
boolean success = false;
try {
success = refineP2Set(
new VarAndContext(v, EMPTY_CALLSTACK), badLocs);
} catch (TerminateEarlyException e) {
success = false;
}
if (success) {
return true;
} else {
if (!fieldCheckHeuristic.runNewPass()) {
return false;
}
}
}
} finally {
}
}
protected boolean weirdCall(Integer callSite) {
SootMethod invokedMethod = csInfo.getInvokedMethod(callSite);
return SootUtil.isThreadStartMethod(invokedMethod)
|| SootUtil.isNewInstanceMethod(invokedMethod);
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(Context c, Local l) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(Context c, Local l, SootField f) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(Local l, SootField f) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(PointsToSet s, SootField f) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjects(SootField f) {
throw new UnsupportedOperationException();
}
/**
* Currently not implemented.
*
* @throws UnsupportedOperationException
* always
*/
public PointsToSet reachingObjectsOfArrayElement(PointsToSet s) {
throw new UnsupportedOperationException();
}
/**
* @return returns the (SPARK) pointer assignment graph
*/
public PAG getPAG() {
return pag;
}
/**
* @return <code>true</code> is caching is enabled
*/
public boolean usesCache() {
return useCache;
}
/**
* enables caching
*/
public void enableCache() {
useCache = true;
}
/**
* disables caching
*/
public void disableCache() {
useCache = false;
}
/**
* clears the cache
*/
public void clearCache() {
reachingObjectsCache.clear();
reachingObjectsCacheNoCGRefinement.clear();
}
public boolean isRefineCallGraph() {
return refineCallGraph;
}
public void setRefineCallGraph(boolean refineCallGraph) {
this.refineCallGraph = refineCallGraph;
}
public HeuristicType getHeuristicType() {
return heuristicType;
}
public void setHeuristicType(HeuristicType heuristicType) {
this.heuristicType = heuristicType;
clearCache();
}
}
|
gpl-2.0
|
sergirams/puentes_humanos
|
wp-content/themes/Zephyr/comments.php
|
3624
|
<?php
if (!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME']))
die ('Please do not load this page directly. Thanks!');
if ( post_password_required() ) {
return;
}
?>
<div id="comments" class="w-comments has_form">
<?php if ( get_comments_number( get_the_ID() ) ) { ?>
<h4 class="w-comments-title"><?php comments_number('<i class="mdfi_communication_comment"></i>'.__('No comments', 'us'), '<i class="mdfi_communication_comment"></i>'.__('1 Comment.', 'us').' <a href="#respond">'.__('Leave new', 'us').'</a>', '<i class="mdfi_communication_comment"></i>'.__('% Comments.', 'us').' <a href="#respond">'.__('Leave new', 'us').'</a>' );?></h4>
<div class="w-comments-list">
<?php wp_list_comments(array( 'callback' => 'us_comment_start', 'end-callback' => 'us_comment_end', 'walker' => new Walker_Comments_US() )); ?>
</div>
<div class="g-pagination">
<?php previous_comments_link() ?>
<?php next_comments_link() ?>
</div>
<?php } ?>
<?php if ( comments_open() ) : ?>
<div id="respond" class="w-comments-form">
<?php /* <h4 class="w-comments-form-title"><?php comment_form_title(__('Leave comment', 'us'), __('Leave comment', 'us')); ?></h4> */ ?>
<?php if ( get_option('comment_registration') && !is_user_logged_in() ) { ?>
<div class="w-comments-form-text"><?php printf(__('You must be %slogged in%s to post a comment.', 'us'), '<a href="'.wp_login_url( get_permalink() ).'">', '</a>'); ?></div>
<?php } else {
$commenter = wp_get_current_commenter();
$req = get_option( 'require_name_email' );
$aria_req = ( $req ? " aria-required='true'" : '' );
$comment_form_fields = array(
'author' =>
'<p class="comment-form-author w-form-row"><span class="w-form-field">' .
'<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) .
'" size="30"' . $aria_req . ' />
<i class="mdfi_social_person"></i>
<label class="w-form-field-label" for="author">' . __( 'Name', 'us' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label>
<span class="w-form-field-bar"></span></span></p>',
'email' =>
'<p class="comment-form-email w-form-row"><span class="w-form-field">' .
'<input id="email" name="email" type="text" value="' . esc_attr( $commenter['comment_author_email'] ) .
'" size="30"' . $aria_req . ' />
<i class="mdfi_communication_email"></i>
<label class="w-form-field-label" for="email">' . __( 'Email', 'us' ) .( $req ? ' <span class="required">*</span>' : '' ) . '</label>
<span class="w-form-field-bar"></span></span></p>',
'url' =>
'<p class="comment-form-url w-form-row"><span class="w-form-field">' .
'<input id="url" name="url" type="text" value="' . esc_attr( $commenter['comment_author_url'] ) .
'" size="30" />
<i class="mdfi_content_link"></i>
<label class="w-form-field-label" for="url">' . __( 'Website', 'us' ) . '</label>
<span class="w-form-field-bar"></span></span></p>',
);
$comment_form_args = array(
'comment_field' => '<p class="comment-form-comment w-form-row"><span class="w-form-field">
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true">' .
'</textarea>
<i class="mdfi_content_create"></i>
<label class="w-form-field-label" for="comment">' . _x( 'Comment', 'noun', 'us' ) .
'</label>
<span class="w-form-field-bar"></span></span></p>',
'fields' => apply_filters( 'comment_form_default_fields', $comment_form_fields ),
);
comment_form($comment_form_args);
} ?>
</div>
<?php endif;?>
</div>
|
gpl-2.0
|
studioego/kwidgetsaddons
|
src/kruler.cpp
|
17870
|
/* This file is part of the KDE libraries
Copyright (C) 1998 Jörg Habenicht (j.habenicht@europemail.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kruler.h"
#include <QFont>
#include <QPolygon>
#include <QStylePainter>
#define INIT_VALUE 0
#define INIT_MIN_VALUE 0
#define INIT_MAX_VALUE 100
#define INIT_TINY_MARK_DISTANCE 1
#define INIT_LITTLE_MARK_DISTANCE 5
#define INIT_MIDDLE_MARK_DISTANCE (INIT_LITTLE_MARK_DISTANCE * 2)
#define INIT_BIG_MARK_DISTANCE (INIT_LITTLE_MARK_DISTANCE * 10)
#define INIT_SHOW_TINY_MARK false
#define INIT_SHOW_LITTLE_MARK true
#define INIT_SHOW_MEDIUM_MARK true
#define INIT_SHOW_BIG_MARK true
#define INIT_SHOW_END_MARK true
#define INIT_SHOW_POINTER true
#define INIT_SHOW_END_LABEL true
#define INIT_PIXEL_PER_MARK (double)10.0 /* distance between 2 base marks in pixel */
#define INIT_OFFSET (-20)
#define INIT_LENGTH_FIX true
#define INIT_END_OFFSET 0
#define FIX_WIDTH 20 /* widget width in pixel */
#define LINE_END (FIX_WIDTH - 3)
#define END_MARK_LENGTH (FIX_WIDTH - 6)
#define END_MARK_X2 LINE_END
#define END_MARK_X1 (END_MARK_X2 - END_MARK_LENGTH)
#define BIG_MARK_LENGTH (END_MARK_LENGTH*3/4)
#define BIG_MARK_X2 LINE_END
#define BIG_MARK_X1 (BIG_MARK_X2 - BIG_MARK_LENGTH)
#define MIDDLE_MARK_LENGTH (END_MARK_LENGTH/2)
#define MIDDLE_MARK_X2 LINE_END
#define MIDDLE_MARK_X1 (MIDDLE_MARK_X2 - MIDDLE_MARK_LENGTH)
#define LITTLE_MARK_LENGTH (MIDDLE_MARK_LENGTH/2)
#define LITTLE_MARK_X2 LINE_END
#define LITTLE_MARK_X1 (LITTLE_MARK_X2 - LITTLE_MARK_LENGTH)
#define BASE_MARK_LENGTH (LITTLE_MARK_LENGTH/2)
#define BASE_MARK_X2 LINE_END
#define BASE_MARK_X1 (BASE_MARK_X2 - BASE_MARK_LENGTH)
#define LABEL_SIZE 8
#define END_LABEL_X 4
#define END_LABEL_Y (END_LABEL_X + LABEL_SIZE - 2)
#undef PROFILING
#ifdef PROFILING
# include <qdatetime.h>
#endif
class Q_DECL_HIDDEN KRuler::KRulerPrivate
{
public:
int endOffset_length; /* marks the offset at the end of the ruler
* i.e. right side at horizontal and down side
* at vertical rulers.
* the ruler end mark is moved endOffset_length
* ticks away from the widget end.
* positive offset moves end mark inside the ruler.
* if lengthFix is true, endOffset_length holds the
* length of the ruler.
*/
int fontWidth; // ONLY valid for vertical rulers
QAbstractSlider range;
Qt::Orientation dir;
int tmDist;
int lmDist;
int mmDist;
int bmDist;
int offset;
bool showtm : 1; /* show tiny, little, medium, big, endmarks */
bool showlm : 1;
bool showmm : 1;
bool showbm : 1;
bool showem : 1;
bool showpointer : 1;
bool showEndL : 1;
bool lengthFix : 1;
double ppm; /* pixel per mark */
QString endlabel;
};
KRuler::KRuler(QWidget *parent)
: QAbstractSlider(parent)
, d(new KRulerPrivate)
{
setRange(INIT_MIN_VALUE, INIT_MAX_VALUE);
setPageStep(10);
setValue(INIT_VALUE);
initWidget(Qt::Horizontal);
setFixedHeight(FIX_WIDTH);
}
KRuler::KRuler(Qt::Orientation orient,
QWidget *parent, Qt::WindowFlags f)
: QAbstractSlider(parent)
, d(new KRulerPrivate)
{
setRange(INIT_MIN_VALUE, INIT_MAX_VALUE);
setPageStep(10);
setValue(INIT_VALUE);
setWindowFlags(f);
initWidget(orient);
if (orient == Qt::Horizontal) {
setFixedHeight(FIX_WIDTH);
} else {
setFixedWidth(FIX_WIDTH);
}
}
KRuler::KRuler(Qt::Orientation orient, int widgetWidth,
QWidget *parent, Qt::WindowFlags f)
: QAbstractSlider(parent)
, d(new KRulerPrivate)
{
setRange(INIT_MIN_VALUE, INIT_MAX_VALUE);
setPageStep(10);
setValue(INIT_VALUE);
setWindowFlags(f);
initWidget(orient);
if (orient == Qt::Horizontal) {
setFixedHeight(widgetWidth);
} else {
setFixedWidth(widgetWidth);
}
}
void KRuler::initWidget(Qt::Orientation orientation)
{
#ifdef __GNUC__
#warning FIXME setFrameStyle(WinPanel | Raised);
#endif
d->showpointer = INIT_SHOW_POINTER;
d->showEndL = INIT_SHOW_END_LABEL;
d->lengthFix = INIT_LENGTH_FIX;
d->endOffset_length = INIT_END_OFFSET;
d->tmDist = INIT_TINY_MARK_DISTANCE;
d->lmDist = INIT_LITTLE_MARK_DISTANCE;
d->mmDist = INIT_MIDDLE_MARK_DISTANCE;
d->bmDist = INIT_BIG_MARK_DISTANCE;
d->offset = INIT_OFFSET;
d->showtm = INIT_SHOW_TINY_MARK;
d->showlm = INIT_SHOW_LITTLE_MARK;
d->showmm = INIT_SHOW_MEDIUM_MARK;
d->showbm = INIT_SHOW_BIG_MARK;
d->showem = INIT_SHOW_END_MARK;
d->ppm = INIT_PIXEL_PER_MARK;
d->dir = orientation;
}
KRuler::~KRuler()
{
delete d;
}
#ifndef KWIDGETSADDONS_NO_DEPRECATED
void
KRuler::setMinValue(int value)
{
setMinimum(value);
}
#endif
#ifndef KWIDGETSADDONS_NO_DEPRECATED
int
KRuler::minValue() const
{
return minimum();
}
#endif
#ifndef KWIDGETSADDONS_NO_DEPRECATED
void
KRuler::setMaxValue(int value)
{
setMaximum(value);
}
#endif
#ifndef KWIDGETSADDONS_NO_DEPRECATED
int
KRuler::maxValue() const
{
return maximum();
}
#endif
void
KRuler::setTinyMarkDistance(int dist)
{
if (dist != d->tmDist) {
d->tmDist = dist;
update(contentsRect());
}
}
int
KRuler::tinyMarkDistance() const
{
return d->tmDist;
}
void
KRuler::setLittleMarkDistance(int dist)
{
if (dist != d->lmDist) {
d->lmDist = dist;
update(contentsRect());
}
}
int
KRuler::littleMarkDistance() const
{
return d->lmDist;
}
void
KRuler::setMediumMarkDistance(int dist)
{
if (dist != d->mmDist) {
d->mmDist = dist;
update(contentsRect());
}
}
int
KRuler::mediumMarkDistance() const
{
return d->mmDist;
}
void
KRuler::setBigMarkDistance(int dist)
{
if (dist != d->bmDist) {
d->bmDist = dist;
update(contentsRect());
}
}
int
KRuler::bigMarkDistance() const
{
return d->bmDist;
}
void
KRuler::setShowTinyMarks(bool show)
{
if (show != d->showtm) {
d->showtm = show;
update(contentsRect());
}
}
bool
KRuler::showTinyMarks() const
{
return d->showtm;
}
void
KRuler::setShowLittleMarks(bool show)
{
if (show != d->showlm) {
d->showlm = show;
update(contentsRect());
}
}
bool
KRuler::showLittleMarks() const
{
return d->showlm;
}
void
KRuler::setShowMediumMarks(bool show)
{
if (show != d->showmm) {
d->showmm = show;
update(contentsRect());
}
}
bool
KRuler::showMediumMarks() const
{
return d->showmm;
}
void
KRuler::setShowBigMarks(bool show)
{
if (show != d->showbm) {
d->showbm = show;
update(contentsRect());
}
}
bool
KRuler::showBigMarks() const
{
return d->showbm;
}
void
KRuler::setShowEndMarks(bool show)
{
if (show != d->showem) {
d->showem = show;
update(contentsRect());
}
}
bool
KRuler::showEndMarks() const
{
return d->showem;
}
void
KRuler::setShowPointer(bool show)
{
if (show != d->showpointer) {
d->showpointer = show;
update(contentsRect());
}
}
bool
KRuler::showPointer() const
{
return d->showpointer;
}
#ifndef KWIDGETSADDONS_NO_DEPRECATED
void
KRuler::setFrameStyle(int)
{
}
#endif
void
KRuler::setShowEndLabel(bool show)
{
if (d->showEndL != show) {
d->showEndL = show;
update(contentsRect());
}
}
bool
KRuler::showEndLabel() const
{
return d->showEndL;
}
void
KRuler::setEndLabel(const QString &label)
{
d->endlabel = label;
// premeasure the fontwidth and save it
if (d->dir == Qt::Vertical) {
QFont font = this->font();
font.setPointSize(LABEL_SIZE);
QFontMetrics fm(font);
d->fontWidth = fm.width(d->endlabel);
}
update(contentsRect());
}
QString KRuler::endLabel() const
{
return d->endlabel;
}
void
KRuler::setRulerMetricStyle(KRuler::MetricStyle style)
{
switch (style) {
default: /* fall through */
case Custom:
return;
case Pixel:
setLittleMarkDistance(1);
setMediumMarkDistance(5);
setBigMarkDistance(10);
setShowTinyMarks(false);
setShowLittleMarks(true);
setShowMediumMarks(true);
setShowBigMarks(true);
setShowEndMarks(true);
update(contentsRect());
setPixelPerMark(10.0);
break;
case Inch:
setTinyMarkDistance(1);
setLittleMarkDistance(2);
setMediumMarkDistance(4);
setBigMarkDistance(8);
setShowTinyMarks(true);
setShowLittleMarks(true);
setShowMediumMarks(true);
setShowBigMarks(true);
setShowEndMarks(true);
update(contentsRect());
setPixelPerMark(9.0);
break;
case Millimetres: /* fall through */
case Centimetres: /* fall through */
case Metres:
setLittleMarkDistance(1);
setMediumMarkDistance(5);
setBigMarkDistance(10);
setShowTinyMarks(false);
setShowLittleMarks(true);
setShowMediumMarks(true);
setShowBigMarks(true);
setShowEndMarks(true);
update(contentsRect());
setPixelPerMark(3.0);
}
switch (style) {
case Pixel:
setEndLabel(QStringLiteral("pixel"));
break;
case Inch:
setEndLabel(QStringLiteral("inch"));
break;
case Millimetres:
setEndLabel(QStringLiteral("mm"));
break;
case Centimetres:
setEndLabel(QStringLiteral("cm"));
break;
case Metres:
setEndLabel(QStringLiteral("m"));
default: /* never reached, see above switch */
/* empty command */;
}
// if the style changes one of the values,
// update would have been called inside the methods
// -> no update() call needed here !
}
void
KRuler::setPixelPerMark(double rate)
{
// never compare floats against each other :)
d->ppm = rate;
update(contentsRect());
}
double
KRuler::pixelPerMark() const
{
return d->ppm;
}
void
KRuler::setLength(int length)
{
int tmp;
if (d->lengthFix) {
tmp = length;
} else {
tmp = width() - length;
}
if (tmp != d->endOffset_length) {
d->endOffset_length = tmp;
update(contentsRect());
}
}
int
KRuler::length() const
{
if (d->lengthFix) {
return d->endOffset_length;
}
return (width() - d->endOffset_length);
}
void
KRuler::setLengthFixed(bool fix)
{
d->lengthFix = fix;
}
bool
KRuler::lengthFixed() const
{
return d->lengthFix;
}
void
KRuler::setOffset(int _offset)
{
// debug("set offset %i", _offset);
if (d->offset != _offset) {
d->offset = _offset;
update(contentsRect());
}
}
int
KRuler::offset() const
{
return d->offset;
}
int
KRuler::endOffset() const
{
if (d->lengthFix) {
return (width() - d->endOffset_length);
}
return d->endOffset_length;
}
void
KRuler::slideUp(int count)
{
if (count) {
d->offset += count;
update(contentsRect());
}
}
void
KRuler::slideDown(int count)
{
if (count) {
d->offset -= count;
update(contentsRect());
}
}
void
KRuler::slotNewValue(int _value)
{
int oldvalue = value();
if (oldvalue == _value) {
return;
}
// setValue(_value);
setValue(_value);
if (value() == oldvalue) {
return;
}
// get the rectangular of the old and the new ruler pointer
// and repaint only him
if (d->dir == Qt::Horizontal) {
QRect oldrec(-5 + oldvalue, 10, 11, 6);
QRect newrec(-5 + _value, 10, 11, 6);
repaint(oldrec.united(newrec));
} else {
QRect oldrec(10, -5 + oldvalue, 6, 11);
QRect newrec(10, -5 + _value, 6, 11);
repaint(oldrec.united(newrec));
}
}
void
KRuler::slotNewOffset(int _offset)
{
if (d->offset != _offset) {
//setOffset(_offset);
d->offset = _offset;
repaint(contentsRect());
}
}
void
KRuler::slotEndOffset(int offset)
{
int tmp;
if (d->lengthFix) {
tmp = width() - offset;
} else {
tmp = offset;
}
if (d->endOffset_length != tmp) {
d->endOffset_length = tmp;
repaint(contentsRect());
}
}
void
KRuler::paintEvent(QPaintEvent * /*e*/)
{
// debug ("KRuler::drawContents, %s",(horizontal==dir)?"horizontal":"vertical");
QStylePainter p(this);
#ifdef PROFILING
QTime time;
time.start();
for (int profile = 0; profile < 10; profile++) {
#endif
int value = this->value(),
minval = minimum(),
maxval;
if (d->dir == Qt::Horizontal) {
maxval = maximum()
+ d->offset
- (d->lengthFix ? (height() - d->endOffset_length) : d->endOffset_length);
} else {
maxval = maximum()
+ d->offset
- (d->lengthFix ? (width() - d->endOffset_length) : d->endOffset_length);
}
//ioffsetval = value-offset;
// pixelpm = (int)ppm;
// left = clip.left(),
// right = clip.right();
double f, fend,
offsetmin = (double)(minval - d->offset),
offsetmax = (double)(maxval - d->offset),
fontOffset = (((double)minval) > offsetmin) ? (double)minval : offsetmin;
// draw labels
QFont font = p.font();
font.setPointSize(LABEL_SIZE);
p.setFont(font);
// draw littlemarklabel
// draw mediummarklabel
// draw bigmarklabel
// draw endlabel
if (d->showEndL) {
if (d->dir == Qt::Horizontal) {
p.translate(fontOffset, 0);
p.drawText(END_LABEL_X, END_LABEL_Y, d->endlabel);
} else { // rotate text +pi/2 and move down a bit
//QFontMetrics fm(font);
#ifdef KRULER_ROTATE_TEST
p.rotate(-90.0 + rotate);
p.translate(-8.0 - fontOffset - d->fontWidth + xtrans,
ytrans);
#else
p.rotate(-90.0);
p.translate(-8.0 - fontOffset - d->fontWidth, 0.0);
#endif
p.drawText(END_LABEL_X, END_LABEL_Y, d->endlabel);
}
p.resetMatrix();
}
// draw the tiny marks
if (d->showtm) {
fend = d->ppm * d->tmDist;
for (f = offsetmin; f < offsetmax; f += fend) {
if (d->dir == Qt::Horizontal) {
p.drawLine((int)f, BASE_MARK_X1, (int)f, BASE_MARK_X2);
} else {
p.drawLine(BASE_MARK_X1, (int)f, BASE_MARK_X2, (int)f);
}
}
}
if (d->showlm) {
// draw the little marks
fend = d->ppm * d->lmDist;
for (f = offsetmin; f < offsetmax; f += fend) {
if (d->dir == Qt::Horizontal) {
p.drawLine((int)f, LITTLE_MARK_X1, (int)f, LITTLE_MARK_X2);
} else {
p.drawLine(LITTLE_MARK_X1, (int)f, LITTLE_MARK_X2, (int)f);
}
}
}
if (d->showmm) {
// draw medium marks
fend = d->ppm * d->mmDist;
for (f = offsetmin; f < offsetmax; f += fend) {
if (d->dir == Qt::Horizontal) {
p.drawLine((int)f, MIDDLE_MARK_X1, (int)f, MIDDLE_MARK_X2);
} else {
p.drawLine(MIDDLE_MARK_X1, (int)f, MIDDLE_MARK_X2, (int)f);
}
}
}
if (d->showbm) {
// draw big marks
fend = d->ppm * d->bmDist;
for (f = offsetmin; f < offsetmax; f += fend) {
if (d->dir == Qt::Horizontal) {
p.drawLine((int)f, BIG_MARK_X1, (int)f, BIG_MARK_X2);
} else {
p.drawLine(BIG_MARK_X1, (int)f, BIG_MARK_X2, (int)f);
}
}
}
if (d->showem) {
// draw end marks
if (d->dir == Qt::Horizontal) {
p.drawLine(minval - d->offset, END_MARK_X1, minval - d->offset, END_MARK_X2);
p.drawLine(maxval - d->offset, END_MARK_X1, maxval - d->offset, END_MARK_X2);
} else {
p.drawLine(END_MARK_X1, minval - d->offset, END_MARK_X2, minval - d->offset);
p.drawLine(END_MARK_X1, maxval - d->offset, END_MARK_X2, maxval - d->offset);
}
}
// draw pointer
if (d->showpointer) {
QPolygon pa(4);
if (d->dir == Qt::Horizontal) {
pa.setPoints(3, value - 5, 10, value + 5, 10, value/*+0*/, 15);
} else {
pa.setPoints(3, 10, value - 5, 10, value + 5, 15, value/*+0*/);
}
p.setBrush(p.background().color());
p.drawPolygon(pa);
}
#ifdef PROFILING
}
int elapsed = time.elapsed();
debug("paint time %i", elapsed);
#endif
}
|
gpl-2.0
|
foxbei/joomla16
|
templates/yoo_expo/layouts/com_content/article/default.php
|
3816
|
<?php
/**
* @package yoo_expo Template
* @file default.php
* @version 5.5.0 January 2011
* @author YOOtheme http://www.yootheme.com
* @copyright Copyright (C) 2007 - 2011 YOOtheme GmbH
* @license YOOtheme Proprietary Use License (http://www.yootheme.com/license)
*/
// no direct access
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT.DS.'helpers');
// Create shortcuts to some parameters.
$params = $this->item->params;
$canEdit = $this->item->params->get('access-edit');
?>
<div id="system" class="<?php $this->pageclass_sfx; ?>">
<?php if ($this->params->get('show_page_heading', 1)) : ?>
<h1 class="title"><?php echo $this->escape($this->params->get('page_heading')); ?></h1>
<?php endif; ?>
<div class="item">
<?php if (!$this->print) : ?>
<?php if ($params->get('show_email_icon')) : ?>
<div class="icon email"><?php echo JHtml::_('icon.email', $this->item, $params); ?></div>
<?php endif; ?>
<?php if ($params->get('show_print_icon')) : ?>
<div class="icon print"><?php echo JHtml::_('icon.print_popup', $this->item, $params); ?></div>
<?php endif; ?>
<?php else : ?>
<div class="icon printscreen"><?php echo JHtml::_('icon.print_screen', $this->item, $params); ?></div>
<?php endif; ?>
<?php if ($params->get('show_create_date')) : ?>
<div class="date">
<div class="day"><?php echo JHTML::_('date',$this->item->created, JText::_('d')); ?></div>
<div class="month"><?php echo JHTML::_('date',$this->item->created, JText::_('F')); ?></div>
<div class="year"><?php echo JHTML::_('date',$this->item->created, JText::_('Y')); ?></div>
</div>
<?php endif; ?>
<?php if ($params->get('show_title')|| $params->get('access-edit')) : ?>
<h1 class="title">
<?php if ($params->get('link_titles') && !empty($this->item->readmore_link)) : ?>
<a href="<?php echo $this->item->readmore_link; ?>"><?php echo $this->escape($this->item->title); ?></a>
<?php else : ?>
<?php echo $this->escape($this->item->title); ?>
<?php endif; ?>
</h1>
<?php endif; ?>
<?php
if (!$params->get('show_intro')) {
echo $this->item->event->afterDisplayTitle;
}
echo $this->item->event->beforeDisplayContent;
if (isset ($this->item->toc)) {
echo $this->item->toc;
}
?>
<div class="content"><?php echo $this->item->text; ?></div>
<?php if (($params->get('show_author') && !empty($this->item->author)) || $params->get('show_category')) : ?>
<p class="meta">
<?php
if ($params->get('show_author') && !empty($this->item->author )) {
$author = $this->item->author;
$author = ($this->item->created_by_alias ? $this->item->created_by_alias : $author);
if (!empty($this->item->contactid ) && $params->get('link_author') == true) {
echo '<span><span>'.JText::_('JAUTHOR').':</span> '.JHTML::_('link',JRoute::_('index.php?option=com_contact&view=contact&id='.$this->item->contactid),$author).'</span>';
} else {
echo '<span><span>'.JText::_('JAUTHOR').':</span> '.$author.'</span>';
}
}
if ($params->get('show_category')) {
echo '<span><span>'.JText::_('TPL_WARP_POSTED_IN').':</span> ';
$title = $this->escape($this->item->category_title);
$url = '<a href="'.JRoute::_(ContentHelperRoute::getCategoryRoute($this->item->catslug)).'">'.$title.'</a>';
if ($params->get('link_category') AND $this->item->catslug) {
echo $url.'</span>';
} else {
echo $title.'</span>';
}
}
?>
</p>
<?php endif; ?>
<?php if ($canEdit) : ?>
<p class="edit"><?php echo JHtml::_('icon.edit', $this->item, $params); ?> <?php echo JText::_('TPL_WARP_EDIT_ARTICLE'); ?></p>
<?php endif; ?>
<?php echo $this->item->event->afterDisplayContent; ?>
</div>
</div>
|
gpl-2.0
|
soeffing/openx_test
|
lib/OX/Extension/deliveryAdRender.php
|
1966
|
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.org/ |
| |
| 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 |
+---------------------------------------------------------------------------+
$Id: deliveryAdRender.php 81439 2012-05-07 23:59:14Z chris.nutting $
*/
require_once(LIB_PATH.'/Extension/ExtensionDelivery.php');
/**
* @package OpenXExtension
* @subpackage DeliveryAdRender
*/
class OX_Extension_deliveryAdRender extends OX_Extension_Delivery
{
function __construct()
{
}
}
?>
|
gpl-2.0
|
CombustibleLemonade/KnowledgeNet
|
Scripts/Base/Base.cpp
|
1681
|
#include <iostream>
#include <vector>
#include "Base.h"
#include "Defaults.h"
namespace KNOW
{
Profiler::Profiler()
{
Measure.restart();
}
sf::Time Profiler::operator ()()
{
sf::Time Delta = Measure.getElapsedTime();
Measure.restart();
return Delta;
}
sf::Vector2f AbsoluteMousePosition(sf::RenderWindow& RelativeWindow)
{
sf::Vector2f Position =
sf::Vector2f(sf::Mouse::getPosition(RelativeWindow));
sf::View WindowView = RelativeWindow.getView();
sf::Vector2f WindowSize = sf::Vector2f(RelativeWindow.getSize());
sf::Vector2f ViewSize = sf::Vector2f(WindowView.getSize());
sf::Vector2f MousePos;
float Zoom = ViewSize.x/WindowSize.x;
MousePos.x = (Position.x/ViewSize.x)*WindowView.getSize().x;
MousePos.y = (Position.y/ViewSize.y)*WindowView.getSize().y;
MousePos += WindowView.getCenter()/Zoom-WindowSize/2.0f;
MousePos *= Zoom;
return MousePos;
}
void BaseDrawFunc()
{}
bool CursorCollisionCheck(sf::FloatRect CollisionShape)
{
sf::Vector2f Position = AbsoluteMousePosition(KNOW::DefaultWindow);
return CollisionShape.contains(Position);
}
bool CursorCollisionCheck(sf::FloatRect CollisionShape, float Zoom)
{
sf::Vector2f Position = AbsoluteMousePosition(KNOW::DefaultWindow);
return CollisionShape.contains(Position);
}
void CenterOrigin(sf::Sprite &SpriteToCenter)
{
sf::FloatRect SpriteRect = SpriteToCenter.getLocalBounds();
SpriteToCenter.setOrigin(SpriteRect.width/2, SpriteRect.height/2);
}
}
|
gpl-2.0
|
lclsdu/CS
|
jspxcms/src/com/jspxcms/ext/repository/AdDaoPlus.java
|
318
|
package com.jspxcms.ext.repository;
import java.util.List;
import com.jspxcms.common.orm.Limitable;
import com.jspxcms.ext.domain.Ad;
/**
* AdDaoPlus
*
* @author liufang
*
*/
public interface AdDaoPlus {
public List<Ad> findList(Integer[] siteId, String[] slot, Integer[] slotId,
Limitable limitable);
}
|
gpl-2.0
|
plechev-64/wp-recall
|
add-on/prime-forum/classes/class-prime-last-posts.php
|
3407
|
<?php
class PrimeLastPosts {
public $number = 5;
public $name_length = 30;
public $post_length = 120;
public $avatar_size = 40;
public $topics = array();
public $posts = array();
function __construct( $args ) {
$this->init_properties( $args );
$this->topics = $this->get_topics();
$this->posts = $this->get_posts();
}
function init_properties( $args ) {
$properties = get_class_vars( get_class( $this ) );
foreach ( $properties as $name => $val ) {
if ( isset( $args[$name] ) )
$this->$name = $args[$name];
}
}
function get_topics() {
$PrimePosts = new PrimePosts();
$query = RQ::tbl( new PrimeTopics() )
->join( ['topic_id', 'topic_id' ], $PrimePosts )
->limit( $this->number )
->groupby( 'topic_id' )
->orderby( "MAX(" . $PrimePosts->get_colname( 'post_date' ) . ")", 'DESC', false );
$query = apply_filters( 'pfm_last_topics_query', $query );
return $query->get_results( 'cache' );
}
function get_posts() {
global $wpdb;
if ( ! $this->topics )
return false;
$tIDs = array();
foreach ( $this->topics as $topic ) {
$tIDs[] = $topic->topic_id;
}
$args = array(
'select' => array(
'topic_id',
'post_id',
'post_content',
'user_id'
),
'topic_id__in' => $tIDs,
'orderby' => 'post_date'
);
$posts = RQ::tbl( new PrimePosts() )
->parse( apply_filters( 'pfm_last_posts_query_args', $args ) )
->get_results();
if ( ! $posts )
return false;
return $posts;
}
function string_trim( $string, $length ) {
$string = strip_shortcodes( $string );
if ( iconv_strlen( $string = strip_tags( $string ), 'utf-8' ) > $length ) {
$string = iconv_substr( $string, 0, $length, 'utf-8' );
$string = preg_replace( '@(.*)\s[^\s]*$@s', '\\1', $string ) . '...';
}
return $string;
}
function get_post_by_topic( $topic_id ) {
if ( ! $this->posts )
return false;
foreach ( $this->posts as $post ) {
if ( $post->topic_id == $topic_id )
return $post;
}
return false;
}
function get_content() {
if ( ! $this->topics )
return false;
$content = '<div class="prime-last-posts">';
$content .= '<ul class="last-post-list">';
foreach ( $this->topics as $topic ) {
$post = $this->get_post_by_topic( $topic->topic_id );
$url = pfm_get_post_permalink( $post->post_id );
$content .= '<li class="last-post-box">';
if ( $this->avatar_size ) {
$content .= '<div class="last-post-author-avatar">
<a href="' . $url . '">' . get_avatar( $post->user_id, $this->avatar_size ) . '</a>
</div>';
}
if ( $this->name_length ) {
$content .= '<div class="last-post-title">
<a href="' . $url . '">
' . ($topic->topic_closed ? '<i class="rcli fa-lock"></i>' : '') . ' ' . $this->string_trim( $topic->topic_name, $this->name_length ) . '
</a>
</div>';
}
if ( $this->post_length ) {
$content .= '<div class="last-post-content">
' . $this->string_trim( $post->post_content, $this->post_length ) . ' '
. '<a class="last-post-more" href=' . $url . '> ' . __( 'Read more', 'wp-recall' ) . '</a>
</div>';
}
$content .= '</li>';
}
$content .= '</ul>';
$content .= '</div>';
return $content;
}
}
|
gpl-2.0
|
MagicMediaInc/blaine
|
wp-content/themes/mediacenter/framework/inc/custom-styles.php
|
3399
|
<?php
if ( !function_exists ('media_center_custom_styles') ) :
function media_center_custom_styles() {
global $media_center_theme_options;
$default_font_family = isset( $media_center_theme_options['default_font'] ) ? $media_center_theme_options[ 'default_font' ] : '\'Open Sans\', sans-serif;';
$title_font_family = isset( $media_center_theme_options['title_font'] ) ? $media_center_theme_options[ 'title_font' ] : '\'Open Sans\', sans-serif;';
?>
<!-- ===================== Theme Options Styles ===================== -->
<style type="text/css">
/* Typography */
h1, .h1,
h2, .h2,
h3, .h3,
h4, .h4,
h5, .h5,
h6, .h6{
font-family: <?php echo $title_font_family['font-family']; ?>;
}
body{
font-family: <?php echo $default_font_family['font-family']; ?>;
}
/* Animation */
<?php if ( $media_center_theme_options['top_bar_left_menu_dropdown_animation'] != 'none' ): ?>
.top-left .open > .dropdown-menu,
.top-left .open > .dropdown-menu > .dropdown-submenu > .dropdown-menu {
animation-name: <?php echo $media_center_theme_options['top_bar_left_menu_dropdown_animation']; ?>;
}
<?php endif; ?>
<?php if ( $media_center_theme_options['top_bar_right_menu_dropdown_animation'] != 'none' ): ?>
.top-right .open > .dropdown-menu,
.top-right .open > .dropdown-menu > .dropdown-submenu > .dropdown-menu {
animation-name: <?php echo $media_center_theme_options['top_bar_right_menu_dropdown_animation']; ?>;
}
<?php endif; ?>
<?php if ( $media_center_theme_options['main_navigation_menu_dropdown_animation'] != 'none' ): ?>
#top-megamenu-nav .open > .dropdown-menu,
#top-megamenu-nav .open > .dropdown-menu > .dropdown-submenu > .dropdown-menu {
animation-name: <?php echo $media_center_theme_options['main_navigation_menu_dropdown_animation']; ?>;
}
<?php endif; ?>
<?php if ( $media_center_theme_options['shop_by_departments_menu_dropdown_animation'] != 'none' ): ?>
#top-mega-nav .open > .dropdown-menu,
#top-mega-nav .open > .dropdown-menu > .dropdown-submenu > .dropdown-menu {
animation-name: <?php echo $media_center_theme_options['shop_by_departments_menu_dropdown_animation']; ?>;
}
<?php endif; ?>
/* Product Labels */
<?php
$product_labels = get_categories( array( 'taxonomy' => 'product_label') );
$product_label_css = '';
if ( $product_labels && ! is_wp_error( $product_labels ) && empty( $product_labels['errors'] ) ){
foreach( $product_labels as $product_label ){
if( isset( $product_label->term_id ) ){
$background_color = get_woocommerce_term_meta( $product_label->term_id , 'background_color', true );
$text_color = get_woocommerce_term_meta( $product_label->term_id , 'text_color', true );
$product_label_css .= '.label-' . $product_label->slug . ' > span {';
$product_label_css .= 'color: '. $text_color . ';';
$product_label_css .= '}';
$product_label_css .= '.label-' .$product_label->slug . '.ribbon:after {';
$product_label_css .= 'border-top-color: '. $background_color . ';';
$product_label_css .= '}';
}
}
}
echo $product_label_css;
?>
/* Custom CSS */
<?php
if ( ( isset( $media_center_theme_options['custom_css'] ) ) && ( trim( $media_center_theme_options['custom_css'] ) != "" ) ) {
echo $media_center_theme_options['custom_css'];
}
?>
</style>
<!-- ===================== Theme Options Styles : END ===================== -->
<?php
}
add_action( 'wp_head', 'media_center_custom_styles', 100 );
endif;
|
gpl-2.0
|
patdunlavey/imusgeographics.com
|
sites/all/modules/fb/themes/fb_fbml/node.tpl.php
|
1245
|
<?php
// $Id: node.tpl.php,v 1.9 2010/03/25 19:23:11 yogadex Exp $
/**
* @file
* FBML node template.
*/
$class = "class=\"node node-$type";
if ($sticky)
$class .= " sticky";
if (!$status)
$class .= " node-unpublished";
$class .= "\"";
if (isset($extra_style))
$style = "style = \"$extra_style\"";
?>
<div <?php print $class; ?> <?php print((isset($style)) ? $style : ''); ?>>
<?php if ($picture || $page == 0 || $submitted || $terms) { ?>
<div class="node-header">
<?php if ($picture && $submitted) {
print $picture;
} ?>
<?php if ($page == 0) { ?>
<h2 class="title"><a href="<?php print $node_url?>"><?php print $title?></a></h2>
<?php }; ?>
<span class="submitted"><?php print $submitted?></span>
<span class="taxonomy"><?php print $terms?></span>
</div>
<?php } ?>
<div class="content"><?php print $content?></div>
<div class="footer">
<?php if ($links) { ?>
<div class="links"><?php print $links?></div>
<?php }; ?>
</div>
<?php if ($node_bottom && !$teaser): ?>
<div id="node-bottom">
<?php print $node_bottom; ?>
</div>
<?php endif; ?>
<?php if (isset($children)) { ?>
<div class="children" id="children_<?php print $node->nid; ?>">
<?php print $children; ?>
</div>
<?php } /* end if children */ ?>
</div>
|
gpl-2.0
|
tukkek/javelin
|
tyrant/mikera/tyrant/test/Quest_TC.java
|
3012
|
/*
* Created on 02-Apr-2005
*
* By Mike Anderson
*/
package tyrant.mikera.tyrant.test;
import javelin.controller.old.Game;
import javelin.model.BattleMap;
import tyrant.mikera.engine.Lib;
import tyrant.mikera.engine.RPG;
import tyrant.mikera.engine.Thing;
import tyrant.mikera.tyrant.*;
/**
* @author Mike
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class Quest_TC extends TyrantTestCase {
public void testVisitMap() {
BattleMap map=new BattleMap(1,1);
Thing q=Quest.createVisitMapQuest("Visit the map",map);
// check set-up
assertNotNull(q.get("TargetMap"));
assertEquals(map,q.get("TargetMap"));
Thing h=Game.hero();
Quest.addQuest(h,q);
map.addThing(h,0,0);
assertFalse(q.getFlag("IsComplete"));
Time.advance(0);
assertTrue(q.getFlag("IsComplete"));
}
public void testKillQuest() {
Thing rat=Lib.create("rat");
Thing q=Quest.createKillQuest("Kill the rat",rat);
Thing h=Game.hero();
Quest.addQuest(h,q);
assertFalse(rat.isDead());
assertFalse(q.getFlag("IsComplete"));
assertTrue(q.getFlag("IsActive"));
Damage.inflict(rat,1000,RPG.DT_SPECIAL);
assertTrue(rat.isDead());
assertTrue(q.getFlag("IsComplete"));
assertFalse(q.getFlag("IsActive"));
}
public void testKillNumberQuest() {
Thing q1=Quest.createKillNumberQuest("Kill the goblins","goblin",2);
Thing q2=Quest.createKillNumberQuest("Kill the goblinoids","[IsGoblinoid]",2);
assertEquals("IsGoblinoid",q2.getString("TargetType"));
assertEquals("goblin",q1.getString("TargetName"));
Thing h=Game.hero();
Quest.addQuest(h,q1);
Quest.addQuest(h,q2);
// kill irrelevant stuff
Being.registerKill(h,Lib.create("rat"));
Being.registerKill(h,Lib.create("field mouse"));
assertFalse(q1.getFlag("IsComplete"));
assertFalse(q2.getFlag("IsComplete"));
// kill one goblin
Being.registerKill(h,Lib.create("goblin"));
assertFalse(q1.getFlag("IsComplete"));
assertFalse(q2.getFlag("IsComplete"));
// kill a different goblinoid
Being.registerKill(h,Lib.create("orc"));
assertFalse(q1.getFlag("IsComplete"));
assertTrue(q2.getFlag("IsComplete"));
// kill a second goblin
Being.registerKill(h,Lib.create("goblin"));
assertTrue(q1.getFlag("IsComplete"));
assertTrue(q2.getFlag("IsComplete"));
}
public void testMeetQuest() {
BattleMap map=new BattleMap(3,3);
Thing rat=Lib.create("rat");
Thing q=Quest.createMeetQuest("Met the rat",rat);
Thing h=Game.hero();
Quest.addQuest(h,q);
map.addThing(Game.hero(),0,0);
map.addThing(rat,2,2);
Time.advance(0);
assertFalse(q.getFlag("IsComplete"));
assertTrue(q.getFlag("IsActive"));
map.addThing(Game.hero(),1,1);
Time.advance(0);
assertTrue(q.getFlag("IsComplete"));
assertFalse(q.getFlag("IsActive"));
}
}
|
gpl-2.0
|
EaseRider/DotNetEest
|
AutoReservation.Ui/Converters/DetailViewVisibilityConverter.cs
|
667
|
using System;
using System.Windows;
using System.Windows.Data;
namespace AutoReservation.Ui.Converters
{
public class DetailViewVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
gpl-2.0
|
raphaelm/backupd
|
backupd/remote/ssh/ssh.go
|
683
|
package ssh
import (
"github.com/raphaelm/backupd/backupd/model"
"io"
"strconv"
"strings"
)
type Ssh struct {
Host string
Port int
User string
}
func split2(s, sep string) (a, b string) {
x := strings.SplitN(s, sep, 2)
return x[0], x[1]
}
func Load(r model.Remote) *Ssh {
driver := Ssh{}
host := r.Location
if strings.Contains(host, "@") {
driver.User, host = split2(r.Location, "@")
}
driver.Port = 22
if strings.Contains(host, ":") {
port := ""
host, port = split2(host, ":")
p, err := strconv.Atoi(port)
if err == nil {
driver.Port = p
}
}
driver.Host = host
return &driver
}
func (d *Ssh) GetPipe(module string) *io.Writer {
return nil
}
|
gpl-2.0
|
peteriliev/Maille
|
jasmine-standalone-2.0.1/src/kata/CombSort.js
|
416
|
var CombSort = function() {};
CombSort.sort = function(a) {
var gap = a.length,
swapped = false,
tmp = 0;
while (gap > 1 || swapped)
{
gap = gap / 1.7;
if (gap < 1) {
gap = 1;
}
swapped = false;
for (var i = 0, iMax = a.length; i + gap < iMax; i++) {
if (a[i] > a[i + gap]) {
tmp = a[i];
a[i] = a[i + gap];
a[i + gap] = tmp;
swapped = true;
}
}
}
return a;
};
|
gpl-2.0
|
cjaypierson/lpm
|
administrator/components/com_iproperty/controllers/settings.php
|
964
|
<?php
/**
* @version 3.1.3 2013-08-30
* @package Joomla
* @subpackage Intellectual Property
* @copyright (C) 2013 the Thinkery
* @license GNU/GPL see LICENSE.php
*/
defined( '_JEXEC' ) or die( 'Restricted access');
jimport('joomla.application.component.controllerform');
class IpropertyControllerSettings extends JControllerForm
{
protected $text_prefix = 'COM_IPROPERTY';
protected $context = 'settings';
public function checkEditId($context, $recordid){
return true;
}
protected function allowEdit($data = array(), $key = 'id')
{
$allow = parent::allowEdit($data, $key);
// Check if the user should be in this editing area
$auth = new ipropertyHelperAuth();
$allow = $auth->getAdmin();
return $allow;
}
public function cancel()
{
$this->setRedirect(JRoute::_('index.php?option=com_iproperty', false));
}
}
?>
|
gpl-2.0
|
npelh001/rshell
|
src/connector.cpp
|
1387
|
/*
* Author: Nicholas Pelham
* Date : 10/29/15
*
* All members relating to connectors are defined here.
*
* Connector: Used as a template for all connectors.
* And :
* Or :
* SemiColon:
*/
#include "instruction.h"
#include "connectors.h"
Connector::Connector(Instruction *lInst, Instruction * rInst) {
left = lInst;
right = rInst;
}
Connector::~Connector() {
delete(left);
delete(right);
}
And::And(Instruction *lInst, Instruction *rInst)
: Connector(lInst, rInst) {
}
And::~And() {
}
/*
* Execute the right Instruction only if the left succeeds.
* Returns false if either Instruction fails.
*/
bool And::execute() {
if (left->execute())
return right->execute();
return false;
}
Or::Or(Instruction * lInst, Instruction * rInst)
: Connector(lInst, rInst) {
}
Or::~Or() {
}
/*
* Execute the right Instruction only if the left fails.
* Returns true if either Instruction succeeds.
*/
bool Or::execute() {
if (left->execute())
return true;
if (right->execute())
return true;
return false;
}
SemiColon::SemiColon(Instruction * lInst, Instruction * rInst)
: Connector(lInst, rInst) {
}
SemiColon::~SemiColon() {
}
/*
* Executes both Instructions regardless of success or failure.
*/
bool SemiColon::execute() {
left->execute();
right->execute();
return true;
}
|
gpl-2.0
|
thetouristt/gailurra
|
wp-config.php
|
3198
|
<?php
/**
* Configuración básica de WordPress.
*
* Este archivo contiene las siguientes configuraciones: ajustes de MySQL, prefijo de tablas,
* claves secretas, idioma de WordPress y ABSPATH. Para obtener más información,
* visita la página del Codex{@link http://codex.wordpress.org/Editing_wp-config.php Editing
* wp-config.php} . Los ajustes de MySQL te los proporcionará tu proveedor de alojamiento web.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** Ajustes de MySQL. Solicita estos datos a tu proveedor de alojamiento web. ** //
/** El nombre de tu base de datos de WordPress */
define('DB_NAME', 'gailurra');
/** Tu nombre de usuario de MySQL */
define('DB_USER', 'mon');
/** Tu contraseña de MySQL */
define('DB_PASSWORD', 'lur1');
/** Host de MySQL (es muy probable que no necesites cambiarlo) */
define('DB_HOST', 'localhost');
/** Codificación de caracteres para la base de datos. */
define('DB_CHARSET', 'utf8mb4');
/** Cotejamiento de la base de datos. No lo modifiques si tienes dudas. */
define('DB_COLLATE', '');
/**#@+
* Claves únicas de autentificación.
*
* Define cada clave secreta con una frase aleatoria distinta.
* Puedes generarlas usando el {@link https://api.wordpress.org/secret-key/1.1/salt/ servicio de claves secretas de WordPress}
* Puedes cambiar las claves en cualquier momento para invalidar todas las cookies existentes. Esto forzará a todos los usuarios a volver a hacer login.
*
* @since 2.6.0
*/
define('AUTH_KEY', '${dYcTf)oq 9FH&(WKMx=zF{iH,EIfM$n-}9)iK>J^ic]J8O|0U})M=p|B&40+Ij');
define('SECURE_AUTH_KEY', 'KR%:&,(87US0z?%[k]5-DD_C1@Tfc&.mux8CSA(x*>1x|h!& C,z_IR#=Uv.C$_}');
define('LOGGED_IN_KEY', 'iep<WeF=@HT@SK-+3xnXu$Nl)[d<Z:t]):fL(Cn/C|OzQ.#v6 ]b5f=}d) I(vi=');
define('NONCE_KEY', '+=xdOpyS9s/x&fk:,D6`%E&iYi$B-n]=Zt|^[vIK(e$-p1CQzj*G[(^89_VRCAl)');
define('AUTH_SALT', 'My.|ikQ6tEi+/FX;MwV+VFHGd0d)0i|^K;-I%c9VY}CQrHmPaEx<2I+jQ{}u=+HY');
define('SECURE_AUTH_SALT', 'c/pF Z#<GPxS7U*JD31E{?32UKK;8_3SgUkH9/W$_CsQn~}LI)wcyr>,g`Iq;ox&');
define('LOGGED_IN_SALT', 'PG9uCM-t/~iWYCm,DA,|#9%t/Ac;e*,UbLKxMInL[@iBJoa:jm#{.MR|$cKl;uzN');
define('NONCE_SALT', 'c0V6MW,g;3@n@g.Bf_%lVwJV?wuLpXVkX_>f;#WjLJBUc/wuyb be_!zA@D#_2%{');
/**#@-*/
/**
* Prefijo de la base de datos de WordPress.
*
* Cambia el prefijo si deseas instalar multiples blogs en una sola base de datos.
* Emplea solo números, letras y guión bajo.
*/
$table_prefix = 'wp_';
/**
* Para desarrolladores: modo debug de WordPress.
*
* Cambia esto a true para activar la muestra de avisos durante el desarrollo.
* Se recomienda encarecidamente a los desarrolladores de temas y plugins que usen WP_DEBUG
* en sus entornos de desarrollo.
*/
define('WP_DEBUG', false);
/* ¡Eso es todo, deja de editar! Feliz blogging */
/** WordPress absolute path to the Wordpress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
|
gpl-2.0
|
neelance/jre4ruby
|
jre4ruby/lib/share/java/security/spec/ECFieldFp.rb
|
3370
|
require "rjava"
# Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Sun designates this
# particular file as subject to the "Classpath" exception as provided
# by Sun in the LICENSE file that accompanied this code.
#
# This code 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
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
# CA 95054 USA or visit www.sun.com if you need additional information or
# have any questions.
module Java::Security::Spec
module ECFieldFpImports #:nodoc:
class_module.module_eval {
include ::Java::Lang
include ::Java::Security::Spec
include_const ::Java::Math, :BigInteger
include_const ::Java::Util, :Arrays
}
end
# This immutable class defines an elliptic curve (EC) prime
# finite field.
#
# @see ECField
#
# @author Valerie Peng
#
# @since 1.5
class ECFieldFp
include_class_members ECFieldFpImports
include ECField
attr_accessor :p
alias_method :attr_p, :p
undef_method :p
alias_method :attr_p=, :p=
undef_method :p=
typesig { [BigInteger] }
# Creates an elliptic curve prime finite field
# with the specified prime <code>p</code>.
# @param p the prime.
# @exception NullPointerException if <code>p</code> is null.
# @exception IllegalArgumentException if <code>p</code>
# is not positive.
def initialize(p)
@p = nil
if (!(p.signum).equal?(1))
raise IllegalArgumentException.new("p is not positive")
end
@p = p
end
typesig { [] }
# Returns the field size in bits which is size of prime p
# for this prime finite field.
# @return the field size in bits.
def get_field_size
return @p.bit_length
end
typesig { [] }
# Returns the prime <code>p</code> of this prime finite field.
# @return the prime.
def get_p
return @p
end
typesig { [Object] }
# Compares this prime finite field for equality with the
# specified object.
# @param obj the object to be compared.
# @return true if <code>obj</code> is an instance
# of ECFieldFp and the prime value match, false otherwise.
def ==(obj)
if ((self).equal?(obj))
return true
end
if (obj.is_a?(ECFieldFp))
return ((@p == (obj).attr_p))
end
return false
end
typesig { [] }
# Returns a hash code value for this prime finite field.
# @return a hash code value.
def hash_code
return @p.hash_code
end
private
alias_method :initialize__ecfield_fp, :initialize
end
end
|
gpl-2.0
|
jalev/learning_docker_ruby
|
spec/ldr_spec.rb
|
147
|
require 'spec_helper'
describe LDR do
it "should return something when asked to" do
puts LDR.info
LDR.info.should != nil
end
end
|
gpl-2.0
|
AndreFSilveira/myblog
|
wp-content/plugins/pcom-envio-validacao/pcom-envio-validacao.php
|
11463
|
<?php
/**
* Plugin Name: PontoCom Validação e Envio de Formulários
* Plugin URI: http://agenciadeinternet.com/
* Description: Funções para Validação e envio de Fomulários por e-mail.
* Author: PontoCom Agência de Internet
* Author URI: http://agenciadeinternet.com/
**/
define ('pcom_envio_validacao_DIR', ABSPATH.PLUGINDIR.'/pcom-envio-validacao/');
define ('pcom_envio_validacao_URL', get_bloginfo('siteurl').'/'.PLUGINDIR.'/pcom-envio-validacao');
//funções para validação de formulários e mensagens de erro
function validarItem($name, $campo, $msg = ''){
if ($_POST[$name] == "" || $_POST[$name] == $campo){
if($msg) add_error_message($msg);
else add_error_message('Preencha "'.$campo.'" corretamente!');
return 1;
} else return 0;
}
function validarEmail($name, $msg){
if (!preg_match("/^[a-z0-9_\.\-]+@[a-z0-9_\.\-]*[a-z0-9_\-]+\.[a-z]{2,4}$/", $_POST[$name])){
if($msg) add_error_message($msg);
else add_error_message('Preencha o e-mail corretamente!');
return 1;
} else return 0;
}
function validarArquivo($name, $msg = '' ){
if (!(strlen($_FILES[$name]['tmp_name']) > 0)){
if($msg) add_error_message($msg);
else add_error_message('Você deve enviar um arquivo!');
return 1;
} else return 0;
}
//adicionando mensagens à sessão
function add_error_message($msg){
if (!isset($_SESSION['error-messages'])){
$_SESSION['error-messages'] = array() ;
}
$_SESSION['error-messages'][] = $msg ;
}
function add_success_message($msg){
if (!isset($_SESSION['success-message'])){
$_SESSION['success-message'] = array() ;
}
$_SESSION['success-message'][] = $msg ;
}
//obtendo mensagens da sessão
function get_error_messages() {
if (isset($_SESSION['error-messages'])){
$mensagens = $_SESSION['error-messages'];
unset($_SESSION['error-messages']);
return $mensagens;
}
}
function get_success_message() {
if (isset($_SESSION['success-message'])){
$mensagens = $_SESSION['success-message'];
unset($_SESSION['success-message']);
return $mensagens;
}
}
//Utilizar este código para exibir as mensagens no site
/*<?php
$mensagens = get_error_messages();
if (is_array($mensagens)) {?>
<div class="erro">
<ul>
<?php foreach ($mensagens as $item) {
echo("<li>" . $item . "</li>");
}?>
</ul>
</div>
<?php } ?>
<?php
$success_message = get_success_message();
if (!empty($success_message)) {?>
<div class="sucesso">
<ul>
<?php echo("<li>" . $success_message[0] . "</li>");?>
</ul>
</div>
<?php } ?>*/
//Utilizar este CSS
/*
.erro{border:dashed 1px #F00; padding:8px; margin:10px; background:#FFE4E1; font-size:15px}
.erro ul li{font-size: 15px; list-style-type: none;}
.sucesso{border:dashed 1px #315ca8; padding:8px; margin:10px; background:#66FF66;}
.sucesso ul li{font-size: 15px; list-style-type: none; color:009900 !important;}
*/
// ----------------------------------------------------------------------------------------
// Envia Fale Conosco
// ----------------------------------------------------------------------------------------
add_action("init","envia_fale_conosco");
function envia_fale_conosco(){
if (isset($_POST['form_faleconosco'])){
if(validarFaleConosco()){
$campos[0] = adicionaCampo('contato_destino', 'Destino');
$campos[1] = adicionaCampo('contato_setor', 'Setor');
$campos[2] = adicionaCampo('contato_nome', 'Nome');
$campos[3] = adicionaCampo('contato_email', 'E-mail');
$campos[4] = adicionaCampo('contato_telefone', 'Telefone');
$campos[5] = adicionaCampo('contato_estado', 'Estado');
$campos[6] = adicionaCampo('contato_cidade', 'Cidade');
$campos[7] = adicionaCampo('contato_mensagem', 'Mensagem');
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fale Conosco FAEP</title>
</head>
<body>
<table width="600" border="0" cellspacing="0" cellpadding="0" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#666; border:4px solid #46765b;">
<tr>
<td colspan="2" bgcolor="#46765b" style="padding:10px 10px 14px 10px; text-transform:uppercase; font-weight:bold; color:#FFF">Novo contato recebido pelo site</td>
</tr>';
$count=1;
foreach($campos as $campo):
$background = (($count%2 == 0) ? 'background:#eeeeee':'');
$message.='
<tr>
<td style="padding:10px;'.$background.'"><strong>'.$campo['name_campo'].':</strong></td>
<td width="80%" style="'.$background.'">'.utf8_decode($_POST[$campo['name_input']]).'</td>
</tr>';
$count++;
endforeach;
$message.='</table>
</body>
</html>
';
require (pcom_envio_validacao_DIR.'class.phpmailer.php');
require (pcom_envio_validacao_DIR.'class.smtp.php');
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->Encoding = '8bit';
$mail->IsSMTP(); // Define que a mensagem será SMTP
$mail->SMTPAuth = true; // Usa autenticação SMTP? (opcional)
$mail->Host = get_option('_theme_smtp_host'); // Endereço do servidor SMTP
$mail->Port = get_option('_theme_smtp_port');
$mail->Username = get_option('_theme_smtp_user'); // Usuário do servidor SMTP
$mail->Password = get_option('_theme_smtp_password'); // Senha do servidor SMTP
//$mail->From = 'dionathanclak@agenciadeinternet.com';
$mail->From = $_POST['contato_email'];
//$mail->FromName = utf8_decode('Contato FAEP');;
$mail->FromName = utf8_decode($_POST['contato_nome']);
//$mail->AddAddress('dionathanclak@agenciadeinternet.com', "Contato FAEP");
$mail->AddAddress(get_option('_theme_email_recebe_fc'), "Contato FAEP");
$mail->Subject = utf8_decode("Fale Conosco - FAEP");
$mail->Body = $message;
if($mail->Send()){
add_success_message("Contato enviado com sucesso!") ;
}
else{
add_error_message("Não foi possível enviar sua mensagem neste momento. Por favor, tente novamente mais tarde.") ;
}
}
}
}
function validarFaleConosco(){
$erros = 0;
$erros += validarItem('contato_destino', 'Selecione o Destino', 'Favor selecionar o DESTINO!');
$erros += validarItem('contato_setor', 'Selecione o Setor', 'Favor selecionar o SETOR!');
$erros += validarItem('contato_nome', 'Digite seu Nome', 'Preencha o NOME corretamente!');
$erros += validarEmail('contato_email', 'Preencha o EMAIL corretamente!');
$erros += validarItem('contato_telefone', 'Digite seu Telefone', 'Preencha o TELEFONE corretamente!');
$erros += validarItem('contato_estado', 'Selecione o Estado', 'Favor selecionar o ESTADO!');
$erros += validarItem('contato_cidade', 'Digite sua Cidade', 'Preencha a CIDADE corretamente!');
$erros += validarItem('contato_mensagem', 'Digite a Mensagem', 'Preencha a MENSAGEM corretamente!');
return $erros ? false : true;
}
function adicionaCampo($name_input, $name_campo){
$campo = array('name_input' => $name_input, 'name_campo' => $name_campo);
return $campo;
}
add_action("init","envia_curriculo");
function envia_curriculo(){
if (isset($_POST['form_envieseucurriculo'])){
if(validarEnvieSeuCurriculo()){
$campos[1] = adicionaCampo('contato_nome', 'Nome');
$campos[2] = adicionaCampo('contato_email', 'E-mail');
$campos[3] = adicionaCampo('contato_telefone', 'Telefone');
$campos[4] = adicionaCampo('contato_estado', 'Estado');
$campos[5] = adicionaCampo('contato_cidade', 'Cidade');
$campos[6] = adicionaCampo('contato_mensagem', 'Mensagem');
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Currículo FAEP</title>
</head>
<body>
<table width="600" border="0" cellspacing="0" cellpadding="0" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#666; border:4px solid #46765b;">
<tr>
<td colspan="2" bgcolor="#46765b" style="padding:10px 10px 14px 10px; text-transform:uppercase; font-weight:bold; color:#FFF">Novo currículo recebido pelo site</td>
</tr>';
$count=1;
foreach($campos as $campo):
$background = (($count%2 == 0) ? 'background:#eeeeee':'');
$message.='
<tr>
<td style="padding:10px;'.$background.'"><strong>'.$campo['name_campo'].':</strong></td>
<td width="80%" style="'.$background.'">'.utf8_decode($_POST[$campo['name_input']]).'</td>
</tr>';
$count++;
endforeach;
$message.='</table>
</body>
</html>
';
require (pcom_envio_validacao_DIR.'class.phpmailer.php');
require (pcom_envio_validacao_DIR.'class.smtp.php');
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->Encoding = '8bit';
$mail->IsSMTP(); // Define que a mensagem será SMTP
$mail->SMTPAuth = true; // Usa autenticação SMTP? (opcional)
$mail->Host = get_option('_theme_smtp_host'); // Endereço do servidor SMTP
$mail->Port = get_option('_theme_smtp_port');
$mail->Username = get_option('_theme_smtp_user'); // Usuário do servidor SMTP
$mail->Password = get_option('_theme_smtp_password'); // Senha do servidor SMTP
//$mail->From = 'dionathanclak@agenciadeinternet.com';
$mail->From = $_POST['contato_email'];
//$mail->FromName = utf8_decode('Contato FAEP');
$mail->FromName = utf8_decode($_POST['contato_nome']);
//$mail->AddAddress('dionathanclak@agenciadeinternet.com', "Contato FAEP");
$mail->AddAddress(get_option('_theme_recebe_email_cur'), "Contato FAEP");
$mail->Subject = utf8_decode("Currículo - FAEP");
$mail->Body = $message;
//if (isset($_FILES['contato_arquivo']) && $_FILES['contato_arquivo']['tmp_name']) {
$mail->AddAttachment($_FILES['contato_arquivo']['tmp_name'], $_FILES['contato_arquivo']['name']);
//}
if($mail->Send()){
add_success_message("Currículo enviado com sucesso!") ;
}
else{
add_error_message("Não foi possível enviar seu currículo neste momento. Por favor, tente novamente mais tarde.") ;
}
}
}
}
function validarEnvieSeuCurriculo(){
$erros = 0;
$erros += validarArquivo('contato_arquivo', 'Você deve anexar um CURRÍCULO!');
$erros += validarItem('contato_nome', 'Digite seu Nome', 'Preencha o NOME corretamente!');
$erros += validarEmail('contato_email', 'Preencha o EMAIL corretamente!');
$erros += validarItem('contato_telefone', 'Digite seu Telefone', 'Preencha o TELEFONE corretamente!');
$erros += validarItem('contato_estado', 'Selecione o Estado', 'Favor selecionar o ESTADO!');
$erros += validarItem('contato_cidade', 'Digite sua Cidade', 'Preencha a CIDADE corretamente!');
$erros += validarItem('contato_mensagem', 'Digite a Mensagem', 'Preencha a MENSAGEM corretamente!');
return $erros ? false : true;
}
|
gpl-2.0
|
martinnj/DNSMigrationPrope
|
DNSMigrationPrope/Properties/Settings.Designer.cs
|
1074
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DNSMigrationPrope.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
|
gpl-2.0
|
WSUV-CS420-Team4/ParkingTrackerApi
|
config.example.php
|
102
|
<?php
$db_host = "localhost";
$db_user = "user";
$db_pass = "pass";
$db_name = "parkingtracker";
?>
|
gpl-2.0
|
socialscript/socialscript
|
application/lib/Smarty/plugins/outputfilter.trimwhitespace.php
|
3200
|
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFilter
*/
/**
* Smarty trimwhitespace outputfilter plugin
*
* Trim unnecessary whitespace from HTML markup.
*
* @author Rodney Rehm
* @param string $source
* input string
* @param Smarty_Internal_Template $smarty
* Smarty object
* @return string filtered output
* @todo substr_replace() is not overloaded by mbstring.func_overload - so this
* function might fail!
*/
function smarty_outputfilter_trimwhitespace($source, Smarty_Internal_Template $smarty) {
$store = array();
$_store = 0;
$_offset = 0;
// Unify Line-Breaks to \n
$source = preg_replace("/\015\012|\015|\012/", "\n", $source);
// capture Internet Explorer Conditional Comments
if(preg_match_all('#<!--\[[^\]]+\]>.*?<!\[[^\]]+\]-->#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach($matches as $match) {
$store[] = $match[0][0];
$_length = strlen($match[0][0]);
$replace = '@!@SMARTY:' . $_store . ':SMARTY@!@';
$source = substr_replace($source, $replace, $match[0][1] - $_offset, $_length);
$_offset += $_length - strlen($replace);
$_store ++;
}
}
// Strip all HTML-Comments
$source = preg_replace('#<!--.*?-->#ms', '', $source);
// capture html elements not to be messed with
$_offset = 0;
if(preg_match_all('#<(script|pre|textarea)[^>]*>.*?</\\1>#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach($matches as $match) {
$store[] = $match[0][0];
$_length = strlen($match[0][0]);
$replace = '@!@SMARTY:' . $_store . ':SMARTY@!@';
$source = substr_replace($source, $replace, $match[0][1] - $_offset, $_length);
$_offset += $_length - strlen($replace);
$_store ++;
}
}
$expressions = array(
// replace multiple spaces between tags by a single space
// can't remove them entirely, becaue that might break poorly
// implemented CSS display:inline-block elements
'#(:SMARTY@!@|>)\s+(?=@!@SMARTY:|<)#s' => '\1 \2',
// remove spaces between attributes (but not in attribute values!)
'#(([a-z0-9]\s*=\s*(["\'])[^\3]*?\3)|<[a-z0-9_]+)\s+([a-z/>])#is' => '\1 \4',
// note: for some very weird reason trim() seems to remove spaces
// inside attributes.
// maybe a \0 byte or something is interfering?
'#^\s+<#Ss' => '<',
'#>\s+$#Ss' => '>'
);
$source = preg_replace(array_keys($expressions), array_values($expressions), $source);
// note: for some very weird reason trim() seems to remove spaces inside
// attributes.
// maybe a \0 byte or something is interfering?
// $source = trim( $source );
// capture html elements not to be messed with
$_offset = 0;
if(preg_match_all('#@!@SMARTY:([0-9]+):SMARTY@!@#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach($matches as $match) {
$store[] = $match[0][0];
$_length = strlen($match[0][0]);
$replace = array_shift($store);
$source = substr_replace($source, $replace, $match[0][1] + $_offset, $_length);
$_offset += strlen($replace) - $_length;
$_store ++;
}
}
return $source;
}
?>
|
gpl-2.0
|
yippee-ki-yay/TurboFolkEditor
|
Termin19b/src/grafeditor/app/Main.java
|
323
|
package grafeditor.app;
public class Main {
public Main() {
super();
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AppCore app=AppCore.getInstance();
app.setVisible(true);
}
}
|
gpl-2.0
|
stevemynett/Grasshopper-Framework
|
search.php
|
708
|
<?php get_header(); ?>
<section id="main">
<section id="main_content" role="main">
<h2>Search results</h2>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
<?php post_meta(); ?>
<?php custom_excerpt(45, "More Info"); ?>
</article>
<?php endwhile; else: ?>
<p>Sorry, no posts matched your criteria. Please try another keyword.</p>
<?php endif; ?>
</section>
<?php get_sidebar(); ?>
</section>
<?php get_footer(); ?>
|
gpl-2.0
|
Risca/scummvm
|
backends/events/default/default-events.cpp
|
7685
|
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/scummsys.h"
#if !defined(DISABLE_DEFAULT_EVENTMANAGER)
#include "common/system.h"
#include "common/config-manager.h"
#include "common/translation.h"
#include "backends/events/default/default-events.h"
#include "backends/keymapper/keymapper.h"
#include "backends/keymapper/remap-dialog.h"
#include "backends/vkeybd/virtual-keyboard.h"
#include "engines/engine.h"
#include "gui/message.h"
DefaultEventManager::DefaultEventManager(Common::EventSource *boss) :
_buttonState(0),
_modifierState(0),
_shouldQuit(false),
_shouldRTL(false),
_confirmExitDialogActive(false) {
assert(boss);
_dispatcher.registerSource(boss, false);
_dispatcher.registerSource(&_artificialEventSource, false);
_dispatcher.registerObserver(this, kEventManPriority, false);
// Reset key repeat
_currentKeyDown.keycode = 0;
_currentKeyDown.ascii = 0;
_currentKeyDown.flags = 0;
_keyRepeatTime = 0;
#ifdef ENABLE_VKEYBD
_vk = new Common::VirtualKeyboard();
#endif
#ifdef ENABLE_KEYMAPPER
_keymapper = new Common::Keymapper(this);
// EventDispatcher will automatically free the keymapper
_dispatcher.registerMapper(_keymapper);
_remap = false;
#else
_dispatcher.registerMapper(new Common::DefaultEventMapper());
#endif
}
DefaultEventManager::~DefaultEventManager() {
#ifdef ENABLE_VKEYBD
delete _vk;
#endif
}
void DefaultEventManager::init() {
#ifdef ENABLE_VKEYBD
if (ConfMan.hasKey("vkeybd_pack_name")) {
_vk->loadKeyboardPack(ConfMan.get("vkeybd_pack_name"));
} else {
_vk->loadKeyboardPack("vkeybd_default");
}
#endif
}
bool DefaultEventManager::pollEvent(Common::Event &event) {
// Skip recording of these events
uint32 time = g_system->getMillis(true);
bool result = false;
_dispatcher.dispatch();
if (!_eventQueue.empty()) {
event = _eventQueue.pop();
result = true;
}
if (result) {
event.synthetic = false;
switch (event.type) {
case Common::EVENT_KEYDOWN:
_modifierState = event.kbd.flags;
// init continuous event stream
_currentKeyDown.ascii = event.kbd.ascii;
_currentKeyDown.keycode = event.kbd.keycode;
_currentKeyDown.flags = event.kbd.flags;
_keyRepeatTime = time + kKeyRepeatInitialDelay;
if (event.kbd.keycode == Common::KEYCODE_BACKSPACE) {
// WORKAROUND: Some engines incorrectly attempt to use the
// ascii value instead of the keycode to detect the backspace
// key (a non-portable behavior). This fails at least on
// Mac OS X, possibly also on other systems.
// As a workaround, we force the ascii value for backspace
// key pressed. A better fix would be for engines to stop
// making invalid assumptions about ascii values.
event.kbd.ascii = Common::KEYCODE_BACKSPACE;
_currentKeyDown.ascii = Common::KEYCODE_BACKSPACE;
}
break;
case Common::EVENT_KEYUP:
_modifierState = event.kbd.flags;
if (event.kbd.keycode == _currentKeyDown.keycode) {
// Only stop firing events if it's the current key
_currentKeyDown.keycode = 0;
}
break;
case Common::EVENT_MOUSEMOVE:
_mousePos = event.mouse;
break;
case Common::EVENT_LBUTTONDOWN:
_mousePos = event.mouse;
_buttonState |= LBUTTON;
break;
case Common::EVENT_LBUTTONUP:
_mousePos = event.mouse;
_buttonState &= ~LBUTTON;
break;
case Common::EVENT_RBUTTONDOWN:
_mousePos = event.mouse;
_buttonState |= RBUTTON;
break;
case Common::EVENT_RBUTTONUP:
_mousePos = event.mouse;
_buttonState &= ~RBUTTON;
break;
case Common::EVENT_MAINMENU:
if (g_engine && !g_engine->isPaused())
g_engine->openMainMenuDialog();
if (_shouldQuit)
event.type = Common::EVENT_QUIT;
else if (_shouldRTL)
event.type = Common::EVENT_RTL;
break;
#ifdef ENABLE_VKEYBD
case Common::EVENT_VIRTUAL_KEYBOARD:
if (_vk->isDisplaying()) {
_vk->close(true);
} else {
if (g_engine)
g_engine->pauseEngine(true);
_vk->show();
if (g_engine)
g_engine->pauseEngine(false);
result = false;
}
break;
#endif
#ifdef ENABLE_KEYMAPPER
case Common::EVENT_KEYMAPPER_REMAP:
if (!_remap) {
_remap = true;
Common::RemapDialog _remapDialog;
if (g_engine)
g_engine->pauseEngine(true);
_remapDialog.runModal();
if (g_engine)
g_engine->pauseEngine(false);
_remap = false;
}
break;
#endif
case Common::EVENT_RTL:
if (ConfMan.getBool("confirm_exit")) {
if (g_engine)
g_engine->pauseEngine(true);
GUI::MessageDialog alert(_("Do you really want to return to the Launcher?"), _("Launcher"), _("Cancel"));
result = _shouldRTL = (alert.runModal() == GUI::kMessageOK);
if (g_engine)
g_engine->pauseEngine(false);
} else
_shouldRTL = true;
break;
case Common::EVENT_MUTE:
if (g_engine)
g_engine->flipMute();
break;
case Common::EVENT_QUIT:
if (ConfMan.getBool("confirm_exit")) {
if (_confirmExitDialogActive) {
result = false;
break;
}
_confirmExitDialogActive = true;
if (g_engine)
g_engine->pauseEngine(true);
GUI::MessageDialog alert(_("Do you really want to quit?"), _("Quit"), _("Cancel"));
result = _shouldQuit = (alert.runModal() == GUI::kMessageOK);
if (g_engine)
g_engine->pauseEngine(false);
_confirmExitDialogActive = false;
} else
_shouldQuit = true;
break;
default:
break;
}
} else {
// Check if event should be sent again (keydown)
if (_currentKeyDown.keycode != 0 && _keyRepeatTime < time) {
// fire event
event.type = Common::EVENT_KEYDOWN;
event.synthetic = true;
event.kbd.ascii = _currentKeyDown.ascii;
event.kbd.keycode = (Common::KeyCode)_currentKeyDown.keycode;
event.kbd.flags = _currentKeyDown.flags;
_keyRepeatTime = time + kKeyRepeatSustainDelay;
result = true;
}
}
return result;
}
void DefaultEventManager::pushEvent(const Common::Event &event) {
// If already received an EVENT_QUIT, don't add another one
if (event.type == Common::EVENT_QUIT) {
if (!_shouldQuit)
_artificialEventSource.addEvent(event);
} else
_artificialEventSource.addEvent(event);
}
void DefaultEventManager::purgeMouseEvents() {
_dispatcher.dispatch();
Common::Queue<Common::Event> filteredQueue;
while (!_eventQueue.empty()) {
Common::Event event = _eventQueue.pop();
switch (event.type) {
case Common::EVENT_MOUSEMOVE:
case Common::EVENT_LBUTTONDOWN:
case Common::EVENT_LBUTTONUP:
case Common::EVENT_RBUTTONDOWN:
case Common::EVENT_RBUTTONUP:
case Common::EVENT_WHEELUP:
case Common::EVENT_WHEELDOWN:
case Common::EVENT_MBUTTONDOWN:
case Common::EVENT_MBUTTONUP:
// do nothing
break;
default:
filteredQueue.push(event);
break;
}
}
_eventQueue = filteredQueue;
}
#endif // !defined(DISABLE_DEFAULT_EVENTMANAGER)
|
gpl-2.0
|
berryjace/www
|
crm/library/BL/Entity/Repository/OrganizationTypeRepository.php
|
564
|
<?php
namespace BL\Entity\Repository;
use Doctrine\ORM\EntityRepository;
/**
* List of State In USA
*
* @author Rashed
*/
class OrganizationTypeRepository extends EntityRepository {
/**
* Function to get all Design Tag
* @author Rashed
* @copyright Blueliner Marketing
* @version 0.1
* @access public
* @return String
*/
public function findAll() {
$q = $this->_em->createQuery("SELECT ot.id, ot.name FROM BL\Entity\OrganizationType ot Order By ot.name ASC");
return $q->getResult();
}
}
?>
|
gpl-2.0
|
ioquake/jedi-academy
|
codemp/client/FXExport.cpp
|
2271
|
//Anything above this #include will be ignored by the compiler
#include "../qcommon/exe_headers.h"
#include "client.h"
#include "FxScheduler.h"
//#define __FXCHECKER
#ifdef __FXCHECKER
#include <float.h>
#endif // __FXCHECKER
int FX_RegisterEffect(const char *file)
{
return theFxScheduler.RegisterEffect(file, true);
}
void FX_PlayEffect( const char *file, vec3_t org, vec3_t fwd, int vol, int rad )
{
#ifdef __FXCHECKER
if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2]))
{
assert(0);
}
if (_isnan(fwd[0]) || _isnan(fwd[1]) || _isnan(fwd[2]))
{
assert(0);
}
if (fabs(fwd[0]) < 0.1 && fabs(fwd[1]) < 0.1 && fabs(fwd[2]) < 0.1)
{
assert(0);
}
#endif // __FXCHECKER
theFxScheduler.PlayEffect(file, org, fwd, vol, rad);
}
void FX_PlayEffectID( int id, vec3_t org, vec3_t fwd, int vol, int rad, qboolean isPortal )
{
#ifdef __FXCHECKER
if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2]))
{
assert(0);
}
if (_isnan(fwd[0]) || _isnan(fwd[1]) || _isnan(fwd[2]))
{
assert(0);
}
if (fabs(fwd[0]) < 0.1 && fabs(fwd[1]) < 0.1 && fabs(fwd[2]) < 0.1)
{
assert(0);
}
#endif // __FXCHECKER
theFxScheduler.PlayEffect(id, org, fwd, vol, rad, !!isPortal );
}
void FX_PlayBoltedEffectID( int id, vec3_t org,
const int boltInfo, int iGhoul2, int iLooptime, qboolean isRelative )
{
theFxScheduler.PlayEffect(id, org, 0, boltInfo, iGhoul2, -1, -1, -1, qfalse, iLooptime, !!isRelative );
}
void FX_PlayEntityEffectID( int id, vec3_t org,
vec3_t axis[3], const int boltInfo, const int entNum, int vol, int rad )
{
#ifdef __FXCHECKER
if (_isnan(org[0]) || _isnan(org[1]) || _isnan(org[2]))
{
assert(0);
}
#endif // __FXCHECKER
theFxScheduler.PlayEffect(id, org, axis, boltInfo, NULL, -1, vol, rad );
}
void FX_AddScheduledEffects( qboolean portal )
{
theFxScheduler.AddScheduledEffects(!!portal);
}
void FX_Draw2DEffects( float screenXScale, float screenYScale )
{
theFxScheduler.Draw2DEffects( screenXScale, screenYScale );
}
int FX_InitSystem( refdef_t* refdef )
{
return FX_Init( refdef );
}
void FX_SetRefDefFromCGame( refdef_t* refdef )
{
FX_SetRefDef( refdef );
}
qboolean FX_FreeSystem( void )
{
return (qboolean)FX_Free( true );
}
void FX_AdjustTime( int time )
{
theFxHelper.AdjustTime(time);
}
|
gpl-2.0
|
gildaslemoal/elpi
|
runtime/catalina/work/default-server/0.0.0.0/settings/org/apache/jsp/error/error_jsp.java
|
4779
|
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.59
* Generated at: 2015-07-16 22:30:49 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp.error;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.ofbiz.base.util.*;
public final class error_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
response.addHeader("X-Powered-By", "JSP/2.1");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<title>Open For Business Message</title>\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n");
out.write("</head>\n");
out.write("\n");
String errorMsg = (String) request.getAttribute("_ERROR_MESSAGE_");
out.write("\n");
out.write("\n");
out.write("<body bgcolor=\"#FFFFFF\">\n");
out.write("<div align=\"center\">\n");
out.write(" <br/>\n");
out.write(" <table width=\"100%\" border=\"1\" height=\"200\">\n");
out.write(" <tr>\n");
out.write(" <td>\n");
out.write(" <table width=\"100%\" border=\"0\" height=\"200\">\n");
out.write(" <tr bgcolor=\"#CC6666\">\n");
out.write(" <td height=\"45\">\n");
out.write(" <div align=\"center\"><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"4\" color=\"#FFFFFF\"><b>:ERROR MESSAGE:</b></font></div>\n");
out.write(" </td>\n");
out.write(" </tr>\n");
out.write(" <tr>\n");
out.write(" <td>\n");
out.write(" <div align=\"left\"><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"2\">");
out.print(UtilFormatOut.replaceString(errorMsg, "\n", "<br/>"));
out.write("</font></div>\n");
out.write(" </td>\n");
out.write(" </tr>\n");
out.write(" </table>\n");
out.write(" </td>\n");
out.write(" </tr>\n");
out.write(" </table>\n");
out.write("</div>\n");
out.write("<div align=\"center\"></div>\n");
out.write("</body>\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
|
gpl-2.0
|
michaelaw320/YoutubeAudioSplitter
|
YoutubeAudioSplitter/Tools/freac/source/freac-1.0.20a/src/track.cpp
|
836
|
/* BonkEnc Audio Encoder
* Copyright (C) 2001-2008 Robert Kausch <robert.kausch@bonkenc.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the "GNU General Public License".
*
* THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
#include <track.h>
BonkEnc::Track::Track()
{
channels = 0;
rate = 0;
bits = 0;
length = -1;
approxLength = -1;
fileSize = -1;
order = BYTE_INTEL;
isCDTrack = False;
drive = -1;
discid = 0;
cdTrack = -1;
track = -1;
year = -1;
}
BonkEnc::Track::~Track()
{
for (Int i = 0; i < pictures.Length(); i++) delete pictures.GetNth(i);
}
|
gpl-2.0
|
ibnoe/simonev
|
protected/pages/s/pendapatan/Target.php
|
7806
|
<?php
prado::using ('Application.pages.s.pendapatan.MainPagePendapatan');
class Target extends MainPagePendapatan {
public function onLoad ($param) {
parent::onLoad ($param);
$this->showTarget=true;
if (!$this->IsCallback&&!$this->IsPostback) {
if (!isset($_SESSION['currentPageTarget'])||$_SESSION['currentPageTarget']['page_name']!='s.pendapatan.Target') {
$_SESSION['currentPageTarget']=array('page_name'=>'s.pendapatan.Target','page_num'=>0,'no_rek4'=>'none','search'=>false);
}
$this->toolbarOptionsTahunAnggaran->DataSource=$this->TGL->getYear();
$this->toolbarOptionsTahunAnggaran->Text=$this->session['ta'];
$this->toolbarOptionsTahunAnggaran->dataBind();
$this->toolbarOptionsBulanRealisasi->Enabled=false;
$_SESSION['currentPageTarget']['search']=false;
$_SESSION['currentPageTarget']['no_rek4']='none';
$rekening=$this->kegiatan->getList('rek2 WHERE no_rek1=4',array('no_rek2','nama_rek2'),'no_rek2',null,7);
$this->cmbAddKelompok->DataSource=$rekening;
$this->cmbAddKelompok->dataBind();
$this->populateData();
}
}
public function changeTahunAnggaran ($sender,$param) {
$_SESSION['ta']=$this->toolbarOptionsTahunAnggaran->Text;
$this->populateData ($_SESSION['currentPageTarget']['search']);
}
public function renderCallback ($sender,$param) {
$this->RepeaterS->render($param->NewWriter);
}
public function Page_Changed ($sender,$param) {
$_SESSION['currentPageTarget']['page_num']=$param->NewPageIndex;
$this->populateData();
}
public function changeRekening ($sender,$param) {
$_SESSION['currentPageTarget']['no_rek4']='none';
switch ($sender->getId()) {
case 'cmbAddTransaksi' :
$idtransaksi=$this->cmbAddTransaksi->Text;
$this->disableComponentRekening1 ();
$this->disableAndEnabled();
if ($idtransaksi != 'none' || $idtransaksi != '') {
$result=$this->rekening->getListKelompok($idtransaksi);
if (count($result)> 1) {
$this->cmbAddKelompok->DataSource=$result;
$this->cmbAddKelompok->Enabled=true;
$this->cmbAddKelompok->dataBind();
}
}
break;
case 'cmbAddKelompok' :
$idkelompok = $this->cmbAddKelompok->Text;
$this->disableComponentRekening2 ();
$this->disableAndEnabled();
if ($idkelompok != 'none' || $idkelompok !='') {
$result=$this->rekening->getListJenis($idkelompok);
if (count($result)> 1) {
$this->cmbAddJenis->DataSource=$result;
$this->cmbAddJenis->Enabled=true;
$this->cmbAddJenis->dataBind();
}
}
break;
case 'cmbAddJenis' :
$idjenis = $this->cmbAddJenis->Text;
$this->disableComponentRekening3 ();
$this->disableAndEnabled();
if ($idjenis != 'none' || $idjenis != '') {
$result=$this->rekening->getListObjek($idjenis);
if (count($result)> 1) {
$this->cmbAddObjek->DataSource=$result;
$this->cmbAddObjek->Enabled=true;
$this->cmbAddObjek->dataBind();
}
}
break;
case 'cmbAddObjek' :
$idobjek = $this->cmbAddObjek->Text;
if ($idobjek != 'none') {
$_SESSION['currentPageTarget']['no_rek4']=$idobjek;
$this->populateData();
$this->disableAndEnabled(true);
}else{
$this->disableAndEnabled(false);
}
break;
}
}
public function filterRecord($sender,$param) {
$_SESSION['currentPageTarget']['no_rek4']='none';
$_SESSION['currentPageTarget']['search']=true;
$this->populateData($_SESSION['currentPageTarget']['search']);
}
protected function populateData($search=false) {
$tahun=$_SESSION['ta'];
$no_rek4=$_SESSION['currentPageTarget']['no_rek4'];
$str_filter=$no_rek4=='none'||$no_rek4==''?'':" AND no_rek4='$no_rek4'";
$str = "SElECT no_rek5,nama_rek5 FROM v_rekening WHERE no_rek1=4$str_filter";
$str_jumlah = "v_rekening WHERE no_rek1=4$str_filter";
if ($search) {
$kriteria=$this->txtKriteria->Text;
if ($this->cmbBerdasarkan->Text=='kode') {
$str_jumlah = "$str_jumlah AND no_rek5 LIKE '%$kriteria%'";
$str = "$str AND no_rek5 LIKE '%$kriteria%'";
}else {
$str_jumlah = "$str_jumlah AND nama_rek5 LIKE '%$kriteria%'";
$str = "$str AND nama_rek5 LIKE '%$kriteria%'";
}
}
$jumlah_baris=$this->DB->getCountRowsOfTable ($str_jumlah,'no_rek5');
$this->RepeaterS->VirtualItemCount=$jumlah_baris;
$this->RepeaterS->CurrentPageIndex=$_SESSION['currentPageTarget']['page_num'];
$currentPage=$this->RepeaterS->CurrentPageIndex;
$offset=$currentPage*$this->RepeaterS->PageSize;
$itemcount=$this->RepeaterS->VirtualItemCount;
$limit=$this->RepeaterS->PageSize;
if (($offset+$limit)>$itemcount) {
$limit=$itemcount-$offset;
}
if ($limit < 0) {$offset=0;$limit=10;$_SESSION['currentPageTarget']['page_num']=0;}
$str = "$str LIMIT $offset,$limit";
$this->DB->setFieldTable(array('no_rek5','nama_rek5'));
$r=$this->DB->getRecord($str);
$result=array();
$str = "SELECT target FROM target_penerimaan WHERE tahun=$tahun";
$this->DB->setFieldTable(array('target'));
while (list($k,$v)=each ($r)) {
$no_rek5=$v['no_rek5'];
$target=$this->DB->getRecord("$str AND no_rek5='$no_rek5'");
$v['target']=isset($target[1])?$this->finance->toRupiah($target[1]['target']):0;
$result[$k]=$v;
}
$this->RepeaterS->DataSource=$result;
$this->RepeaterS->dataBind();
}
public function saveData ($sender,$param) {
if ($this->Page->IsValid) {
$tahun=$this->session['ta'];
foreach ($this->RepeaterS->Items as $inputan) {
$item=$inputan->txtTargetPenerimaan->getNamingContainer();
$no_rek5=$this->RepeaterS->DataKeys[$item->getItemIndex()];
$target=$this->finance->toInteger($inputan->txtTargetPenerimaan->Text);
$this->DB->deleteRecord("target_penerimaan WHERE no_rek5='$no_rek5' AND tahun=$tahun");
$this->DB->insertRecord("INSERT INTO target_penerimaan (idtarget,no_rek5,target,tahun) VALUES (NULL,'$no_rek5',$target,$tahun)");
}
$this->redirect('s.pendapatan.Target');
}
}
private function disableAndEnabled ($flag=false) {
if ($flag) {
}else {
}
}
private function disableComponentRekening1 () {
$this->cmbAddKelompok->DataSource=array();
$this->cmbAddKelompok->Enabled=false;
$this->cmbAddKelompok->dataBind();
$this->cmbAddJenis->DataSource=array();
$this->cmbAddJenis->Enabled=false;
$this->cmbAddJenis->dataBind();
$this->cmbAddObjek->DataSource=array();
$this->cmbAddObjek->Enabled=false;
$this->cmbAddObjek->dataBind();
}
private function disableComponentRekening2 () {
$this->cmbAddJenis->DataSource=array();
$this->cmbAddJenis->Enabled=false;
$this->cmbAddJenis->dataBind();
$this->cmbAddObjek->DataSource=array();
$this->cmbAddObjek->Enabled=false;
$this->cmbAddObjek->dataBind();
}
private function disableComponentRekening3 () {
$this->cmbAddObjek->DataSource=array();
$this->cmbAddObjek->Enabled=false;
$this->cmbAddObjek->dataBind();
}
}
?>
|
gpl-2.0
|
iionly/Elgg_1.8_izap_videos
|
izap_videos/actions/izap_videos/admin/recycle.php
|
657
|
<?php
/**
* iZAP Videos plugin by iionly
* (based on version 3.71b of the original izap_videos plugin for Elgg 1.7)
* Contact: iionly@gmx.de
* https://github.com/iionly
*
* Original developer of the iZAP Videos plugin:
* @package Elgg videotizer, by iZAP Web Solutions
* @license GNU Public License version 2
* @Contact iZAP Team "<support@izap.in>"
* @Founder Tarun Jangra "<tarun@izap.in>"
* @link http://www.izap.in/
*
*/
$guid = get_input('guid');
$queue_object = new izapQueue();
if ($queue_object->restore($guid)) {
system_message(elgg_echo('izap_videos:adminSettings:restore_video'));
izapTrigger_izap_videos();
}
forward(REFERER);
|
gpl-2.0
|
BayCEER/goat
|
src/main/java/de/unibayreuth/bayeos/goat/panels/attributes/JGeraetPanel.java
|
2796
|
/*******************************************************************************
* Copyright (c) 2011 University of Bayreuth - BayCEER.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* University of Bayreuth - BayCEER - initial API and implementation
******************************************************************************/
package de.unibayreuth.bayeos.goat.panels.attributes;
import java.awt.BorderLayout;
import java.util.Vector;
import org.apache.log4j.Logger;
import de.unibayreuth.bayceer.bayeos.objekt.Mess_Geraet;
import de.unibayreuth.bayeos.goat.JMainFrame;
import de.unibayreuth.bayeos.goat.panels.UpdatePanel;
import de.unibayreuth.bayeos.utils.MsgBox;
/*
* dpMessungen.java
*
* Created on 10. Februar 2003, 13:35
*/
/**
*
* @author oliver
*/
public class JGeraetPanel extends UpdatePanel {
final static Logger logger = Logger.getLogger(JGeraetPanel.class.getName());
private GeraetForm frm;
/** Creates new form dpMessungen */
public JGeraetPanel(JMainFrame app) {
super(app);
frm = new GeraetForm();
add(frm,BorderLayout.CENTER);
}
public boolean loadData() {
try {
Mess_Geraet ger = (Mess_Geraet)helper.getObjekt(objektNode.getId(),objektNode.getObjektart());
if (ger == null) return false;
frm.setId(ger.getId());
frm.setObjektArt(ger.getObjektart());
frm.setBeschreibung(ger.getBeschreibung());
frm.setSeriennr(ger.getSeriennr());
frm.setCTime(ger.getCtime());
frm.setUTime(ger.getUtime());
frm.setCBenutzer(ger.getCbenutzer());
frm.setUBenutzer(ger.getUbenutzer());
boolean enabled = ger.getCheck_write().booleanValue();
frm.setEditable(enabled); // Fields
setEditable(enabled); // Buttons
return true;
} catch (ClassCastException c) {
logger.error(c.getMessage());
return false;
}
}
public boolean updateData() {
try {
Vector attrib = new Vector();
attrib.add(objektNode.getDe());
attrib.add(frm.getBeschreibung());
attrib.add(frm.getSeriennr());
return helper.updateObjekt(frm.getId(),frm.getObjektArt(),attrib);
} catch (NumberFormatException n) {
logger.error(n.getMessage());
MsgBox.error(JGeraetPanel.this,"Wrong Format " + n.getMessage());
return false;
}
}
}
|
gpl-2.0
|
softmediadev/kohana-phonenumber
|
classes/Kohana/PhoneNumber.php
|
8333
|
<?php defined('SYSPATH') or die('No direct script access.');
class Kohana_PhoneNumber
{
protected $number;
protected $config;
protected $phoneNumberUtil;
protected $shortNumberInfo;
protected $phoneNumberGeocoder;
protected $phoneNumber = NULL;
protected $phoneNumberRegion = NULL;
protected $phoneNumberType = NULL;
protected $validNumber = FALSE;
protected $validNumberForRegion = FALSE;
protected $possibleNumber = FALSE;
protected $isPossibleNumberWithReason = NULL;
protected $geolocation = NULL;
protected $phoneNumberToCarrierInfo = NULL;
protected $timezone = NULL;
protected $countryCodeSource = array(
0 => 'FROM_NUMBER_WITH_PLUS_SIGN',
1 => 'FROM_NUMBER_WITH_IDD',
2 => 'FROM_NUMBER_WITHOUT_PLUS_SIGN',
3 => 'FROM_DEFAULT_COUNTRY'
);
protected $possibleNumberReason = array(
0 => 'IS_POSSIBLE',
1 => 'INVALID_COUNTRY_CODE',
2 => 'TOO_SHORT',
3 => 'TOO_LONG'
);
protected $phoneNumberTypes = array(
0 => 'FIXED_LINE',
1 => 'MOBILE',
2 => 'FIXED_LINE_OR_MOBILE',
3 => 'TOLL_FREE',
4 => 'PREMIUM_RATE',
5 => 'SHARED_COST',
6 => 'VOIP',
7 => 'PERSONAL_NUMBER',
8 => 'PAGER',
9 => 'UAN',
10 => 'UNKNOWN',
27 => 'EMERGENCY',
28 => 'VOICEMAIL',
29 => 'SHORT_CODE',
30 => 'STANDARD_RATE'
);
protected $expectedCost = array(
3 => 'TOLL_FREE',
4 => 'PREMIUM_RATE',
30 => 'STANDARD_RATE',
10 => 'UNKNOWN_COST'
);
protected $expectedCostForRegion = array(
3 => 'TOLL_FREE',
4 => 'PREMIUM_RATE',
30 => 'STANDARD_RATE',
10 => 'UNKNOWN_COST'
);
public static function instance( $number = NULL, array $config = NULL )
{
return new self($number, $config);
}
public function __construct( $number, array $config = NULL )
{
$this->number = $number;
$this->config = Kohana::$config->load('phonenumber')->as_array();
if ( ! empty($config))
$this->config = Arr::merge($this->config, $config);
if ( ! isset($this->config['country']))
$this->config['country'] = '';
if (empty($this->config['country']))
throw new Kohana_Exception('Country code is required');
$this->config['country'] = strtoupper($this->config['country']);
if ( ! isset($this->config['language']))
$this->config['language'] = '';
if ( ! isset($this->config['region']))
$this->config['region'] = '';
$this->config['language'] = empty($this->config['language']) ? 'en' : strtolower($this->config['language']);
$this->config['region'] = empty($this->config['region']) ? NULL : strtoupper($this->config['region']);
$this->phoneNumberUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$this->shortNumberInfo = \libphonenumber\ShortNumberInfo::getInstance();
$this->phoneNumberGeocoder = \libphonenumber\geocoding\PhoneNumberOfflineGeocoder::getInstance();
if ( ! empty($number))
{
try {
$this->phoneNumber = $this->phoneNumberUtil->parse($number, $this->config['country'], NULL, TRUE);
$this->possibleNumber = $this->phoneNumberUtil->isPossibleNumber($this->phoneNumber);
$this->isPossibleNumberWithReason = $this->phoneNumberUtil->isPossibleNumberWithReason($this->phoneNumber);
$this->validNumber = $this->phoneNumberUtil->isValidNumber($this->phoneNumber);
$this->validNumberForRegion = $this->phoneNumberUtil->isValidNumberForRegion($this->phoneNumber, $this->config['country']);
$this->phoneNumberRegion = $this->phoneNumberUtil->getRegionCodeForNumber($this->phoneNumber);
$this->phoneNumberType = $this->phoneNumberUtil->getNumberType($this->phoneNumber);
$this->geolocation = $this->phoneNumberGeocoder->getDescriptionForNumber(
$this->phoneNumber,
$this->config['language'],
$this->config['region']
);
$this->phoneNumberToCarrierInfo = \libphonenumber\PhoneNumberToCarrierMapper::getInstance()->getNameForNumber(
$this->phoneNumber,
$this->config['language']
);
$this->timezone = \libphonenumber\PhoneNumberToTimeZonesMapper::getInstance()->getTimeZonesForNumber($this->phoneNumber);
} catch (\libphonenumber\NumberParseException $e) {
throw new Kohana_Exception(
':error',
array(':error' => $e->getMessage()),
$e->getCode()
);
}
}
}
public function getPNObject()
{
return $this->phoneNumber;
}
public function getPNUtilInstance()
{
return $this->phoneNumberUtil;
}
public function getShortNumberInstance()
{
return $this->shortNumberInfo;
}
public function getPNGeocoderInstance()
{
return $this->phoneNumberGeocoder;
}
public function getCountryCodeSource()
{
if ($this->phoneNumber)
return $this->countryCodeSource[$this->phoneNumber->getCountryCodeSource()];
}
public function formatE164()
{
if ($this->phoneNumber)
return $this->phoneNumberUtil->format($this->phoneNumber, \libphonenumber\PhoneNumberFormat::E164);
}
public function formatNational()
{
if ($this->phoneNumber)
return $this->phoneNumberUtil->format($this->phoneNumber, \libphonenumber\PhoneNumberFormat::NATIONAL);
}
public function formatInternational()
{
if ($this->phoneNumber)
return $this->phoneNumberUtil->format($this->phoneNumber, \libphonenumber\PhoneNumberFormat::INTERNATIONAL);
}
public function formatRFC3966()
{
if ($this->phoneNumber)
return $this->phoneNumberUtil->format($this->phoneNumber, \libphonenumber\PhoneNumberFormat::RFC3966);
}
public function formatInOriginalFormat()
{
if ($this->phoneNumber)
return $this->phoneNumberUtil->formatInOriginalFormat($this->phoneNumber, $this->config['country']);
}
public function formatOutOfCountryCallingNumber($country)
{
$country = strtoupper($country);
if ($this->phoneNumber)
return $this->phoneNumberUtil->formatOutOfCountryCallingNumber($this->phoneNumber, $country);
}
public function isPossibleShortNumber()
{
if ($this->phoneNumber)
return $this->shortNumberInfo->isPossibleShortNumber($this->phoneNumber);
}
public function isValidShortNumber()
{
if ($this->phoneNumber)
return $this->shortNumberInfo->isValidShortNumber($this->phoneNumber);
}
public function isPossibleShortNumberForRegion()
{
if ($this->phoneNumber)
return $this->shortNumberInfo->isPossibleShortNumberForRegion($this->phoneNumber, $this->phoneNumberRegion);
}
public function isValidShortNumberForRegion()
{
if ($this->phoneNumber)
return $this->shortNumberInfo->isValidShortNumberForRegion($this->phoneNumber, $this->phoneNumberRegion);
}
public function getExpectedCost()
{
if ($this->phoneNumber)
return $this->expectedCost[$this->shortNumberInfo->getExpectedCost($this->phoneNumber)];
}
public function getExpectedCostForRegion()
{
if ($this->phoneNumber)
return $this->expectedCostForRegion[$this->shortNumberInfo->getExpectedCostForRegion($this->phoneNumber, $this->phoneNumberRegion)];
}
public function isEmergencyNumber()
{
return $this->shortNumberInfo->isEmergencyNumber($this->number, $this->config['country']);
}
public function connectsToEmergencyNumber()
{
return $this->shortNumberInfo->connectsToEmergencyNumber($this->number, $this->config['country']);
}
public function getExampleNumber()
{
return $this->phoneNumberUtil->getExampleNumber($this->config['country']);
}
public function getExampleNumberForType()
{
return $this->phoneNumberUtil->getExampleNumberForType($this->config['country'], $this->phoneNumberType);
}
public function getExampleShortNumber()
{
return $this->phoneNumberUtil->getExampleShortNumber($this->config['country']);
}
public function getGeolocation()
{
return $this->geolocation;
}
public function getCarrier()
{
return $this->phoneNumberToCarrierInfo;
}
public function getTimeZones()
{
if (is_array($this->timezone))
return implode($this->timezone, ', ');
else
return $this->timezone;
}
public function isPossibleNumber()
{
return $this->possibleNumber;
}
public function isPossibleNumberWithReason()
{
return $this->possibleNumberReason[$this->isPossibleNumberWithReason];
}
public function isValidNumber()
{
return $this->validNumber;
}
public function isValidNumberForRegion()
{
return $this->validNumberForRegion;
}
public function getRegionCodeForNumber()
{
return $this->phoneNumberRegion;
}
public function getNumberType()
{
return $this->phoneNumberTypes[$this->phoneNumberType];
}
}
|
gpl-2.0
|
TheTypoMaster/Scaper
|
openjdk/jdk/src/share/classes/com/sun/jdi/ArrayType.java
|
3789
|
/*
* Copyright 1998-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.jdi;
import java.util.List;
/**
* Provides access to the class of an array and the type of
* its components in the target VM.
*
* @see ArrayReference
*
* @author Robert Field
* @author Gordon Hirsch
* @author James McIlree
* @since 1.3
*/
public interface ArrayType extends ReferenceType {
/**
* Creates a new instance of this array class in the target VM.
* The array is created with the given length and each component
* is initialized to is standard default value.
*
* @param length the number of components in the new array
* @return the newly created {@link ArrayReference} mirroring
* the new object in the target VM.
*
* @throws VMCannotBeModifiedException if the VirtualMachine is read-only - see {@link VirtualMachine#canBeModified()}.
*/
ArrayReference newInstance(int length);
/**
* Gets the JNI signature of the components of this
* array class. The signature
* describes the declared type of the components. If the components
* are objects, their actual type in a particular run-time context
* may be a subclass of the declared class.
*
* @return a string containing the JNI signature of array components.
*/
String componentSignature();
/**
* Returns a text representation of the component
* type of this array.
*
* @return a text representation of the component type.
*/
String componentTypeName();
/**
* Returns the component type of this array,
* as specified in the array declaration.
* <P>
* Note: The component type of a array will always be
* created or loaded before the array - see the
* <a href="http://java.sun.com/docs/books/vmspec/">Java Virtual
* Machine Specification</a>, section
* <a href="http://java.sun.com/docs/books/vmspec/2nd-edition/html/ConstantPool.doc.html#79473">5.3.3
* Creating Array Classes</a>.
* However, although the component type will be loaded it may
* not yet be prepared, in which case the type will be returned
* but attempts to perform some operations on the returned type
* (e.g. {@link ReferenceType#fields() fields()}) will throw
* a {@link ClassNotPreparedException}.
* Use {@link ReferenceType#isPrepared()} to determine if
* a reference type is prepared.
*
* @see Type
* @see Field#type() Field.type() - for usage examples
* @return the {@link Type} of this array's components.
*/
Type componentType() throws ClassNotLoadedException;
}
|
gpl-2.0
|
openattic/openattic
|
webui/app/components/ceph-iscsi/shared/ceph-iscsi-state.service.js
|
12173
|
/**
*
* @source: http://bitbucket.org/openattic/openattic
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (c) 2017 SUSE LLC
*
*
* The JavaScript code in this page 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; version 2.
*
* This package 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.
*
* As additional permission under GNU GPL version 2 section 3, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 1, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
* @licend The above is the entire license notice
* for the JavaScript code in this page.
*
*/
"use strict";
import _ from "lodash";
export default class CephIscsiStateService {
constructor (taskQueueSubscriber, taskQueueService, Notification, cephIscsiService) {
this.taskQueueSubscriber = taskQueueSubscriber;
this.taskQueueService = taskQueueService;
this.Notification = Notification;
this.cephIscsiService = cephIscsiService;
this.stopTaskDescr = "iSCSI stop exports";
this.deployTaskDescr = "iSCSI deploy exports";
}
_getHostnameWithoutFqdn (hostname) {
return hostname.indexOf(".") !== -1 ? hostname.substring(0, hostname.indexOf(".")) : hostname;
}
containsHost (hosts, hostname) {
if (!_.isArrayLike(hosts) || hosts.length === 0) {
return false;
}
if (hosts.indexOf(hostname) !== -1) {
return true;
}
let hostsWithoutFqdn = hosts.map((h) => {
return h.indexOf(".") !== -1 ? h.substring(0, h.indexOf(".")) : h;
});
let hostWithoutFqdn = this._getHostnameWithoutFqdn(hostname);
return hostsWithoutFqdn.indexOf(hostWithoutFqdn) !== -1;
}
_getHostState (hosts, hostname) {
if (!_.isUndefined(hosts[hostname])) {
return hosts[hostname];
}
let hostsWithoutFqdn = {};
_.forEach(hosts, (currHost, currHostname) => {
let currentHostnameWithoutFqdn = this._getHostnameWithoutFqdn(currHostname);
hostsWithoutFqdn[currentHostnameWithoutFqdn] = currHost;
});
let hostWithoutFqdn = this._getHostnameWithoutFqdn(hostname);
return hostsWithoutFqdn[hostWithoutFqdn];
}
_getStatesByHosts (rows, hosts, state) {
let states = {};
rows.forEach((row) => {
row.portals.forEach((portal) => {
if (this.containsHost(hosts, portal.hostname)) {
if (_.isUndefined(states[row.targetId])) {
states[row.targetId] = {
hostsStarting: [],
hostsStopping: [],
hostsEnabled: [],
hostsDisabled: []
};
}
if (state === "STARTING") {
states[row.targetId].hostsStarting.push(portal.hostname);
} else if (state === "STOPPING") {
states[row.targetId].hostsStopping.push(portal.hostname);
}
}
});
});
return states;
}
_updateStates (fsid, rows, updateHosts) {
let taskIds = [];
this.taskQueueService
.get({
status: "Not Started"
})
.$promise
.then((notStartedTasksResult) => {
notStartedTasksResult.results.forEach((notStartedTask) => {
if (notStartedTask.description === this.stopTaskDescr ||
notStartedTask.description === this.deployTaskDescr) {
taskIds.push(notStartedTask.id);
const state = notStartedTask.description === this.stopTaskDescr ? "STOPPING" : "STARTING";
const statesTargets = this._getStatesByHosts(rows, notStartedTask.hosts, state);
let statesHosts = {};
notStartedTask.hosts.forEach((hostname) => {
statesHosts[hostname] = {
state: state
};
});
updateHosts(state, {targets: statesTargets, hosts: statesHosts});
}
});
this.taskQueueService
.get({
status: "Running"
})
.$promise
.then((runningTasksResult) => {
runningTasksResult.results.forEach((runningTask) => {
if (runningTask.description === this.stopTaskDescr || runningTask.description === this.deployTaskDescr) {
if (taskIds.indexOf(runningTask.id) === -1) {
taskIds.push(runningTask.id);
const state = runningTask.description === this.stopTaskDescr ? "STOPPING" : "STARTING";
const statesTargets = this._getStatesByHosts(rows, runningTask.hosts, state);
let statesHosts = {};
runningTask.hosts.forEach((hostname) => {
statesHosts[hostname] = {
state: state
};
});
updateHosts(state, {targets: statesTargets, hosts: statesHosts});
}
}
});
taskIds.forEach((taskId) => {
this.taskQueueSubscriber.subscribe(taskId, () => {
this._updateStates(fsid, rows, updateHosts);
});
});
if (taskIds.length === 0) {
this.cephIscsiService
.iscsistatus({
fsid: fsid
})
.$promise
.then((res) => {
let states = {};
rows.forEach((row) => {
row.portals.forEach((portal) => {
if (_.isUndefined(states[row.targetId])) {
states[row.targetId] = {
hostsStarting: [],
hostsStopping: [],
hostsEnabled: [],
hostsDisabled: []
};
}
let hostState = this._getHostState(res, portal.hostname);
if (_.isObjectLike(hostState) &&
_.isObjectLike(hostState.targets) &&
_.isObjectLike(hostState.targets[row.targetId])) {
if (hostState.targets[row.targetId].enabled) {
states[row.targetId].hostsEnabled.push(portal.hostname);
} else {
states[row.targetId].hostsDisabled.push(portal.hostname);
}
} else {
states[row.targetId].hostsDisabled.push(portal.hostname);
}
});
});
_.forEach(res, (hostState) => {
if (!_.isUndefined(hostState.active)) {
hostState.state = hostState.active ? "RUNNING" : "STOPPED";
}
});
updateHosts(res.status ? "RUNNING" : "STOPPED", {targets: states, hosts: res}, true);
})
.catch(() => {
updateHosts();
});
}
})
.catch(() => {
updateHosts();
});
})
.catch(() => {
updateHosts();
});
}
updateHosts (fsid, hosts) {
_.forEach(hosts, (host, hostname) => {
if (!_.isUndefined(host.active)) {
hosts[hostname] = {
state: "LOADING"
};
}
});
this._updateStates(fsid, [], (stateByHost, states, updateAll) => {
if (!_.isUndefined(states) && !_.isUndefined(states.hosts)) {
_.forEach(hosts, (host, hostname) => {
let stateHost = states.hosts[hostname];
if (!_.isUndefined(stateHost)) {
if (!_.isUndefined(stateHost.state)) {
host.state = stateHost.state;
}
}
});
}
if (updateAll) {
_.forEach(hosts, (host) => {
if (["LOADING", "STARTING", "STOPPING"].indexOf(host.state) !== -1) {
host.state = "UNKNOWN";
}
});
}
});
}
update (fsid, results) {
results.forEach((row) => {
row.state = "LOADING";
delete row.hostsEnabled;
delete row.hostsDisabled;
});
this._updateStates(fsid, results, (stateByHost, states, updateAll) => {
if (!_.isUndefined(states) && !_.isUndefined(states.targets)) {
results.forEach((row) => {
let targetState = states.targets[row.targetId];
if (!_.isUndefined(targetState)) {
if (targetState.hostsStarting.length > 0) {
row.state = "STARTING";
} else if (targetState.hostsStopping.length > 0) {
row.state = "STOPPING";
} else if (targetState.hostsEnabled.length > 0) {
if (targetState.hostsDisabled.length > 0) {
row.state = "RUNNING_WARN";
row.hostsEnabled = targetState.hostsEnabled;
row.hostsDisabled = targetState.hostsDisabled;
} else {
row.state = "RUNNING";
}
} else {
row.state = "STOPPED";
}
}
});
}
if (updateAll) {
results.forEach((row) => {
if (["LOADING", "STARTING", "STOPPING"].indexOf(row.state) !== -1) {
row.state = "UNKNOWN";
}
});
}
});
}
start (host, hostname, fsid) {
host.active = undefined;
host.state = "STARTING";
this.cephIscsiService
.iscsideploy({
fsid: fsid,
minions: [hostname]
})
.$promise
.then((res) => {
this.taskQueueSubscriber.subscribe(res.taskqueue_id, () => {
this._updateStates(fsid, [], (state, states, updateAll) => {
if (!_.isUndefined(states) && !_.isUndefined(states.hosts) && !_.isUndefined(states.hosts[hostname])) {
host.state = states.hosts[hostname].state;
if (host.state === "RUNNING") {
this.Notification.success({
title: hostname + " started successfully"
});
} else if (host.state === "STOPPED") {
this.Notification.error({
title: "Error starting " + hostname
});
}
}
if (updateAll) {
if (["LOADING", "STARTING", "STOPPING"].indexOf(host.state) !== -1) {
host.state = "UNKNOWN";
}
}
});
});
})
.catch(() => {
host.active = undefined;
host.state = undefined;
});
}
stop (host, hostname, fsid) {
host.active = undefined;
host.state = "STOPPING";
this.cephIscsiService
.iscsiundeploy({
fsid: fsid,
minions: [hostname]
})
.$promise
.then((res) => {
this.taskQueueSubscriber.subscribe(res.taskqueue_id, () => {
this._updateStates(fsid, [], (state, states, updateAll) => {
if (!_.isUndefined(states) && !_.isUndefined(states.hosts) && !_.isUndefined(states.hosts[hostname])) {
host.state = states.hosts[hostname].state;
if (host.state === "STOPPED") {
this.Notification.success({
title: hostname + " stopped successfully"
});
} else if (host.state === "RUNNING") {
this.Notification.error({
title: "Error stopping " + hostname
});
}
}
if (updateAll) {
if (["LOADING", "STARTING", "STOPPING"].indexOf(host.state) !== -1) {
host.state = "UNKNOWN";
}
}
});
});
})
.catch(() => {
host.active = undefined;
host.state = undefined;
});
}
}
|
gpl-2.0
|
davidepedranz/algoritmi_2014
|
lezione_2/sortpesato.cpp
|
3730
|
//============================================================================
// Name : sortpesato.cpp
// Author : Davide Pedranz
// Version : 1n
// Licence : GPL v2
// Description : See statement.
//============================================================================
// #include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// struct Result {
// int swaps;
// int cost;
// Result() {
// swaps = 0;
// cost = 0;
// }
// };
struct Block {
int value;
bool visited;
Block(int v) {
visited = false;
value = v;
}
int getValue() {
visited = true;
return value;
}
};
// returns min element index
int posMin(int* a, int start, int end) {
int min = a[start];
int pos = start;
for(int i = start + 1; i < end; i++) {
if(a[i] < min) {
min = a[i];
pos = i;
}
}
return pos;
}
// numero di scambi fatti da algoritmo selectionSort (mettendo minimo in cima)
int computeSwaps(int* a, int n) {
int swaps = 0;
int indexMin;
for(int i = 0; i < n; i++) {
indexMin = posMin(a, i, n);
if(indexMin != i) {
swap(a[i], a[indexMin]);
swaps++;
}
}
return swaps;
}
// ======================================================================================================================
// ======================================================================================================================
// void printArray(int* array, int n) {
// for(int i = 0; i < n; i++) {
// cout << array[i] << " ";
// }
// cout << endl;
// }
// void printVV(vector<vector<int>>& vv) {
// int i = 1;
// for(vector<int> v : vv) {
// cout << "vettore " << i++ << ":\t";
// for(int el : v) {
// cout << el << " ";
// }
// cout << endl;
// }
// }
// void printV(vector<int>& v) {
// for(int el : v) {
// cout << el << " ";
// }
// cout << endl;
// }
// wrapper
int computeCost(int* a, int n) {
Block** b = new Block*[n+1];
vector<vector<int>> vv;
for(int i = 1; i <= n; i++) {
b[i] = new Block(a[i-1]);
}
// printArray(a, n);
// for(int i = 1; i <= n; i++) {
// cout << b[i] -> value << " ";
// }
// cout << endl;
for(int i = 1; i <= n; i++) {
if(!b[i]->visited && b[i]->value != i) {
vector<int> v;
Block* current = b[i];
int value = current->getValue();
v.push_back(value);
Block* next = b[value];
while(!next->visited) {
int val = next->getValue();
v.push_back(val);
next = b[val];
}
vv.push_back(v);
}
}
// printVV(vv);
int totalCost = 0;
for(auto v : vv) {
// cout << endl;
// printV(v);
int sum = 0;
int min = n+10;
for(int el : v) {
sum += el;
if(el < min) {
min = el;
}
}
int costA = sum - min + min * (v.size() - 1);
// cout << "cost A: " << costA << endl;
int costB = sum - min + 1 * (v.size() - 1) + 2 * (1 + min);
// cout << "cost B: " << costB << endl;
int realCost = costA < costB ? costA : costB;
// cout << "realCost: " << realCost << endl;
totalCost += realCost;
}
for(int i = 0; i < n; i++) {
delete b[i];
}
delete[] b;
return totalCost;
}
// ======================================================================================================================
// ======================================================================================================================
int main() {
ifstream in("input.txt");
ofstream out("output.txt");
// read data
int n;
in >> n;
int* a = new int[n];
int* b = new int[n];
// read array from input file
for(int i = 0; i < n; i++) {
in >> a[i];
b[i] = a[i];
}
int swaps = computeSwaps(a, n);
int cost = computeCost(b, n);
// return
out << swaps << " " << cost << endl;
delete[] a;
delete[] b;
return 0;
}
|
gpl-2.0
|
msmobility/silo
|
useCases/munich/src/main/java/de/tum/bgu/msm/data/person/PersonMuc.java
|
3607
|
package de.tum.bgu.msm.data.person;
import de.tum.bgu.msm.data.household.Household;
import de.tum.bgu.msm.schools.PersonWithSchool;
import java.util.Optional;
public class PersonMuc implements PersonWithSchool {
private final Person delegate;
private Nationality nationality;
private int schoolType = 0;
private int schoolPlace = 0;
private int schoolId = -1;
public PersonMuc(int id, int age,
Gender gender, Occupation occupation,
PersonRole role, int jobId,
int income) {
delegate = new PersonImpl(id, age, gender, occupation, role, jobId, income);
}
@Override
public void setSchoolType(int schoolType) {this.schoolType = schoolType; }
@Override
public int getSchoolType() {return schoolType;}
@Override
public void setSchoolPlace(int schoolPlace) {
this.schoolPlace = schoolPlace;
}
@Override
public int getSchoolPlace() {return schoolPlace;}
@Override
public int getSchoolId() {
return schoolId;
}
@Override
public void setSchoolId(int schoolId) {
this.schoolId = schoolId;
}
public void setNationality(Nationality nationality) {
this.nationality = nationality;
}
public Nationality getNationality() {
return nationality;
}
@Override
public void setHousehold(Household householdId) {
delegate.setHousehold(householdId);
}
@Override
public Household getHousehold() {
return delegate.getHousehold();
}
@Override
public void setRole(PersonRole pr) {
delegate.setRole(pr);
}
@Override
public void birthday() {
delegate.birthday();
}
@Override
public void setIncome(int newIncome) {
delegate.setIncome(newIncome);
}
@Override
public void setWorkplace(int newWorkplace) {
delegate.setWorkplace(newWorkplace);
}
@Override
public void setOccupation(Occupation newOccupation) {
delegate.setOccupation(newOccupation);
}
@Override
public int getId() {
return delegate.getId();
}
@Override
public int getAge() {
return delegate.getAge();
}
@Override
public Gender getGender() {
return delegate.getGender();
}
@Override
public Occupation getOccupation() {
return delegate.getOccupation();
}
@Override
public int getAnnualIncome() {
return delegate.getAnnualIncome();
}
@Override
public PersonType getType() {
return delegate.getType();
}
@Override
public PersonRole getRole() {
return delegate.getRole();
}
@Override
public int getJobId() {
return delegate.getJobId();
}
@Override
public void setDriverLicense(boolean driverLicense) {
delegate.setDriverLicense(driverLicense);
}
@Override
public boolean hasDriverLicense() {
return delegate.hasDriverLicense();
}
@Override
public String toString() {
return delegate.toString()
+"\nNationality " + nationality
+"\nSchool type " + schoolType
+"\nSchool place " + schoolPlace
+"\nSchool id " + schoolId;
}
@Override
public Optional<Object> getAttribute(String key) {
return delegate.getAttribute(key);
}
@Override
public void setAttribute(String key, Object value) {
delegate.setAttribute(key, value);
}
}
|
gpl-2.0
|
guc-spinet/saishokukenbi
|
wp-content/themes/opinion_tcd018/single-press.php
|
2000
|
<?php get_header(); $options = get_desing_plus_option(); ?>
<div id="main_col">
<ul id="bread_crumb" class="clearfix">
<li class="home"><a href="<?php echo esc_url(home_url('/')); ?>"><span><?php _e('Home', 'tcd-w'); ?></span></a></li>
<li><a href="<?php echo get_post_type_archive_link('press'); ?>"><span><?php _e('Press Release Archive', 'tcd-w'); ?></span></a></li>
<li class="last"><?php the_title(); ?></li>
</ul>
<div id="left_col">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="news_title">
<h2><?php the_title(); ?></h2>
<p class="date"><?php the_time('Y-n-j'); ?></p>
</div>
<div class="post clearfix">
<?php the_content(__('Read more', 'tcd-w')); ?>
<?php custom_wp_link_pages(); ?>
</div><!-- END .post -->
<?php endwhile; endif; ?>
<?php if ($options['show_next_post']) : ?>
<div id="previous_next_post" class="clearfix">
<p id="previous_post"><?php previous_post_link('%link') ?></p>
<p id="next_post"><?php next_post_link('%link') ?></p>
</div>
<?php endif; ?>
<?php // Recent news --------------------------------------------------------------------------------------- ?>
<div id="Recent_news">
<h3 class="headline2"><?php _e("Recent Press Release","tcd-w"); ?></h3>
<?php
$args = array('post_type' => 'press', 'posts_per_page' => 5);
$recent_news = get_posts($args);
if ($recent_news) {
?>
<ul id="news_list" class="clearfix">
<?php foreach ($recent_news as $post) : setup_postdata ($post); ?>
<li class="clearfix">
<p class="news_date"><?php the_time('Y/n/j'); ?></p>
<h4 class="news_title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h4>
</li>
<?php endforeach; wp_reset_query(); ?>
</ul>
<?php }; ?>
</div><!-- END #recent_news -->
</div><!-- END #left_col -->
<?php get_template_part('sidebar1'); ?>
</div><!-- END #main_col -->
<?php get_template_part('sidebar2'); ?>
<?php get_footer(); ?>
|
gpl-2.0
|
bobbingwide/oik-clone
|
shortcodes/oik-cloned.php
|
3744
|
<?php // (C) Copyright Bobbing Wide 2015, 2019
/**
* Implement [cloned] shortcode for oik-clone
*
* The cloned shortcode will display the same sort of content as the Clone on update meta box
* only listing the targets where the cloning has been done.
*
* The links will probably be ugly initially
*
*
* @TODO If used in a widget then it should only work with the page is_single(). How can we tell? What will the filter be?
*
*/
function oik_cloned( $atts=null, $content=null, $tag=null ) {
if ( !defined( "OIK_APIKEY" ) ) return '';
oik_require( 'shortcodes/oik-clone.php', 'oik-clone');
$id = oik_clone_maybe_get_current_post_id( $atts );
if ( $id ) {
$atts['id'] = $id;
oik_cloned_display_links( $id, $atts );
} else {
bw_trace2( "Missing post ID" );
}
return( bw_ret() );
}
/**
* Display the links to cloned content
*
* We don't care about the post type's publicize setting
* Just look at the post meta data
* We don't even need to know the current slaves?
*
* Displaying the "label" is optional.
*
* @param ID $post_id - the ID of the post
* @param array $atts - shortcode attributes incl ['id'] matching $post_id
*/
function oik_cloned_display_links( $post_id, $atts ) {
oik_require( "admin/class-oik-clone-meta-clone-ids.php", "oik-clone" );
$clone_meta = new OIK_clone_meta_clone_ids();
$cloned = $clone_meta->get_clone_info( $post_id );
//$clones = get_post_meta( $post_id, "_oik_clone_ids", false );
//$cloned = oik_reduce_from_serialized( $clones );
if ( count( $cloned ) ) {
$label = bw_array_get_dcb( $atts, "label", "Clones of: ", "__", "oik-clone" );
if ( $label !== false ) {
e( $label );
alink( null, get_permalink( $post_id ), get_the_title( $post_id ) );
}
oik_require( "shortcodes/oik-list.php" );
$uo = bw_sl( $atts );
foreach ( $cloned as $server => $post ) {
bw_trace2( $post, "post", false, BW_TRACE_DEBUG );
if ( is_array( $post ) ) {
$cloned_date = bw_array_get( $post, "cloned", null );
$post = bw_array_get( $post, "id", null );
if ( is_array( $post ) ) {
$post = bw_array_get( $post, "id", null );
if ( null == $post ) {
// Oh good, only two levels of nesting.
} else {
// It could still be an array. We need to stop!
$post=0;
}
} else {
//print_r( $post );
//bw_trace2( $post, "post now?", false );
}
} else {
$cloned_date = null;
}
//bw_trace2( $post, "post now?", false );
$url = "$server/?p=$post";
stag( "li" );
alink( null, $url );
if ( $cloned_date ) {
br();
e( bw_format_date( $cloned_date, "M j, Y @ G:i" ) );
}
oik_cloned_display_dnc( $post_id, $server );
etag( "li" );
}
bw_el( $uo );
}
}
/**
* @param string $shortcode
*
* @return string
*/
function oik_cloned_display_dnc( $post_id, $server ) {
static $clone_meta_dnc = null;
if ( null === $clone_meta_dnc ) {
oik_require( "admin/class-oik-clone-meta-clone-dnc.php", "oik-clone" );
$clone_meta_dnc = new OIK_clone_meta_clone_dnc();
$clone_meta_dnc->get_dnc_info( $post_id );
}
if ( $clone_meta_dnc->is_slave_dnc( $server ) ) {
e( ' - Do Not Clone');
}
}
/*
* Help hook for [cloned] shortcode
*/
function cloned__help( $shortcode="cloned" ) {
return( "Display clones of this content" );
}
/**
* Syntax hook for [cloned] shortcode
*/
function cloned__syntax( $shortcode="cloned" ) {
$syntax = array( "ID,0" => bw_skv( null, "<i>ID</i>", "Post ID" )
, "uo" => bw_skv( "u", "o|d", "List type" )
, "label" => bw_skv( __( "Clones of: ", "oik-clone" ), "<i>text</i>|false", "Prefix with source link" )
);
return( $syntax );
}
|
gpl-2.0
|
opieproject/opie
|
i18n/de/libpolished.ts
|
218
|
<!DOCTYPE TS><TS>
<defaultcodec>iso8859-1</defaultcodec>
<context>
<name>Decoration</name>
<message>
<source>Polished</source>
<translation>Poliert</translation>
</message>
</context>
</TS>
|
gpl-2.0
|
mlerner/nicely
|
app/controllers/reports_controller.rb
|
348
|
class ReportsController < ApplicationController
before_filter :load_task
def create
@report = Report.new
@report.user = User.find_by_id(params[:user_id])
@task.reports << @report
if @report.save && @task.save
render json: {report: @report, success: true }
else
render json: { success: false }
end
end
end
|
gpl-2.0
|
arezki1990/wordpress
|
wp-content/plugins/email-subscribers/email-subscribers.php
|
2600
|
<?php
/*
Plugin Name: Email Subscribers
Plugin URI: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/
Description: Email subscribers plugin has options to send newsletters to subscribers. It has a separate page with HTML editor to create a HTML newsletter. Also have options to send notification email to subscribers when new posts are published to your blog. Separate page available to include and exclude categories to send notifications.
Version: 2.5
Author: Gopi Ramasamy
Donate link: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/
Author URI: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
/*
Copyright 2014 Email subscribers (http://www.gopiplus.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { die('You are not allowed to call this page directly.'); }
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'base'.DIRECTORY_SEPARATOR.'es-defined.php');
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'es-stater.php');
add_action('admin_menu', array( 'es_cls_registerhook', 'es_adminmenu' ));
register_activation_hook(ES_FILE, array( 'es_cls_registerhook', 'es_activation' ));
register_deactivation_hook(ES_FILE, array( 'es_cls_registerhook', 'es_deactivation' ));
add_action( 'widgets_init', array( 'es_cls_registerhook', 'es_widget_loading' ));
add_shortcode( 'email-subscribers', 'es_shortcode' );
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'es-directly.php');
function es_textdomain()
{
load_plugin_textdomain( 'email-subscribers' , false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'es_textdomain');
add_action( 'transition_post_status', array( 'es_cls_sendmail', 'es_prepare_notification' ), 10, 3 );
?>
|
gpl-2.0
|
5putnik/discreta12eueumesmoehugo
|
doc/html/search/variables_4.js
|
875
|
var searchData=
[
['para',['para',['../structflecha__st.html#a5223790dbdf3eb9f52abc54d6e959833',1,'flecha_st']]],
['pos',['pos',['../structlugar__st.html#ad5ba855068e8634869b5751b70279774',1,'lugar_st::pos()'],['../structpassa__dados__st.html#a5057d2ab77480a830502f7b82ad38992',1,'passa_dados_st::pos()'],['../structconta__trans__st.html#aed874882a2027e3868cd5031ee0c922d',1,'conta_trans_st::pos()']]],
['prox',['prox',['../structflecha__st.html#abad38d52ef7177586f206eea56a7ed06',1,'flecha_st::prox()'],['../structlugar__st.html#a5fad74bfc2a653bb14f801978ff20dc3',1,'lugar_st::prox()'],['../structthread__st.html#a63d87e3def93637001505e0f1b92320e',1,'thread_st::prox()'],['../structpassa__dados__st.html#a661b5b8e30c20dc8a4eae1ff90acbdf9',1,'passa_dados_st::prox()'],['../structconta__trans__st.html#a54a41f162a51befa671af798241a37c6',1,'conta_trans_st::prox()']]]
];
|
gpl-2.0
|
MikkelSandbag/seElgg
|
mod/twitter_api/languages/pl.php
|
3994
|
<?php
return array (
'twitter_api' => 'Usługi Twittera',
'twitter_api:requires_oauth' => 'Usługi Twittera wymagają włączonego pluginu dostarczającego bibliotekę OAuth.',
'twitter_api:consumer_key' => 'Klucz konsumenta',
'twitter_api:consumer_secret' => 'Sekretny klucz konsumenta',
'twitter_api:settings:instructions' => 'Musisz uzyskać klucz (ang. consumer key) na stronie <a href="https://dev.twitter.com/apps/new" target="_blank">Twitter</a>. Wypełnij zgłoszenie nowej aplikacji. Wybierz "Browser" jako typ aplikacji oraz "Read & Write" jako rodzaj dostępu. Url wywołania zwrotnego (ang. callback) to %stwitter_api/authorize',
'twitter_api:usersettings:description' => "Połącz swoje %s konto z Twitterem.",
'twitter_api:usersettings:request' => "Musisz się najpierw <a href=\"%s\">uwierzytelnić</a> %s aby mieć dostęp to konta na Twitterze.",
'twitter_api:usersettings:cannot_revoke' => "Nie można rozłączyć twojego konta na Twitterze, ponieważ nie wprowadziłeś adresu e-mail ani hasła. <a href=\"%s\">Wprowadź je teraz</a>.",
'twitter_api:authorize:error' => 'Nie powiodła się aautoryzacja na Twitterze.',
'twitter_api:authorize:success' => 'Autoryzowano dostęp do Twittera.',
'twitter_api:usersettings:authorized' => "Autoryzowałeś dostęp %s do twojego konta na Twitterze: @%s.",
'twitter_api:usersettings:revoke' => 'Kliknij <a href="%s">tutaj</a> aby cofnąć dostęp.',
'twitter_api:usersettings:site_not_configured' => 'Administrator musi skonfigurować Twittera, zanim będzie można go użyć.',
'twitter_api:revoke:success' => 'Cofnięto dostęp do Twittera.',
'twitter_api:post_to_twitter' => "Wysyłać wpisy mikrobloga na Twitter'a?",
'twitter_api:login' => 'Zezwolić użytkownikom na logowanie poprzez Twitter\'a?',
'twitter_api:new_users' => 'Czy pozwolić na rejestrację przy użyciu kont na Twitterze, nawet gdy rejestracja jest wyłączona?',
'twitter_api:login:success' => 'Zostałeś zalogowany.',
'twitter_api:login:error' => 'Nie powiodło się logowanie na Twitterze.',
'twitter_api:login:email' => "Musisz podać poprawny adres e-mail do twojego nowego %s konta.",
'twitter_api:invalid_page' => 'Błędna strona',
'twitter_api:deprecated_callback_url' => 'Adres zwrotny URL został zmieniony w API Twittera na %s. Poproś administratora o zmianę.',
'twitter_api:interstitial:settings' => 'Zmień swoje ustawienia',
'twitter_api:interstitial:description' => 'Już prawie wszystko gotowe aby używać %s! Potrzebujemy jeszcze tylko kilku dodatkowych informacji. Są one opcjonalne, ale pozwolą na logowanie się w przypadku jeśli Twitter będzie niedostępny lub zdecydujesz się rozłączyć konta.',
'twitter_api:interstitial:username' => 'To twój login. Nie może zostać zmieniony. Jeśli ustawisz hasło, będziesz mógł użyć loginu lub adresu e-mail aby się zalogować.',
'twitter_api:interstitial:name' => 'To jest nazwa, którą inne osoby zobaczą wchodząc z Tobą w interakcje.',
'twitter_api:interstitial:email' => 'Twój adres e-mail. Inni użytkownicy domyślnie go nie zobaczą.',
'twitter_api:interstitial:password' => 'Hasło na wypadek niedostępności Twittera lub rozłączenia kont.',
'twitter_api:interstitial:password2' => 'To samo hasło, ponownie.',
'twitter_api:interstitial:no_thanks' => 'Nie, dziękuję',
'twitter_api:interstitial:no_display_name' => 'Musisz posiadać nazwę do wyświetlania.',
'twitter_api:interstitial:invalid_email' => 'Musisz podać poprawny adres e-mail lub pozostawić to pole pustym.',
'twitter_api:interstitial:existing_email' => 'Ten adres e-mail jest już zarejestrowany na tej stronie.',
'twitter_api:interstitial:password_mismatch' => 'Twoje hasła do siebie nie pasują.',
'twitter_api:interstitial:cannot_save' => 'Nie udało się zapisać szczegółów konta.',
'twitter_api:interstitial:saved' => 'Szczegóły konta zostały zapisane!'
);
|
gpl-2.0
|
faddison/Cleftgoose
|
plugins/system/jsntplframework/libraries/joomlashine/api/lightcart.php
|
4830
|
<?php
/**
* @version $Id$
* @package JSNExtension
* @subpackage JSNTplFramework
* @author JoomlaShine Team <support@joomlashine.com>
* @copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved.
* @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*
* Websites: http://www.joomlashine.com
* Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
* JSN Lightcart API
*
* @package JSNTplFramework
* @subpackage Template
* @since 1.0.0
*/
abstract class JSNTplApiLightcart
{
/**
* @var string
*/
private static $_lightcartUrl = 'http://www.joomlashine.com/index.php?option=com_lightcart';
/**
* Retrieve all product editions
*
* @param string $category Category of the product
* @param string $id Identified name of the product
*
* @return array
*/
public static function getProductDetails ($category, $id)
{
try
{
$response = JSNTplHttpClient::get('http://www.joomlashine.com/versioning/product_version.php?category=' . $category);
}
catch (Exception $e)
{
throw $e;
}
// Decoding content
$responseContent = trim($response['body']);
$responseObject = json_decode($responseContent);
if ($responseObject == null) {
throw new Exception($responseContent);
}
$productDetails = null;
// Loop to each item to find product details
foreach ($responseObject->items as $item) {
if ($item->identified_name == $id) {
$productDetails = $item;
break;
}
}
if (empty($productDetails)) {
throw new Exception(JText::_('JSN_TPLFW_INVALID_PRODUCT_ID'));
}
return $productDetails;
}
/**
* Retrieve all editions of the product that have bought by customer
*
* @param string $id Identified name of the product
* @param string $username Customer username
* @param string $password Customer password
*
* @return array
*/
public static function getOrderedEditions ($id, $username, $password)
{
$joomlaVersion = JSNTplHelper::getJoomlaVersion();
// Send request to joomlashine server to checking customer information
$options = array(
'RequestMethod' => 'POST',
'PostValues' => array(
'controller' => 'remoteconnectauthentication',
'task' => 'authenticate',
'tmpl' => 'component',
'identified_name' => $id,
'joomla_version' => $joomlaVersion,
'username' => $username,
'password' => $password,
'upgrade' => 'no',
'custom' => '1',
'language' => JFactory::getLanguage()->getTag()
)
);
try
{
$response = JSNTplHttpClient::get(self::$_lightcartUrl, '', true, $options);
}
catch (Exception $e)
{
throw $e;
}
// Retrieve response content
$responseContent = trim($response['body']);
$responseObject = json_decode($responseContent);
if ($responseObject === null) {
throw new Exception($responseContent);
}
return $responseObject->editions;
}
/**
* Download product installation package from lightcart.
* Return path to downloaded package when download successfull
*
* @param string $id Identified name of the product
* @param string $edition Product edition to download
* @param string $username Customer username
* @param string $password Customer password
*
* @return string
*/
public static function downloadPackage ($id, $edition = null, $username = null, $password = null, $savePath = null)
{
$joomlaVersion = JSNTplHelper::getJoomlaVersion(2);
// Send request to joomlashine server to checking customer information
$postData = array(
'controller' => 'remoteconnectauthentication',
'task' => 'authenticate',
'tmpl' => 'component',
'identified_name' => $id,
'joomla_version' => $joomlaVersion,
'upgrade' => 'yes',
'custom' => '1',
'language' => JFactory::getLanguage()->getTag()
);
if (!empty($edition)) {
$postData['edition'] = $edition;
}
if (!empty($username) && !empty($password)) {
$postData['username'] = $username;
$postData['password'] = $password;
}
$config = JFactory::getConfig();
$tmpPath = empty($savePath) && !is_dir($savePath) ? $config->get('tmp_path') : $savePath;
$downloadUrl = self::$_lightcartUrl . '&' . http_build_query($postData);
$filePath = $tmpPath . '/jsn-' . $id . '.zip';
try
{
JSNTplHttpClient::get($downloadUrl, $filePath);
// Validate downloaded update package
if (filesize($filePath) < 10)
{
// Get LightCart error code
$errorCode = file_get_contents($filePath);
throw new Exception(JText::_('JSN_TPLFW_LIGHTCART_ERROR_' . $errorCode));
}
}
catch (Exception $e)
{
throw $e;
}
return $filePath;
}
}
|
gpl-2.0
|
JarnoVgr/ZombieSurvival
|
gamemodes/zombiesurvival/entities/entities/prop_gunturret/init.lua
|
6818
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
ENT.LastHitSomething = 0
local function RefreshTurretOwners(pl)
for _, ent in pairs(ents.FindByClass("prop_gunturret")) do
if ent:IsValid() and ent:GetObjectOwner() == pl then
ent:ClearObjectOwner()
ent:ClearTarget()
end
end
end
hook.Add("PlayerDisconnected", "GunTurret.PlayerDisconnected", RefreshTurretOwners)
hook.Add("OnPlayerChangedTeam", "GunTurret.OnPlayerChangedTeam", RefreshTurretOwners)
function ENT:Initialize()
self:SetModel("models/Combine_turrets/Floor_turret.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:SetMass(50)
phys:EnableMotion(false)
phys:Wake()
end
self:SetAmmo(self.DefaultAmmo)
self:SetMaxObjectHealth(250)
self:SetObjectHealth(self:GetMaxObjectHealth())
--[[ local RandomSkin = math.random(1,3)
local MaterialToApply = ""
-- Skin 1
if RandomSkin == 1 then
MaterialToApply = "models/Floor_turret/Floor_turret/floor_turret_citizen"
elseif RandomSkin == 2 then
MaterialToApply = "models/Floor_turret/Floor_turret/floor_turret_citizen2"
elseif RandomSkin == 3 then
MaterialToApply = "models/Floor_turret/Floor_turret/floor_turret_citizen4"
end
self:SetMaterial(MaterialToApply)
-- self:SetMaterial("models/Floor_turret/Floor_turret/floor_turret_citizen", forceMaterial = true)
]]--
end
function ENT:SetObjectHealth(health)
self:SetDTFloat(3, health)
if health <= 0 and not self.Destroyed then
self.Destroyed = true
local pos = self:LocalToWorld(self:OBBCenter())
local effectdata = EffectData()
effectdata:SetOrigin(pos)
util.Effect("Explosion", effectdata, true, true)
local amount = math.ceil(self:GetAmmo() * 0.5)
while amount > 0 do
local todrop = math.min(amount, 50)
amount = amount - todrop
local ent = ents.Create("prop_ammo")
if ent:IsValid() then
local heading = VectorRand():GetNormalized()
ent:SetAmmoType("smg1")
ent:SetAmmo(todrop)
ent:SetPos(pos + heading * 8)
ent:SetAngles(VectorRand():Angle())
ent:Spawn()
local phys = ent:GetPhysicsObject()
if phys:IsValid() then
phys:ApplyForceOffset(heading * math.Rand(8000, 32000), pos)
end
end
end
end
end
local tempknockback
function ENT:StartBulletKnockback()
tempknockback = {}
end
function ENT:EndBulletKnockback()
tempknockback = nil
end
function ENT:DoBulletKnockback(scale)
for ent, prevvel in pairs(tempknockback) do
local curvel = ent:GetVelocity()
ent:SetVelocity(curvel * -1 + (curvel - prevvel) * scale + prevvel)
end
end
local function BulletCallback(attacker, tr, dmginfo)
local ent = tr.Entity
if ent:IsValid() then
if ent:IsPlayer() then
if ent:Team() == TEAM_UNDEAD and tempknockback then
if attacker:GetTarget() == ent then
attacker.LastHitSomething = CurTime()
end
tempknockback[ent] = ent:GetVelocity()
end
else
local phys = ent:GetPhysicsObject()
if ent:GetMoveType() == MOVETYPE_VPHYSICS and phys:IsValid() and phys:IsMoveable() then
ent:SetPhysicsAttacker(attacker)
end
end
dmginfo:SetAttacker(attacker:GetObjectOwner())
dmginfo:SetInflictor(attacker)
end
end
function ENT:FireTurret(src, dir)
if self:GetNextFire() <= CurTime() then
local curammo = self:GetAmmo()
if curammo > 0 then
self:SetNextFire(CurTime() + 0.05)
self:SetAmmo(curammo - 1)
self:StartBulletKnockback()
self:FireBullets({Num = 1, Src = src, Dir = dir, Spread = Vector(0.05, 0.05, 0), Tracer = 1, Force = 1, Damage = 4, Callback = BulletCallback})
self:DoBulletKnockback(0.05)
self:EndBulletKnockback()
else
self:SetNextFire(CurTime() + 2)
self:EmitSound("npc/turret_floor/die.wav")
end
end
end
function ENT:Think()
if self.Destroyed then
self:Remove()
return
end
self:CalculatePoseAngles()
local owner = self:GetObjectOwner()
if owner:IsValid() and self:GetAmmo() > 0 and self:GetMaterial() == "" then
if self:GetManualControl() then
if owner:KeyDown(IN_ATTACK) then
if not self:IsFiring() then self:SetFiring(true) end
self:FireTurret(self:ShootPos(), self:GetGunAngles():Forward())
elseif self:IsFiring() then
self:SetFiring(false)
end
local target = self:GetTarget()
if target:IsValid() then self:ClearTarget() end
else
if self:IsFiring() then self:SetFiring(false) end
local target = self:GetTarget()
if target:IsValid() then
if self:IsValidTarget(target) and CurTime() < self.LastHitSomething + 0.5 then
local shootpos = self:ShootPos()
self:FireTurret(shootpos, (self:GetTargetPos(target) - shootpos):GetNormalized())
else
self:ClearTarget()
--self:EmitSound("npc/turret_floor/deploy.wav")
self:EmitSound("NPC_FloorTurret.Ping")
end
else
local target = self:SearchForTarget()
if target then
self:SetTarget(target)
self:SetTargetReceived(CurTime())
self:EmitSound("npc/turret_floor/active.wav")
--self:EmitSound("NPC_FloorTurret.Ping")
end
end
end
elseif self:IsFiring() then
self:SetFiring(false)
end
self:NextThink(CurTime())
return true
end
function ENT:Use(activator, caller)
if self.Removing or not activator:IsPlayer() or self:GetMaterial() ~= "" then return end
if activator:Team() == TEAM_HUMAN then
if self:GetObjectOwner():IsValid() then
local curammo = self:GetAmmo()
local togive = math.min(math.min(15, activator:GetAmmoCount("smg1")), self.MaxAmmo - curammo)
if togive > 0 then
self:SetAmmo(curammo + togive)
activator:RemoveAmmo(togive, "smg1")
activator:RestartGesture(ACT_GMOD_GESTURE_ITEM_GIVE)
self:EmitSound("npc/turret_floor/click1.wav")
gamemode.Call("PlayerRepairedObject", activator, self, togive * 1.5, self)
end
else
self:SetObjectOwner(activator)
if not activator:HasWeapon("weapon_zs_gunturretcontrol") then
activator:Give("weapon_zs_gunturretcontrol")
end
end
end
end
function ENT:AltUse(activator, tr)
self:PackUp(activator)
end
function ENT:OnPackedUp(pl)
pl:GiveEmptyWeapon("weapon_zs_gunturret")
pl:GiveAmmo(1, "thumper")
pl:PushPackedItem(self:GetClass(), self:GetObjectHealth(), self:GetAmmo())
self:Remove()
end
function ENT:OnTakeDamage(dmginfo)
self:TakePhysicsDamage(dmginfo)
local attacker = dmginfo:GetAttacker()
if not (attacker:IsValid() and attacker:IsPlayer() and attacker:Team() == TEAM_HUMAN) then
self:ResetLastBarricadeAttacker(attacker, dmginfo)
self:SetObjectHealth(self:GetObjectHealth() - dmginfo:GetDamage())
end
end
|
gpl-2.0
|
izrik/tudor
|
tests/persistence_t/in_memory/layer/test_internals_2.py
|
7561
|
from models.object_types import ObjectTypes
from tests.persistence_t.in_memory.in_memory_test_base import InMemoryTestBase
# not copied from any other file
class GetObjectTypeTest(InMemoryTestBase):
def setUp(self):
self.pl = self.generate_pl()
self.pl.create_all()
def test_get_object_type_task_returns_task(self):
# given
task = self.pl.create_task('task1')
# when
result = self.pl._get_object_type(task)
# then
self.assertEqual(ObjectTypes.Task, result)
def test_get_object_type_tag_returns_tag(self):
# given
tag = self.pl.create_tag('tag1')
# when
result = self.pl._get_object_type(tag)
# then
self.assertEqual(ObjectTypes.Tag, result)
def test_get_object_type_attachment_returns_attachment(self):
# given
attachment = self.pl.create_attachment('attachment1')
# when
result = self.pl._get_object_type(attachment)
# then
self.assertEqual(ObjectTypes.Attachment, result)
def test_get_object_type_note_returns_note(self):
# given
note = self.pl.create_note('note1')
# when
result = self.pl._get_object_type(note)
# then
self.assertEqual(ObjectTypes.Note, result)
def test_get_object_type_user_returns_user(self):
# given
user = self.pl.create_user('user1')
# when
result = self.pl._get_object_type(user)
# then
self.assertEqual(ObjectTypes.User, result)
def test_get_object_type_option_returns_option(self):
# given
option = self.pl.create_option('key', 'value')
# when
result = self.pl._get_object_type(option)
# then
self.assertEqual(ObjectTypes.Option, result)
def test_get_object_type_non_domain_object_raises(self):
# expect
with self.assertRaises(Exception) as cm:
self.pl._get_object_type('something')
# then
self.assertEqual('Not a domain object: something, str',
str(cm.exception))
class GetNextObjectIdsTest(InMemoryTestBase):
def setUp(self):
self.pl = self.generate_pl()
self.pl.create_all()
def test_get_next_task_id_no_tasks_returns_one(self):
# precondition
self.assertEqual(0, len(self.pl._tasks))
# when
result = self.pl._get_next_task_id()
# then
self.assertEqual(1, result)
def test_get_next_task_id_some_tasks_returns_max_plus_one(self):
# given
task = self.pl.create_task('task')
task.id = 3
self.pl.add(task)
self.pl.commit()
# precondition
self.assertEqual(1, len(self.pl._tasks))
self.assertEqual(3, self.pl._tasks[0].id)
# when
result = self.pl._get_next_task_id()
# then
self.assertEqual(4, result)
def test_get_next_tag_id_no_tags_returns_one(self):
# precondition
self.assertEqual(0, len(self.pl._tags))
# when
result = self.pl._get_next_tag_id()
# then
self.assertEqual(1, result)
def test_get_next_tag_id_some_tags_returns_max_plus_one(self):
# given
tag = self.pl.create_tag('tag')
tag.id = 3
self.pl.add(tag)
self.pl.commit()
# precondition
self.assertEqual(1, len(self.pl._tags))
self.assertEqual(3, self.pl._tags[0].id)
# when
result = self.pl._get_next_tag_id()
# then
self.assertEqual(4, result)
def test_get_next_attachment_id_no_attachments_returns_one(self):
# precondition
self.assertEqual(0, len(self.pl._attachments))
# when
result = self.pl._get_next_attachment_id()
# then
self.assertEqual(1, result)
def test_get_next_attachment_id_some_attachments_return_max_plus_one(self):
# given
attachment = self.pl.create_attachment('attachment')
attachment.id = 3
self.pl.add(attachment)
self.pl.commit()
# precondition
self.assertEqual(1, len(self.pl._attachments))
self.assertEqual(3, self.pl._attachments[0].id)
# when
result = self.pl._get_next_attachment_id()
# then
self.assertEqual(4, result)
def test_get_next_note_id_no_notes_returns_one(self):
# precondition
self.assertEqual(0, len(self.pl._notes))
# when
result = self.pl._get_next_note_id()
# then
self.assertEqual(1, result)
def test_get_next_note_id_some_notes_returns_max_plus_one(self):
# given
note = self.pl.create_note('note')
note.id = 3
self.pl.add(note)
self.pl.commit()
# precondition
self.assertEqual(1, len(self.pl._notes))
self.assertEqual(3, self.pl._notes[0].id)
# when
result = self.pl._get_next_note_id()
# then
self.assertEqual(4, result)
def test_get_next_user_id_no_users_returns_one(self):
# precondition
self.assertEqual(0, len(self.pl._users))
# when
result = self.pl._get_next_user_id()
# then
self.assertEqual(1, result)
def test_get_next_user_id_some_users_returns_max_plus_one(self):
# given
user = self.pl.create_user('user')
user.id = 3
self.pl.add(user)
self.pl.commit()
# precondition
self.assertEqual(1, len(self.pl._users))
self.assertEqual(3, self.pl._users[0].id)
# when
result = self.pl._get_next_user_id()
# then
self.assertEqual(4, result)
class GetNextIdTest(InMemoryTestBase):
def setUp(self):
self.pl = self.generate_pl()
self.pl.create_all()
task = self.pl.create_task('task')
task.id = 3
self.pl.add(task)
tag = self.pl.create_tag('tag')
tag.id = 5
self.pl.add(tag)
attachment = self.pl.create_attachment('attachment')
attachment.id = 7
self.pl.add(attachment)
note = self.pl.create_note('note')
note.id = 9
self.pl.add(note)
user = self.pl.create_user('user')
user.id = 11
self.pl.add(user)
self.pl.commit()
def test_get_next_id_task_returns_max_task_id_plus_one(self):
# when
result = self.pl._get_next_id(ObjectTypes.Task)
# then
self.assertEqual(4, result)
def test_get_next_id_tag_returns_max_tag_id_plus_one(self):
# when
result = self.pl._get_next_id(ObjectTypes.Tag)
# then
self.assertEqual(6, result)
def test_get_next_id_attachment_returns_max_attachment_id_plus_one(self):
# when
result = self.pl._get_next_id(ObjectTypes.Attachment)
# then
self.assertEqual(8, result)
def test_get_next_id_note_returns_max_note_id_plus_one(self):
# when
result = self.pl._get_next_id(ObjectTypes.Note)
# then
self.assertEqual(10, result)
def test_get_next_id_user_returns_max_user_id_plus_one(self):
# when
result = self.pl._get_next_id(ObjectTypes.User)
# then
self.assertEqual(12, result)
def test_get_next_id_non_domain_object_raises(self):
# expect
with self.assertRaises(Exception) as cm:
self.pl._get_next_id(str)
# then
self.assertEqual('Unknown object type: <class \'str\'>',
str(cm.exception))
|
gpl-2.0
|
jhemsley30/redtruck.com
|
sites/all/themes/zen/ashly/templates/html--node--2.tpl.php
|
2279
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>
<head profile="<?php print $grddl_profile; ?>">
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $scripts; ?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<!------------------------------------ ------------- fancybox ---------------------------------------------------->
<!-- Add mousewheel plugin (this is optional) -->
<script type="text/javascript" src="http://www.setdesign-la.com/jh-scripts/ashlyFancybox/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="http://www.setdesign-la.com/jh-scripts/ashlyFancybox/source/jquery.fancybox.css?v=2.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="http://www.setdesign-la.com/jh-scripts/ashlyFancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
<!-- Optionally add button and/or thumbnail helpers -->
<link rel="stylesheet" href="http://www.setdesign-la.com/jh-scripts/ashlyFancybox/source/helpers/jquery.fancybox-buttons.css?v=2.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="http://www.setdesign-la.com/jh-scripts/ashlyFancybox/source/helpers/jquery.fancybox-buttons.js?v=2.0.5"></script>
<link rel="stylesheet" href="http://www.setdesign-la.com/jh-scripts/ashlyFancybox/source/helpers/jquery.fancybox-thumbs.css?v=2.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="http://www.setdesign-la.com/jh-scripts/ashlyFancybox/source/helpers/jquery.fancybox-thumbs.js?v=2.0.5"></script>
<!---------------------------------------------- END FANCYBOX ---------------------------------------------------------------->
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
<div id="skip-link">
</div>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $page_bottom; ?>
</body>
</html>
|
gpl-2.0
|
joshdrummond/chinese-polar-races
|
src/com/joshdrummond/cpr/CPR.java
|
3289
|
package com.joshdrummond.cpr;
/*
Chinese Polar Races
Josh Drummond
Fall of '99
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class CPR
extends Applet
// implements FocusListener
{
private Button btnPlay;
private Button btnReview;
private Button btnAbout;
private CPRTitleCanvas canTitle;
private CPRImageCanvas canGraphic;
public static CPRVocab words;
public static Applet app;
public void init()
{
System.out.println("-------------------------------------------------");
System.out.println("Starting Chinese Polar Races...");
System.out.println("Version number: 2.8");
System.out.println("Version date: 6/25/2000");
System.out.println("(c)1999-2000 Josh Drummond");
System.out.println("-------------------------------------------------");
this.app = this;
canTitle = new CPRTitleCanvas("Chinese Polar Races!", new Font("TimesRoman",
Font.BOLD, 48), Color.white);
canGraphic = new CPRImageCanvas(
CPRResourceLoader.getImage("/back1.jpg", this),
//getImage(getDocumentBase(), "back1.jpg"),
350, 350);
btnPlay = new Button(" Play ");
btnPlay.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
doPlay();
}
});
btnReview = new Button(" Practice ");
btnReview.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
doReview();
}
});
btnAbout = new Button(" About ");
btnAbout.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
doAbout();
}
});
// btnAbout.addFocusListener(this);
// btnReview.addFocusListener(this);
// btnPlay.addFocusListener(this);
drawScreen();
}
/* public void focusGained(FocusEvent e)
{
System.out.println("focus gained");
canTitle.stop();
}
public void focusLost(FocusEvent e)
{
System.out.println("focus lost");
canTitle.start();
}
*/
private void drawScreen()
{
this.setBackground(Color.black);
this.setLayout(new BorderLayout());
btnPlay.setBackground(Color.white);
btnPlay.setFont(new Font("Serif", Font.BOLD, 18));
btnReview.setBackground(Color.white);
btnReview.setFont(new Font("Serif", Font.BOLD, 18));
btnAbout.setBackground(Color.white);
btnAbout.setFont(new Font("Serif", Font.BOLD, 18));
Panel panBot = new Panel();
panBot.add(btnPlay);
panBot.add(btnReview);
panBot.add(btnAbout);
this.add(canTitle, "North");
this.add(canGraphic, "Center");
this.add(panBot, "South");
}
private void doPlay()
{
new CPRGameFrame();
}
private void doAbout()
{
new CPRAboutFrame();
}
private void doReview()
{
new CPRReviewFrame();
}
}
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.