repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
EldadDor/AnnoRefPlugin
|
src/main/java/com/idi/intellij/plugin/query/annoref/lang/AnnoRefHighlightingAnnotator.java
|
6610
|
/*
* User: eldad.Dor
* Date: 16/02/14 10:42
*
* Copyright (2005) IDI. All rights reserved.
* This software is a proprietary information of Israeli Direct Insurance.
* Created by IntelliJ IDEA.
*/
package com.idi.intellij.plugin.query.annoref.lang;
import com.google.common.collect.Lists;
import com.idi.intellij.plugin.query.annoref.persist.AnnoRefConfigSettings;
import com.idi.intellij.plugin.query.annoref.util.SQLRefNamingUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.find.FindManager;
import com.intellij.find.FindModel;
import com.intellij.ide.IdeEventQueue;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.*;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.*;
import com.intellij.ui.JBColor;
import com.siyeh.InspectionGadgetsBundle;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.List;
/**
* @author eldad
* @date 16/02/14
* Not really using it but is running...
*/
public class AnnoRefHighlightingAnnotator implements Annotator {
private static final Logger LOGGER = Logger.getInstance(AnnoRefHighlightingAnnotator.class.getName());
private static void annotate(PsiElement element, TextAttributesKey key, AnnotationHolder holder) {
if (element != null) {
holder.createInfoAnnotation(element, null).setTextAttributes(key);
}
}
/* if (psiElement.getNode().getElementType() instanceof SqlTokenType && (psiElement.getContainingFile() != null && psiElement.getContainingFile() instanceof SqlFile)) {
final SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(SybaseDialect.INSTANCE, psiElement.getProject(), SQLRefApplication.getVirtualFileFromPsiFile(psiElement.getContainingFile(), psiElement.getProject()));
}*/
private static void highlightElements(@NotNull final List<PsiElement> elementCollection) {
if (elementCollection.isEmpty()) {
return;
}
IdeEventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final PsiElement[] elements = elementCollection.toArray(new PsiElement[elementCollection.size()]);
final Project project = elements[0].getProject();
final FileEditorManager editorManager = FileEditorManager.getInstance(project);
final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance();
final Editor editor = editorManager.getSelectedTextEditor();
if (editor == null) {
return;
}
final EditorColorsScheme globalScheme = editorColorsManager.getGlobalScheme();
final TextAttributes textattributes = globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
final HighlightManager highlightManager = HighlightManager.getInstance(project);
highlightManager.addOccurrenceHighlights(editor, elements, textattributes, true, null);
// highlightManager.addOccurrenceHighlights(editor, elements, null, true, null);
final WindowManager windowManager = WindowManager.getInstance();
final StatusBar statusBar = windowManager.getStatusBar(project);
statusBar.setInfo(InspectionGadgetsBundle.message("press.escape.to.remove.highlighting.message"));
final FindManager findmanager = FindManager.getInstance(project);
FindModel findmodel = findmanager.getFindNextModel();
if (findmodel == null) {
findmodel = findmanager.getFindInFileModel();
}
findmodel.setSearchHighlighters(true);
findmanager.setFindWasPerformed();
findmanager.setFindNextModel(findmodel);
}
});
}
public static void main(String[] args) {
int hex = 0x5151255;
int r = (hex & 0xFF0000) >> 16;
int g = (hex & 0xFF00) >> 8;
int b = (hex & 0xFF);
final String toHexString = org.jdesktop.swingx.color.ColorUtil.toHexString(Color.RED);
final Color decode = Color.decode("51-51-255");
}
@Override
public void annotate(@NotNull PsiElement psiElement, @NotNull AnnotationHolder annotationHolder) {
final PsiAnnotation psiAnnotation = SQLRefNamingUtil.isAnnoRefAnnotationValid(psiElement);
if (psiAnnotation != null) {
for (final PsiNameValuePair nameValuePair : psiAnnotation.getParameterList().getAttributes()) {
// if (nameValuePair.getName().equals(AnnoRefConfigSettings.getInstance(psiElement.getProject()).getAnnoRefState().ANNOREF_ANNOTATION_ATTRIBUTE_ID)) {
final PsiAnnotationMemberValue value = nameValuePair.getValue();
TextAttributesKey ATTRIBUTE_VALUE_KEY = TextAttributesKey.createTextAttributesKey("annoRef.attributeValue", DefaultLanguageHighlighterColors.STRING);
if (!AnnoRefConfigSettings.getInstance(psiElement.getProject()).getAnnoRefState().ANNO_ALL_SYNTAX_HIGHLIGHT_COLOR.isEmpty()) {
final Color decode = Color.decode(AnnoRefConfigSettings.getInstance(psiElement.getProject()).getAnnoRefState().ANNO_ALL_SYNTAX_HIGHLIGHT_COLOR);
JBColor annoSyntaxColor = new JBColor(decode, decode);
ATTRIBUTE_VALUE_KEY.getDefaultAttributes().setForegroundColor(annoSyntaxColor);
}
// final TextAttributesKey ATTRIBUTE_VALUE_KEY = TextAttributesKey.createTextAttributesKey("annoRef.attributeValue", DefaultLanguageHighlighterColors.STRING);
// ATTRIBUTE_VALUE_KEY.getDefaultAttributes().setForegroundColor(DefaultLanguageHighlighterColors.STRING.getDefaultAttributes().getForegroundColor().darker());
// final JBColor foregroundColor = new JBColor(new Color(255, 255, 0), new Color(100, 28, 0));
final ColorKey colorKey = EditorColors.MODIFIED_LINES_COLOR;
// final JBColor backgroundColor = new JBColor(new Color(71, 143, 36), Gray._0);
// ATTRIBUTE_VALUE_KEY.getDefaultAttributes().setForegroundColor(foregroundColor);
annotate(value, ATTRIBUTE_VALUE_KEY, annotationHolder);
final List<PsiElement> list = Lists.newArrayList();
list.add(value);
highlightElements(list);
return;
// }
}
}
}
private boolean isValidElement(PsiElement psiElement) {
return psiElement instanceof PsiModifierListOwner
&& ((PsiModifierListOwner) psiElement).getModifierList() != null
&& ((PsiModifierListOwner) psiElement).getModifierList().getAnnotations() != null
&& ((PsiModifierListOwner) psiElement).getModifierList().getAnnotations().length > 0;
}
}
|
gpl-2.0
|
l4ka/idl4
|
src/be/ops/alloc.cc
|
1111
|
#include "ops.h"
#define dprintln(a...) do { if (debug_mode&DEBUG_MARSHAL) println(a); } while (0)
CBEOpAllocOnServer::CBEOpAllocOnServer(CMSConnection *connection, CBEType *type, CBEParameter *param, int flags) : CBEMarshalOp(connection, 0, NULL, param, flags)
{
this->type = type;
this->tempVar = NULL;
}
void CBEOpAllocOnServer::buildServerDeclarations(CBEVarSource *varSource)
{
tempVar = varSource->requestVariable(true, type);
}
CASTExpression *CBEOpAllocOnServer::buildServerArg(CBEParameter *param)
{
return tempVar;
}
void CBEOpAllocOnServer::buildClientDeclarations(CBEVarSource *varSource)
{
}
CASTStatement *CBEOpAllocOnServer::buildClientMarshal()
{
return NULL;
}
CASTStatement *CBEOpAllocOnServer::buildClientUnmarshal()
{
return NULL;
}
CASTStatement *CBEOpAllocOnServer::buildServerUnmarshal()
{
return NULL;
}
CASTStatement *CBEOpAllocOnServer::buildServerMarshal()
{
return NULL;
}
CASTStatement *CBEOpAllocOnServer::buildServerReplyMarshal()
{
return NULL;
}
void CBEOpAllocOnServer::buildServerReplyDeclarations(CBEVarSource *varSource)
{
}
|
gpl-2.0
|
BisongT/Myevent_website
|
wp-content/themes/Basetheme/post-types/action-post-type-occasions.php
|
3996
|
<?php
// Register Custom taxonomy
function Occasion_items() {
$labels = array(
'name' => 'myoccasions',
'singular_name' => 'myoccasion',
'menu_name' => 'Myoccasions',
'parent_item' => 'parent_item',
'parent_item_colon' => 'Parent Item:',
'all_items' => 'All myoccasions',
'add_new_item' => 'Add New Occasion',
'add_new' => 'Add New',
'new_item' => 'New Item',
'edit_item' => 'Edit Item',
'update_item' => 'Update Item',
'view_item' => 'View Item',
'search_items' => 'Search Item',
'separate_items_with_commas' => 'Separate items with commas',
'add_or_remove_items' => 'Add or remove items',
'choose_from_most_used' => 'Choose from the most used',
'popular_items' => 'Popular Items',
'search_items' => 'Search Items',
'not_found' => 'Not Found',
);
$args = array(
'label' => __( 'Myoccasion', 'text_domain' ),
'description' => __( 'Post Type Description', 'text_domain' ),
'labels' => $labels,
'supports' => array( ),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-nametag',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_taxonomy( 'myoccasions', array( '' ), $args );
}
add_action( 'init', 'Occasion_items', 0 );
// Register Custom Post Type
function News_Occasions() {
$labels = array(
'name' => _x( 'News & Occasions', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'News & Occasion', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'News & Occasions', 'text_domain' ),
'name_admin_bar' => __( 'Occasion Mgt', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All News & occasions', 'text_domain' ),
'add_new_item' => __( 'Add News & Occasion', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New News & Occasion', 'text_domain' ),
'edit_item' => __( 'Edit News & Occasion', 'text_domain' ),
'update_item' => __( 'Update News & Occasion', 'text_domain' ),
'view_item' => __( 'View News & Occasion', 'text_domain' ),
'search_items' => __( 'Search News & Occasions', 'text_domain' ),
'not_found' => __( 'News & Occasions Not found', 'text_domain' ),
'not_found_in_trash' => __( 'News & Occasions Not found in Trash', 'text_domain' ),
);
$args = array(
'label' => __( 'Occasion', 'text_domain' ),
'description' => __( 'Post Type Description', 'text_domain' ),
'labels' => $labels,
'supports' => array('title','editor','thumbnail' ),
'taxonomies' => array( 'myoccasions' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-nametag',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'occasions', $args );
}
//Hook into the 'init' action
add_action( 'init', 'News_Occasions', 0 );
|
gpl-2.0
|
thepixture/html5data
|
languages/de/tl_article.php
|
340
|
<?php
$GLOBALS['TL_LANG']['tl_article']['html5data'][0] = 'HTML5 Data-Attribut';
$GLOBALS['TL_LANG']['tl_article']['html5data'][1] = 'Geben Sie einen Namen (ohne data-) und einen Wert ein.';
$GLOBALS['TL_LANG']['tl_article']['html5data_attribute_name'] = 'Name';
$GLOBALS['TL_LANG']['tl_article']['html5data_attribute_value'] = 'Wert';
|
gpl-2.0
|
liquidmetal/bananaman
|
jni/gfx/bullet/btMinkowskiPenetrationDepthSolver.cpp
|
12026
|
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btMinkowskiPenetrationDepthSolver.h"
#include "btSubSimplexConvexCast.h"
#include "btVoronoiSimplexSolver.h"
#include "btGjkPairDetector.h"
#include "btConvexShape.h"
#define NUM_UNITSPHERE_POINTS 42
bool btMinkowskiPenetrationDepthSolver::calcPenDepth(btSimplexSolverInterface& simplexSolver,
const btConvexShape* convexA,const btConvexShape* convexB,
const btTransform& transA,const btTransform& transB,
btVector3& v, btVector3& pa, btVector3& pb,
class btIDebugDraw* debugDraw,btStackAlloc* stackAlloc
)
{
(void)stackAlloc;
(void)v;
bool check2d= convexA->isConvex2d() && convexB->isConvex2d();
struct btIntermediateResult : public btDiscreteCollisionDetectorInterface::Result
{
btIntermediateResult():m_hasResult(false)
{
}
btVector3 m_normalOnBInWorld;
btVector3 m_pointInWorld;
btScalar m_depth;
bool m_hasResult;
virtual void setShapeIdentifiersA(int partId0,int index0)
{
(void)partId0;
(void)index0;
}
virtual void setShapeIdentifiersB(int partId1,int index1)
{
(void)partId1;
(void)index1;
}
void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)
{
m_normalOnBInWorld = normalOnBInWorld;
m_pointInWorld = pointInWorld;
m_depth = depth;
m_hasResult = true;
}
};
//just take fixed number of orientation, and sample the penetration depth in that direction
btScalar minProj = btScalar(BT_LARGE_FLOAT);
btVector3 minNorm(btScalar(0.), btScalar(0.), btScalar(0.));
btVector3 minA,minB;
btVector3 seperatingAxisInA,seperatingAxisInB;
btVector3 pInA,qInB,pWorld,qWorld,w;
#ifndef __SPU__
#define USE_BATCHED_SUPPORT 1
#endif
#ifdef USE_BATCHED_SUPPORT
btVector3 supportVerticesABatch[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2];
btVector3 supportVerticesBBatch[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2];
btVector3 seperatingAxisInABatch[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2];
btVector3 seperatingAxisInBBatch[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2];
int i;
int numSampleDirections = NUM_UNITSPHERE_POINTS;
for (i=0;i<numSampleDirections;i++)
{
btVector3 norm = getPenetrationDirections()[i];
seperatingAxisInABatch[i] = (-norm) * transA.getBasis() ;
seperatingAxisInBBatch[i] = norm * transB.getBasis() ;
}
{
int numPDA = convexA->getNumPreferredPenetrationDirections();
if (numPDA)
{
for (int i=0;i<numPDA;i++)
{
btVector3 norm;
convexA->getPreferredPenetrationDirection(i,norm);
norm = transA.getBasis() * norm;
getPenetrationDirections()[numSampleDirections] = norm;
seperatingAxisInABatch[numSampleDirections] = (-norm) * transA.getBasis();
seperatingAxisInBBatch[numSampleDirections] = norm * transB.getBasis();
numSampleDirections++;
}
}
}
{
int numPDB = convexB->getNumPreferredPenetrationDirections();
if (numPDB)
{
for (int i=0;i<numPDB;i++)
{
btVector3 norm;
convexB->getPreferredPenetrationDirection(i,norm);
norm = transB.getBasis() * norm;
getPenetrationDirections()[numSampleDirections] = norm;
seperatingAxisInABatch[numSampleDirections] = (-norm) * transA.getBasis();
seperatingAxisInBBatch[numSampleDirections] = norm * transB.getBasis();
numSampleDirections++;
}
}
}
convexA->batchedUnitVectorGetSupportingVertexWithoutMargin(seperatingAxisInABatch,supportVerticesABatch,numSampleDirections);
convexB->batchedUnitVectorGetSupportingVertexWithoutMargin(seperatingAxisInBBatch,supportVerticesBBatch,numSampleDirections);
for (i=0;i<numSampleDirections;i++)
{
btVector3 norm = getPenetrationDirections()[i];
if (check2d)
{
norm[2] = 0.f;
}
if (norm.length2()>0.01)
{
seperatingAxisInA = seperatingAxisInABatch[i];
seperatingAxisInB = seperatingAxisInBBatch[i];
pInA = supportVerticesABatch[i];
qInB = supportVerticesBBatch[i];
pWorld = transA(pInA);
qWorld = transB(qInB);
if (check2d)
{
pWorld[2] = 0.f;
qWorld[2] = 0.f;
}
w = qWorld - pWorld;
btScalar delta = norm.dot(w);
//find smallest delta
if (delta < minProj)
{
minProj = delta;
minNorm = norm;
minA = pWorld;
minB = qWorld;
}
}
}
#else
int numSampleDirections = NUM_UNITSPHERE_POINTS;
#ifndef __SPU__
{
int numPDA = convexA->getNumPreferredPenetrationDirections();
if (numPDA)
{
for (int i=0;i<numPDA;i++)
{
btVector3 norm;
convexA->getPreferredPenetrationDirection(i,norm);
norm = transA.getBasis() * norm;
getPenetrationDirections()[numSampleDirections] = norm;
numSampleDirections++;
}
}
}
{
int numPDB = convexB->getNumPreferredPenetrationDirections();
if (numPDB)
{
for (int i=0;i<numPDB;i++)
{
btVector3 norm;
convexB->getPreferredPenetrationDirection(i,norm);
norm = transB.getBasis() * norm;
getPenetrationDirections()[numSampleDirections] = norm;
numSampleDirections++;
}
}
}
#endif // __SPU__
for (int i=0;i<numSampleDirections;i++)
{
const btVector3& norm = getPenetrationDirections()[i];
seperatingAxisInA = (-norm)* transA.getBasis();
seperatingAxisInB = norm* transB.getBasis();
pInA = convexA->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInA);
qInB = convexB->localGetSupportVertexWithoutMarginNonVirtual(seperatingAxisInB);
pWorld = transA(pInA);
qWorld = transB(qInB);
w = qWorld - pWorld;
btScalar delta = norm.dot(w);
//find smallest delta
if (delta < minProj)
{
minProj = delta;
minNorm = norm;
minA = pWorld;
minB = qWorld;
}
}
#endif //USE_BATCHED_SUPPORT
//add the margins
minA += minNorm*convexA->getMarginNonVirtual();
minB -= minNorm*convexB->getMarginNonVirtual();
//no penetration
if (minProj < btScalar(0.))
return false;
btScalar extraSeparation = 0.5f;///scale dependent
minProj += extraSeparation+(convexA->getMarginNonVirtual() + convexB->getMarginNonVirtual());
//#define DEBUG_DRAW 1
#ifdef DEBUG_DRAW
if (debugDraw)
{
btVector3 color(0,1,0);
debugDraw->drawLine(minA,minB,color);
color = btVector3 (1,1,1);
btVector3 vec = minB-minA;
btScalar prj2 = minNorm.dot(vec);
debugDraw->drawLine(minA,minA+(minNorm*minProj),color);
}
#endif //DEBUG_DRAW
btGjkPairDetector gjkdet(convexA,convexB,&simplexSolver,0);
btScalar offsetDist = minProj;
btVector3 offset = minNorm * offsetDist;
btGjkPairDetector::ClosestPointInput input;
btVector3 newOrg = transA.getOrigin() + offset;
btTransform displacedTrans = transA;
displacedTrans.setOrigin(newOrg);
input.m_transformA = displacedTrans;
input.m_transformB = transB;
input.m_maximumDistanceSquared = btScalar(BT_LARGE_FLOAT);//minProj;
btIntermediateResult res;
gjkdet.setCachedSeperatingAxis(-minNorm);
gjkdet.getClosestPoints(input,res,debugDraw);
btScalar correctedMinNorm = minProj - res.m_depth;
//the penetration depth is over-estimated, relax it
btScalar penetration_relaxation= btScalar(1.);
minNorm*=penetration_relaxation;
if (res.m_hasResult)
{
pa = res.m_pointInWorld - minNorm * correctedMinNorm;
pb = res.m_pointInWorld;
v = minNorm;
#ifdef DEBUG_DRAW
if (debugDraw)
{
btVector3 color(1,0,0);
debugDraw->drawLine(pa,pb,color);
}
#endif//DEBUG_DRAW
}
return res.m_hasResult;
}
btVector3* btMinkowskiPenetrationDepthSolver::getPenetrationDirections()
{
static btVector3 sPenetrationDirections[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] =
{
btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)),
btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)),
btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)),
btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)),
btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)),
btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)),
btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)),
btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)),
btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)),
btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)),
btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)),
btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)),
btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)),
btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)),
btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)),
btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)),
btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)),
btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)),
btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)),
btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)),
btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)),
btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)),
btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)),
btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)),
btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)),
btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)),
btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)),
btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)),
btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)),
btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)),
btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)),
btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)),
btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)),
btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)),
btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)),
btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)),
btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)),
btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)),
btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)),
btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)),
btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)),
btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654))
};
return sPenetrationDirections;
}
|
gpl-2.0
|
dj6/funbreak
|
app.js
|
2017
|
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var morgan =require('morgan');//express.logger
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var http = require('http');
var cheerio = require('cheerio');
var port = process.env.PORT || 3000;
var app = express();
var dbUrl = 'mongodb://localhost/imovie';
mongoose.connect(dbUrl);
app.locals.moment = require("moment");
app.set('views', './app/views/pages');
app.set('view engine', 'jade');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));//把post请求变为对象
app.use(cookieParser());
app.use(session({
secret : 'imovie',
store: new mongoStore({
url: dbUrl,
collection: 'sessions'
}),
resave: false,
saveUninitialized: true
}));
if('development' === app.get('env')){ //根据不同情境有不同处理
app.set('showStackError',true); //显示报错
app.use(morgan('tiny')); //设置报错格式
app.locals.pretty = true; //设置代码缩进
}
require('./config/routes')(app);
// parse application/json
app.use(bodyParser.json());
var staticDir = __dirname;
app.use(express.static(path.join(staticDir,'public'))); //其他文件引用js文件、lib文件的根目录
//app.use(express.static(__dirname.join('public')));
app.listen(port);
console.log("current dir "+ __dirname);
console.log('ok '+port);
// http.get('http://v.163.com/movie/2015/1/U/7/MAFVGR8PR_MAFVL3AU7.html',function(res){
// var data="";
// //console.log('in');
// res.on('data',function(chunk){
// data += chunk;
// //console.log(chunk);
// });
// res.on('end',function(){
// console.log('get data');
// var $ = cheerio.load(data);
// console.log('yes!');
// $("script").each(function(i,e){
// console.log(i);
// console.log($(this).html());
// });
// });
// //console.log(data);
// });
|
gpl-2.0
|
ZDteam/emil
|
components/com_easyblog/themes/default/blog.categories.php
|
8817
|
<?php
/**
* @package EasyBlog
* @copyright Copyright (C) 2010 Stack Ideas Private Limited. All rights reserved.
* @license GNU/GPL, see LICENSE.php
*
* EasyBlog is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
defined('_JEXEC') or die('Restricted access');
$mainframe = JFactory::getApplication();
?>
<div id="ezblog-body">
<div id="ezblog-section"><?php echo JText::_('COM_EASYBLOG_CATEGORIES_PAGE_HEADING'); ?></div>
<div id="ezblog-category">
<?php foreach($data as $category) { ?>
<div class="profile-item clearfix">
<div class="profile-head">
<?php if($system->config->get('layout_categoryavatar', true)) : ?>
<div class="profile-avatar float-l">
<i class="pabs"></i>
<a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=categories&layout=listings&id='.$category->id); ?>" class="avatar">
<img src="<?php echo $category->avatar;?>" align="top" width="50" class="avatar" />
</a>
</div><!--end: .profile-avatar-->
<?php endif; ?>
<div class="profile-info">
<h3 class="profile-title rip"><a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=categories&layout=listings&id='.$category->id); ?>"><?php echo JText::_( $category->title ); ?></a></h3>
<?php if ( $category->description ) { ?>
<div class="profile-info mts">
<?php echo $category->description; ?>
</div>
<?php } ?>
<div class="profile-connect mts pbs">
<ul class="connect-links reset-ul float-li">
<?php if($system->config->get('main_categorysubscription')) { ?>
<?php if( ($category->private && $system->my->id != 0 ) || ($system->my->id == 0 && $system->config->get( 'main_allowguestsubscribe' )) || $system->my->id != 0) : ?>
<li>
<a href="javascript:eblog.subscription.show( '<?php echo EBLOG_SUBSCRIPTION_CATEGORY; ?>' , '<?php echo $category->id;?>');" title="<?php echo JText::_('COM_EASYBLOG_SUBSCRIPTION_SUBSCRIBE_CATEGORY'); ?>" class="link-subscribe">
<span><?php echo JText::_('COM_EASYBLOG_SUBSCRIPTION_SUBSCRIBE_CATEGORY'); ?></span>
</a>
</li>
<?php endif; ?>
<?php } ?>
<?php if( $system->config->get('main_rss') ){ ?>
<li>
<a href="<?php echo $category->rssLink;?>" title="<?php echo JText::_('COM_EASYBLOG_SUBSCRIBE_FEEDS'); ?>" class="link-rss">
<span><?php echo JText::_('COM_EASYBLOG_SUBSCRIBE_FEEDS'); ?></span>
</a>
</li>
<?php } ?>
</ul>
</div>
<?php if(! empty($category->nestedLink)) { ?>
<div class="profile-child ptm small">
<span><?php echo JText::_( 'COM_EASYBLOG_CATEGORIES_SUBCATEGORIES' ); ?></span>
<?php echo $category->nestedLink; ?>
</div>
<?php } ?>
</div><!--end: .profile-info-->
<div class="clear"></div>
</div><!--end: .profile-head-->
<?php if( $this->getParam( 'show_categorystats') || $this->getParam( 'show_categorystatsitem')) { ?>
<div class="profile-body clearfix">
<?php if( $this->getParam( 'show_categorystats') ) { ?>
<div class="profile-sidebar">
<div class="profile-brief">
<div class="in">
<ul class="profile-stats reset-ul clearfix">
<li class="total-post">
<span class="traits float-r"><?php echo $category->cnt; ?></span>
<span class="key"><?php echo JText::_( 'COM_EASYBLOG_BLOGGERS_TOTAL_POSTS' );?></span>
</li>
<?php if( $system->isBloggerMode === false && $category->blogs ) : ?>
<li class="total-comment">
<span class="traits float-r"><?php echo ( $category->bloggers ) ? count( $category->bloggers ) : '0' ;?></span>
<span class="key"><?php echo JText::_( 'COM_EASYBLOG_CATEGORIES_ACTIVE_BLOGGERS' );?></span>
<?php
$initialLimit = ($mainframe->getCfg('list_limit') == 0) ? 5 : $mainframe->getCfg('list_limit');
if( $this->getParam( 'show_category_bloggers_avatar') ){
?>
<ul class="active-bloggers clearfix reset-ul list-full<?php echo ( $system->config->get('layout_avatar') ) ? '' : ' no-avatar'; ?>">
<?php
$initialLimit = ($mainframe->getCfg('list_limit') == 0) ? 5 : $mainframe->getCfg('list_limit');
if( !empty( $category->bloggers ) )
{
$i = 1;
// Repeat this to simulate blogger data
// $category->bloggers[] = $category->bloggers[0];
foreach($category->bloggers as $member )
{
?>
<li <?php if ($i > $initialLimit) { ?>class="more-activebloggers" style="display: none;"<?php } ?>>
<div class="pts pbs">
<a href="<?php echo $member->getProfileLink(); ?>" title="<?php echo $member->getName(); ?>" class="avatar">
<?php if ( $system->config->get('layout_avatar') ) { ?>
<img <?php if ($i <= $initialLimit) { ?> src="<?php echo $member->getAvatar(); ?>" <?php } else { ?> data-src="<?php echo $member->getAvatar(); ?>" <?php } ?> alt="<?php echo $member->getName(); ?>" width="40" height="40" class="avatar float-l mrm" style="overflow: hidden;"/>
<?php echo EasyBlogTooltipHelper::getBloggerHTML( $member->id, array('my'=>'left bottom','at'=>'left top','of'=>array('traverseUsing'=>'parent')) ); ?>
<?php } ?>
<?php echo $member->getName(); ?>
</a>
</div>
</li>
<?php
$i++;
}
}
?>
</ul>
<?php } ?>
<?php
if( !empty( $category->bloggers ) )
{
if (count($category->bloggers) > $initialLimit) {
?>
<script type="text/javascript">
EasyBlog.ready(function($){
$(".showAllBloggers").click(function(){
$('.more-activebloggers')
.each(function() {
$(this).find('.avatar')
.attr('src', $(this).find('.avatar').attr('data-src'));
})
.show();
$(this).remove();
});
});
</script>
<a class="pts showAllBloggers" style="display: inline-block;" href="javascript: void(0);"><?php echo JText::sprintf('COM_EASYBLOG_SHOW_ALL_BLOGGERS', count($category->bloggers)); ?> »</a>
<?php
}
}
?>
</li>
<?php endif; ?>
</ul>
</div>
</div>
</div>
<?php } // if for statistic?>
<?php if( $this->getParam( 'show_categorystatsitem') ) { ?>
<div class="profile-main">
<?php if(empty($category->blogs)) { ?>
<div><?php echo JText::_('COM_EASYBLOG_CATEGORIES_NO_POST_YET'); ?></div>
<?php } else { ?>
<h4 class="rip mbm"><?php echo JText::_( 'COM_EASYBLOG_CATEGORIES_RECENT_POSTS' );?></h4>
<ul class="post-list reset-ul">
<?php foreach( $category->blogs as $entry ) { ?>
<?php echo $this->fetch( 'blog.item.simple'. EasyBlogHelper::getHelper( 'Sources' )->getTemplateFile( $entry->source ) . '.php' , array( 'entry' => $entry , 'customClass' => 'category' )); ?>
<?php } ?>
<li class="post-listmore fwb">
<div>
<?php echo JText::_('COM_EASYBLOG_OTHER_ENTRIES_FROM'); ?>
<a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=categories&layout=listings&id='.$category->id); ?>"><?php echo $category->title;?></a>
</div>
</li>
</ul>
<?php } ?>
</div>
<?php } // if for statistic items ?>
</div><!--end: .profile-body -->
<?php } //end if for outer if ?>
</div><!--end: .blogger-item-->
<?php } //end foreach ?>
<?php if(count($data) <= 0) { ?>
<div><?php echo JText::_('COM_EASYBLOG_NO_RECORDS_FOUND'); ?></div>
<?php } ?>
<?php if ( $pagination ) : ?>
<div class="pagination clearfix">
<?php echo $pagination; ?>
</div>
<?php endif; ?>
</div>
</div><!--end: #ezblog-body-->
|
gpl-2.0
|
sodacrackers/washyacht
|
sites/all/modules/xautoload/tests/src/VirtualDrupal/HookSystem.php
|
1674
|
<?php
namespace Drupal\xautoload\Tests\VirtualDrupal;
class HookSystem {
/**
* @var ModuleImplements
*/
private $moduleImplements;
/**
* @param DrupalStatic $drupalStatic
* @param Cache $cache
* @param ModuleList $moduleList
*/
function __construct(DrupalStatic $drupalStatic, Cache $cache, ModuleList $moduleList) {
$this->moduleImplements = new ModuleImplements($drupalStatic, $cache, $moduleList, $this);
}
/**
* @param string $hook
*/
function moduleInvokeAll($hook) {
$args = func_get_args();
assert($hook === array_shift($args));
foreach ($this->moduleImplements($hook) as $extension) {
$function = $extension . '_' . $hook;
if (function_exists($function)) {
call_user_func_array($function, $args);
}
}
}
/**
* @param string $hook
* @param mixed $data
*/
function drupalAlter($hook, &$data) {
$args = func_get_args();
assert($hook === array_shift($args));
assert($data === array_shift($args));
while (count($args) < 3) {
$args[] = NULL;
}
foreach ($this->moduleImplements($hook . '_alter') as $extension) {
$function = $extension . '_' . $hook . '_alter';
$function($data, $args[0], $args[1], $args[2]);
}
}
/**
* @param string $hook
*
* @throws \Exception
* @return array
*/
function moduleImplements($hook) {
return $this->moduleImplements->moduleImplements($hook);
}
/**
* Resets the module_implements() cache.
*/
public function moduleImplementsReset() {
$this->moduleImplements->reset();
}
}
|
gpl-2.0
|
wfeliz/aicsite
|
sites/default/themes/ipc/page-node-4.tpl.php
|
9189
|
<?php
// $Id: page.tpl.php,v 1.14.2.6 2009/08/18 16:28:33 jselt Exp $
/**
* @file page.tpl.php
*
* Theme implementation to display a single Drupal page.
*
* Available variables:
*
* General utility variables:
* - $base_path: The base URL path of the Drupal installation. At the very
* least, this will always default to /.
* - $css: An array of CSS files for the current page.
* - $directory: The directory the theme is located in, e.g. themes/garland or
* themes/garland/minelli.
* - $is_front: TRUE if the current page is the front page. Used to toggle the mission statement.
* - $logged_in: TRUE if the user is registered and signed in.
* - $is_admin: TRUE if the user has permission to access administration pages.
*
* Page metadata:
* - $language: (object) The language the site is being displayed in.
* $language->language contains its textual representation.
* $language->dir contains the language direction. It will either be 'ltr' or 'rtl'.
* - $head_title: A modified version of the page title, for use in the TITLE tag.
* - $head: Markup for the HEAD section (including meta tags, keyword tags, and
* so on).
* - $styles: Style tags necessary to import all CSS files for the page.
* - $scripts: Script tags necessary to load the JavaScript files and settings
* for the page.
* - $body_classes: A set of CSS classes for the BODY tag. This contains flags
* indicating the current layout (multiple columns, single column), the current
* path, whether the user is logged in, and so on.
* - $body_classes_array: An array of the body classes. This is easier to
* manipulate then the string in $body_classes.
*
* Site identity:
* - $front_page: The URL of the front page. Use this instead of $base_path,
* when linking to the front page. This includes the language domain or prefix.
* - $logo: The path to the logo image, as defined in theme configuration.
* - $site_name: The name of the site, empty when display has been disabled
* in theme settings.
* - $site_slogan: The slogan of the site, empty when display has been disabled
* in theme settings.
* - $mission: The text of the site mission, empty when display has been disabled
* in theme settings.
*
* Navigation:
* - $search_box: HTML to display the search box, empty if search has been disabled.
* - $primary_links (array): An array containing primary navigation links for the
* site, if they have been configured.
* - $secondary_links (array): An array containing secondary navigation links for
* the site, if they have been configured.
*
* Page content (in order of occurrance in the default page.tpl.php):
* - $left: The HTML for the left sidebar.
*
* - $breadcrumb: The breadcrumb trail for the current page.
* - $title: The page title, for use in the actual HTML content.
* - $help: Dynamic help text, mostly for admin pages.
* - $messages: HTML for status and error messages. Should be displayed prominently.
* - $tabs: Tabs linking to any sub-pages beneath the current page (e.g., the view
* and edit tabs when displaying a node).
*
* - $content: The main content of the current Drupal page.
*
* - $right: The HTML for the right sidebar.
*
* Footer/closing data:
* - $feed_icons: A string of all feed icons for the current page.
* - $footer_message: The footer message as defined in the admin settings.
* - $footer : The footer region.
* - $closure: Final closing markup from any modules that have altered the page.
* This variable should always be output last, after all other dynamic content.
*
* @see template_preprocess()
* @see template_preprocess_page()
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>">
<head>
<title><?php print $head_title; ?></title>
<!--[if lte IE 7]> <style>.iehide{display:none;}</style><![endif]-->
<?php print $head; ?>
<?php print $styles; ?>
<?php print $scripts; ?>
<script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script>
</head>
<body class="<?php print $body_classes; ?>">
<div id="skipnav"><a href="#content">Skip to Content</a></div>
<?php if ($top_bar): ?>
<div id="top-bar"><div id="top-bar-inner" class="region region-top-bar clearfix">
<?php print $top_bar; ?>
</div></div> <!-- /#top-bar-inner, /#top-bar -->
<?php endif; ?>
<div id="page"><div id="page-inner">
<a name="top" id="navigation-top"></a>
<?php if ($primary_links || $secondary_links || $navbar): ?>
<div id="skip-to-nav"><a href="#navigation"><?php print t('Skip to Navigation'); ?></a></div>
<?php endif; ?>
<div id="header"><div id="header-inner" class="clear-block">
<?php if ($logo): ?>
<div id="logo">
<a href="<?php print $base_path; ?>"><img src="<?php print $logo; ?>" alt="<?php print $site_name; ?>" id="logo-image" /></a>
</div>
<?php endif; ?>
<?php if ($jump_menu): ?>
<div id="jump"><?php print $jump_menu; ?></div>
<?php endif;?>
</div></div> <!-- /#header-inner, /#header -->
<?php if ($navbar): ?>
<div id="navbar-ipc"><div id="navbar-inner" class="region region-navbar">
<a name="navigation" id="navigation"></a>
<?php print $navbar; ?>
</div></div> <!-- /#navbar-inner, /#navbar -->
<?php endif; ?>
<div id="main"><div id="main-inner" class="clear-block<?php if ($search_box || $primary_links || $secondary_links || $navbar) { print ' with-navbar'; } ?>">
<div id="col-container">
<div id="left-col"<?php if (!$right): ?> class="no-right-sidebar"<?php endif; ?>>
<div id="content"><div id="content-inner">
<?php if ($mission): ?>
<div id="mission"><?php print $mission; ?></div>
<?php endif; ?>
<?php if ($breadcrumb || $title || $tabs || $help || $messages): ?>
<div id="content-header">
<?php if ($title): ?>
<!-- annoying table to vertically center titles in IE 7 and below -->
<table cellpadding="0" cellspacing="0" border="0" class="page-title">
<tr><td valign="middle">
<h1 class="title"><?php print $title; ?></h1>
</td></tr>
</table>
<?php endif; ?>
<?php print $messages; ?>
<?php if ($tabs): ?>
<div class="tabs"><?php print $tabs; ?></div>
<?php endif; ?>
<?php print $help; ?>
</div> <!-- /#content-header -->
<?php endif; ?>
<!-- move content-top under title for publications page -->
<?php if ($content_top): ?>
<div id="content-top" class="region region-content_top">
<?php print $content_top; ?>
</div> <!-- /#content-top -->
<?php endif; ?>
<div id="content-area">
<?php print $content; ?>
</div>
<?php if ($feed_icons): ?>
<div class="feed-icons"><?php print $feed_icons; ?></div>
<?php endif; ?>
<?php if ($content_bottom): ?>
<div id="content-bottom" class="region region-content_bottom">
<?php print $content_bottom; ?>
</div> <!-- /#content-bottom -->
<?php endif; ?>
</div></div> <!-- /#content-inner, /#content -->
</div> <!-- /#left_col -->
<div id="right-col">
<?php if ($right): ?>
<div id="sidebar-right"><div id="sidebar-right-inner" class="region region-right">
<?php print $right; ?>
</div></div> <!-- /#sidebar-right-inner, /#sidebar-right -->
<?php endif; ?>
</div>
<!-- /#right_col -->
<div class="clear"></div>
</div> <!-- /#col_container -->
</div></div> <!-- /#main-inner, /#main -->
<div id="footer"><div id="footer-inner" class="region region-footer">
<div id="footer-left"><?php print $footer; ?> </div>
<div id="footer-right"><?php print $footer_links; ?></div>
<div class="clear"></div></div></div> <!-- /#footer-inner, /#footer -->
</div></div> <!-- /#page-inner, /#page -->
<?php if ($closure_region): ?>
<div id="closure-blocks" class="region region-closure"><?php print $closure_region; ?></div>
<?php endif; ?>
<script type="text/javascript">
// make all pages titles vertically centered for ie 6 and 7
var ps = document.getElementsByTagName("h1");
for (var i=0;i<ps.length;i++) {
ps[i].style.marginTop = ps[i].offsetHeight < ps[i].parentNode.offsetHeight ?
parseInt((ps[i].parentNode.offsetHeight - ps[i].offsetHeight) / 2) + "px" : "0";
}
ps = null;
</script>
<?php print $closure; ?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11341938-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
|
gpl-2.0
|
Yhzhtk/bookcatch
|
shot_new_old.py
|
480
|
# coding=utf-8
'''
Created on 2013-8-30
拍书,新书或者已添加的书
@author: gudh
'''
import bookauto
if __name__ == '__main__':
# 抓取新数据
#args = []
#args.append(["http://e.jd.com/products/5272-5287-5507-1-%d.html", 1, 5])
#args.append(["http://e.jd.com/products/5272-5287-5507-1-%d.html", 5, 10])
#bookauto.new_shot(args)
# 抓取没有成功的数据
id_seq_file = "d:/id_seq_file.txt"
bookauto.old_shot(id_seq_file)
|
gpl-2.0
|
kunj1988/Magento2
|
app/code/Magento/SalesRule/view/frontend/web/js/action/set-coupon-code.js
|
1853
|
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Customer store credit(balance) application
*/
define([
'ko',
'jquery',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/resource-url-manager',
'Magento_Checkout/js/model/error-processor',
'Magento_SalesRule/js/model/payment/discount-messages',
'mage/storage',
'mage/translate',
'Magento_Checkout/js/action/get-payment-information',
'Magento_Checkout/js/model/totals',
'Magento_Checkout/js/model/full-screen-loader'
], function (ko, $, quote, urlManager, errorProcessor, messageContainer, storage, $t, getPaymentInformationAction,
totals, fullScreenLoader
) {
'use strict';
return function (couponCode, isApplied) {
var quoteId = quote.getQuoteId(),
url = urlManager.getApplyCouponUrl(couponCode, quoteId),
message = $t('Your coupon was successfully applied.');
fullScreenLoader.startLoader();
return storage.put(
url,
{},
false
).done(function (response) {
var deferred;
if (response) {
deferred = $.Deferred();
isApplied(true);
totals.isLoading(true);
getPaymentInformationAction(deferred);
$.when(deferred).done(function () {
fullScreenLoader.stopLoader();
totals.isLoading(false);
});
messageContainer.addSuccessMessage({
'message': message
});
}
}).fail(function (response) {
fullScreenLoader.stopLoader();
totals.isLoading(false);
errorProcessor.process(response, messageContainer);
});
};
});
|
gpl-2.0
|
bdmod/extreme-subversion
|
BinarySourcce/subversion-1.6.17/tools/po/l10n-report.py
|
6043
|
#!/usr/bin/env python
"""Usage: l10n-report.py [OPTION...]
Send the l10n translation status report to an email address. If the
email address is not specified, print in stdout.
Options:
-h, --help Show this help message.
-m, --to-email-id Send the l10n translation status report to this
email address.
"""
import sys
import getopt
import os
import re
import subprocess
def usage_and_exit(errmsg=None):
"""Print a usage message, plus an ERRMSG (if provided), then exit.
If ERRMSG is provided, the usage message is printed to stderr and
the script exits with a non-zero error code. Otherwise, the usage
message goes to stdout, and the script exits with a zero
errorcode."""
if errmsg is None:
stream = sys.stdout
else:
stream = sys.stderr
stream.write("%s\n" % __doc__)
stream.flush()
if errmsg:
stream.write("\nError: %s\n" % errmsg)
stream.flush()
sys.exit(2)
sys.exit(0)
class l10nReport:
def __init__(self, to_email_id="bhuvan@collab.net"):
self.to_email_id = to_email_id
self.from_email_id = "<dev@subversion.tigris.org>"
def safe_command(self, cmd_and_args, cmd_in=""):
[stdout, stderr] = subprocess.Popen(cmd_and_args, \
stdin=subprocess.PIPE, \
stdout=subprocess.PIPE, \
stderr=subprocess.PIPE).communicate(input=cmd_in)
return stdout, stderr
def match(self, pattern, string):
match = re.compile(pattern).search(string)
if match and match.groups():
return match.group(1)
else:
return None
def get_msgattribs(self, file):
msgout = self.safe_command(['msgattrib', '--translated', file])[0]
grepout = self.safe_command(['grep', '-E', '^msgid *"'], msgout)[0]
sedout = self.safe_command(['sed', '1d'], grepout)[0]
trans = self.safe_command(['wc', '-l'], sedout)[0]
msgout = self.safe_command(['msgattrib', '--untranslated', file])[0]
grepout = self.safe_command(['grep', '-E', '^msgid *"'], msgout)[0]
sedout = self.safe_command(['sed', '1d'], grepout)[0]
untrans = self.safe_command(['wc', '-l'], sedout)[0]
msgout = self.safe_command(['msgattrib', '--only-fuzzy', file])[0]
grepout = self.safe_command(['grep', '-E', '^msgid *"'], msgout)[0]
sedout = self.safe_command(['sed', '1d'], grepout)[0]
fuzzy = self.safe_command(['wc', '-l'], sedout)[0]
msgout = self.safe_command(['msgattrib', '--only-obsolete', file])[0]
grepout = self.safe_command(['grep', '-E', '^#~ msgid *"'], msgout)[0]
obsolete = self.safe_command(['wc', '-l'], grepout)[0]
return int(trans), int(untrans), int(fuzzy), int(obsolete)
def pre_l10n_report(self):
# svn revert --recursive subversion/po
cmd = ['svn', 'revert', '--recursive', 'subversion/po']
stderr = self.safe_command(cmd)[1]
if stderr:
sys.stderr.write("\nError: %s\n" % stderr)
sys.stderr.flush()
sys.exit(0)
# svn update
cmd = ['svn', 'update']
stderr = self.safe_command(cmd)[1]
if stderr:
sys.stderr.write("\nError: %s\n" % stderr)
sys.stderr.flush()
sys.exit(0)
# tools/po/po-update.sh
cmd = ['sh', 'tools/po/po-update.sh']
self.safe_command(cmd)
def main():
# Parse the command-line options and arguments.
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "hm:",
["help",
"to-email-id=",
])
except getopt.GetoptError, msg:
usage_and_exit(msg)
to_email_id = None
for opt, arg in opts:
if opt in ("-h", "--help"):
usage_and_exit()
elif opt in ("-m", "--to-email-id"):
to_email_id = arg
l10n = l10nReport()
os.chdir("%s/../.." % os.path.dirname(os.path.abspath(sys.argv[0])))
l10n.pre_l10n_report()
[info_out, info_err] = l10n.safe_command(['svn', 'info'])
if info_err:
sys.stderr.write("\nError: %s\n" % info_err)
sys.stderr.flush()
sys.exit(0)
po_dir = 'subversion/po'
branch_name = l10n.match('URL:.*/svn/(\S+)', info_out)
[info_out, info_err] = l10n.safe_command(['svnversion', po_dir])
if info_err:
sys.stderr.write("\nError: %s\n" % info_err)
sys.stderr.flush()
sys.exit(0)
wc_version = re.sub('[MS]', '', info_out)
title = "Translation status report for %s r%s" % \
(branch_name, wc_version)
os.chdir(po_dir)
files = sorted(os.listdir('.'))
format_head = "%6s %7s %7s %7s %7s" % ("lang", "trans", "untrans",
"fuzzy", "obs")
format_line = "--------------------------------------"
print("\n%s\n%s\n%s" % (title, format_head, format_line))
body = ""
for file in files:
lang = l10n.match('(.*).po$', file)
if not lang:
continue
[trans, untrans, fuzzy, obsolete] = l10n.get_msgattribs(file)
po_format = "%6s %7d %7d %7d %7d" %\
(lang, trans, untrans, fuzzy, obsolete)
body += "%s\n" % po_format
print(po_format)
if to_email_id:
email_from = "From: SVN DEV <noreply@subversion.tigris.org>"
email_to = "To: %s" % to_email_id
email_sub = "Subject: [l10n] Translation status report for %s r%s" \
% (branch_name, wc_version)
msg = "%s\n%s\n%s\n%s\n%s\n%s\n%s" % (email_from, email_to,\
email_sub, title, format_head, format_line, body)
cmd = ['sendmail', '-t']
l10n.safe_command(cmd, msg)
print("The report is sent to '%s' email id." % to_email_id)
else:
print("\nYou have not passed '-m' option, so email is not sent.")
if __name__ == "__main__":
main()
|
gpl-2.0
|
rfdrake/opennms
|
opennms-alarms/http-northbounder/src/main/java/org/opennms/netmgt/alarmd/northbounder/http/HttpNorthbounder.java
|
9281
|
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.alarmd.northbounder.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.opennms.core.utils.EmptyKeyRelaxedTrustProvider;
import org.opennms.core.utils.EmptyKeyRelaxedTrustSSLContext;
import org.opennms.core.utils.HttpResponseRange;
import org.opennms.netmgt.alarmd.api.NorthboundAlarm;
import org.opennms.netmgt.alarmd.api.NorthbounderException;
import org.opennms.netmgt.alarmd.api.support.AbstractNorthbounder;
import org.opennms.netmgt.alarmd.northbounder.http.HttpNorthbounderConfig.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Forwards north bound alarms via HTTP.
* FIXME: Needs lots of work still :(
*
* @author <a mailto:david@opennms.org>David Hustace</a>
*/
public class HttpNorthbounder extends AbstractNorthbounder {
private static final Logger LOG = LoggerFactory.getLogger(HttpNorthbounder.class);
private HttpNorthbounderConfig m_config;
protected HttpNorthbounder() {
super("HttpNorthbounder");
}
//FIXME: This should be wired with Spring but is implmented as was in the PSM
// Make sure that the {@link EmptyKeyRelaxedTrustSSLContext} algorithm
// is available to JSSE
static {
//this is a safe call because the method returns -1 if it is already installed (by PageSequenceMonitor, etc.)
java.security.Security.addProvider(new EmptyKeyRelaxedTrustProvider());
}
@Override
public boolean accepts(NorthboundAlarm alarm) {
if (m_config.getAcceptableUeis() == null || m_config.getAcceptableUeis().contains(alarm.getUei())) {
return true;
}
return false;
}
@Override
public void forwardAlarms(List<NorthboundAlarm> alarms) throws NorthbounderException {
LOG.info("Forwarding {} alarms", alarms.size());
//Need a configuration bean for these
int connectionTimeout = 3000;
int socketTimeout = 3000;
Integer retryCount = Integer.valueOf(3);
HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
String policy = CookiePolicy.BROWSER_COMPATIBILITY;
URI uri = m_config.getURI();
DefaultHttpClient client = new DefaultHttpClient(buildParams(httpVersion, connectionTimeout,
socketTimeout, policy, m_config.getVirtualHost()));
client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));
if ("https".equals(uri.getScheme())) {
final SchemeRegistry registry = client.getConnectionManager().getSchemeRegistry();
final Scheme https = registry.getScheme("https");
// Override the trust validation with a lenient implementation
SSLSocketFactory factory = null;
try {
factory = new SSLSocketFactory(SSLContext.getInstance(EmptyKeyRelaxedTrustSSLContext.ALGORITHM), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
} catch (Throwable e) {
throw new NorthbounderException(e);
}
final Scheme lenient = new Scheme(https.getName(), https.getDefaultPort(), factory);
// This will replace the existing "https" schema
registry.register(lenient);
}
HttpUriRequest method = null;
if (HttpMethod.POST == (m_config.getMethod())) {
HttpPost postMethod = new HttpPost(uri);
//TODO: need to configure these
List<NameValuePair> postParms = new ArrayList<NameValuePair>();
//FIXME:do this for now
NameValuePair p = new BasicNameValuePair("foo", "bar");
postParms.add(p);
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParms, "UTF-8");
postMethod.setEntity(entity);
} catch (UnsupportedEncodingException e) {
throw new NorthbounderException(e);
}
HttpEntity entity = null;
try {
//I have no idea what I'm doing here ;)
entity = new StringEntity("XML HERE");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
postMethod.setEntity(entity);
method = postMethod;
} else if (HttpMethod.GET == m_config.getMethod()) {
//TODO: need to configure these
//List<NameValuePair> getParms = null;
method = new HttpGet(uri);
}
method.getParams().setParameter(CoreProtocolPNames.USER_AGENT, m_config.getUserAgent());
HttpResponse response = null;
try {
response = client.execute(method);
} catch (ClientProtocolException e) {
throw new NorthbounderException(e);
} catch (IOException e) {
throw new NorthbounderException(e);
}
if (response != null) {
int code = response.getStatusLine().getStatusCode();
HttpResponseRange range = new HttpResponseRange("200-399");
if (!range.contains(code)) {
LOG.debug("response code out of range for uri:{}. Expected {} but received {}", uri, range, code);
throw new NorthbounderException("response code out of range for uri:" + uri + ". Expected " + range + " but received " + code);
}
}
LOG.debug(response != null ? response.getStatusLine().getReasonPhrase() : "Response was null");
}
private HttpVersion determineHttpVersion(String version) {
HttpVersion httpVersion = null;
if (version != "1.0") {
httpVersion = HttpVersion.HTTP_1_1;
} else {
httpVersion = HttpVersion.HTTP_1_0;
}
return httpVersion;
}
private HttpParams buildParams(HttpVersion protocolVersion,
int connectionTimeout, int socketTimeout, String policy,
String vHost) {
HttpParams parms = new BasicHttpParams();
parms.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, protocolVersion);
parms.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
parms.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
parms.setParameter(ClientPNames.COOKIE_POLICY, policy);
parms.setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(vHost, 8080));
return parms;
}
public HttpNorthbounderConfig getConfig() {
return m_config;
}
public void setConfig(HttpNorthbounderConfig config) {
m_config = config;
}
}
|
gpl-2.0
|
786228836/MyAndroid
|
app/src/main/java/com/example/test/myandroid/LoginActivity.java
|
1127
|
package com.example.test.myandroid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
@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, 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
|
wakuki14/bangluong
|
components/com_mad4joomla/language/frontend.fr.php
|
3979
|
<?PHP
/**
* @version $Id: mad4joomla 10041 2008-03-18 21:48:13Z fahrettinkutyol $
* @package joomla
* @copyright Copyright (C) 2008 Mad4Media. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
* @copyright (C) mad4media , www.mad4media.de
*/
/** FRENCH VERSION BY KEO - 2009-07-31 - keo.one@gmail.com */
defined( '_JEXEC' ) or die( 'L'accès direct à cette partie du site est interdit.' );
define('M4J_LANG_FORM_CATEGORIES','Catégories de formulaires');
define('M4J_LANG_ERROR_NO_CATEGORY','La catégorie de formulaire demandée n'existe pas ou n'est pas publiée.');
define('M4J_LANG_ERROR_NO_FORM','Le formulaire demandé n'existe pas ou n'est pas publié');
define('M4J_LANG_YES','Oui');
define('M4J_LANG_NO','Non');
define('M4J_LANG_NO_CATEGORY','Sans catégorie');
define('M4J_LANG_NO_CATEGORY_LONG','Ici vous pouvez trouver tous les formulaires qui n'ont pas de catégorie.');
define('M4J_LANG_SUBMIT','Envoyer');
define('M4J_LANG_MISSING','Champ manquant: ');
define('M4J_LANG_ERROR_IN_FORM','Il manque une information obligatoire:');
define('M4J_LANG_ERROR_NO_MAIL_ADRESS','Il n'y a pas d'adresse de destination pour ce formulaire. Le message n'a pu être envoyé.');
define('M4J_LANG_ERROR_CAPTCHA','Code de securité incorrect ou validité expirée!');
define('M4J_LANG_MAIL_SUBJECT','Message du formulaire: ');
define('M4J_LANG_CAPTCHA_ADVICE','Passez la souris sur l'image de gauche et tapez le code dans la case de droite.');
define('M4J_LANG_REQUIRED_DESC','=information obligatoire');
define('M4J_LANG_SENT_SUCCESS','Données transmises avec succés.');
//New To Version 1.1.8
define('M4J_LANG_TO_LARGE','<br/> - La taille du fichier est trop importante ! Maximum: ');
define('M4J_LANG_WRONG_ENDING','<br/> - L'extension du fichier est incorrecte !<br/> Extensions autorisées: ');
//New To Version 1.1.9
define('M4J_LANG_SENT_ERROR','Une erreur s'est produite lors de l'envoi.<br/>Le message n'a pu être envoyé.');
//New To Mad4Joomla
define ( 'M4J_LANG_ERROR_USERMAIL', 'Vous devez saisir une adresse email valide:');
define ( 'M4J_LANG_RESET', 'reset');
define ( 'M4J_LANG_REQUIRED', 'est nécessaire et mai pas être vide. ');
define ( 'M4J_LANG_ERROR_PROMPT', 'Nos excuses. Certaines des données saisies ne sont pas valides et ne peuvent être traitées. Les champs correspondants sont marqués.');
define ( 'M4J_LANG_ALPHABETICAL', 'doivent être soit alphabétiques.');
define ( 'M4J_LANG_NUMERIC', 'doit être numérique.');
define ( 'M4J_LANG_INTEGER', 'doit être un nombre entier.');
define ( 'M4J_LANG_URL', 'doit être un URL.');
define ( 'M4J_LANG_EMAIL', 'doit être une adresse email valide.');
define ( 'M4J_LANG_ALPHANUMERIC', 'Doit être alphanumérique.');
define ( 'M4J_LANG_PLEASE_SELECT', 'S\'il vous plaît sélectionnez');
define ( 'M4J_LANG_ASK2CONFIRM', 'S\'il vous plaît envoyez-moi une confirmation.');
define ( 'M4J_LANG_ASK2CONFIRM_DESC', 'Si vous cochez cette case, vous obtiendrez un email de confirmation des données soumises.');
// New to Mad4Joomla 1.0.5
define('M4J_LANG_ERROR_NO_TEMPLATE','This form hasn\'t been assigned to a form template!');
// New to Mad4Joomla 1.1
define('M4J_LANG_OPTIN_CONFIRMATION_SUBJECT','Vous avez confirmé votre demande.');
define('M4J_LANG_OPTOUT_CONFIRMATION_SUBJECT','Vous avez révoqué la confirmation de votre demande.');
?>
|
gpl-2.0
|
seekmas/cms_dev
|
cache/mod_custom/bd162cb6189e3e2a2bd8fccee31759dc-cache-mod_custom-3f896e5e6dfae42b1a5fa611dce3f5ee.php
|
324
|
<?php die("Access Denied"); ?>#x#a:2:{s:6:"output";a:2:{s:4:"body";s:0:"";s:4:"head";a:0:{}}s:6:"result";s:209:"
<h3 class="margin-bottom">SERVICES</h3>
<ul class="uk-list uk-list-line">
<li><a href="#">Print version</a></li>
<li><a href="#">Newsletter</a></li>
<li><a href="#">RSS feed</a></li>
</ul>
";}
|
gpl-2.0
|
haidarafif0809/qwooxcqmkozzxce
|
batal_item_masuk.php
|
674
|
<?php
// memasukan file db.php
include 'db.php';
// mengirim data(file) no_faktur, menggunakan metode GET
$no_faktur = $_GET['no_faktur'];
// menghapus data pada tabel tbs_pembelian berdasarkan no_faktur
$query = $db->query("DELETE FROM tbs_item_masuk WHERE no_faktur = '$no_faktur'");
// logika $query => jika $query benar maka akan menuju ke formpemebelain.php
// dan jika salah maka akan menampilkan kalimat failed
if ($query == TRUE)
{
header('location:form_item_masuk.php');
}
else
{
echo "failed";
}
//Untuk Memutuskan Koneksi Ke Database
mysqli_close($db);
?>
|
gpl-2.0
|
Blaez/ZiosGram
|
TMessagesProj/src/main/java/org/telegram/messenger/support/widget/util/SortedListAdapterCallback.java
|
1908
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.blaez.ziosgram.support.widget.util;
import org.blaez.ziosgram.support.util.SortedList;
import org.blaez.ziosgram.support.widget.RecyclerView;
/**
* A {@link SortedList.Callback} implementation that can bind a {@link SortedList} to a
* {@link RecyclerView.Adapter}.
*/
public abstract class SortedListAdapterCallback<T2> extends SortedList.Callback<T2> {
final RecyclerView.Adapter mAdapter;
/**
* Creates a {@link SortedList.Callback} that will forward data change events to the provided
* Adapter.
*
* @param adapter The Adapter instance which should receive events from the SortedList.
*/
public SortedListAdapterCallback(RecyclerView.Adapter adapter) {
mAdapter = adapter;
}
@Override
public void onInserted(int position, int count) {
mAdapter.notifyItemRangeInserted(position, count);
}
@Override
public void onRemoved(int position, int count) {
mAdapter.notifyItemRangeRemoved(position, count);
}
@Override
public void onMoved(int fromPosition, int toPosition) {
mAdapter.notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onChanged(int position, int count) {
mAdapter.notifyItemRangeChanged(position, count);
}
}
|
gpl-2.0
|
miguelinux/vbox
|
src/VBox/Devices/Audio_old/DrvHostNullAudio.cpp
|
10540
|
/* $Id: DrvHostNullAudio.cpp $ */
/** @file
* NULL audio driver -- also acts as a fallback if no
* other backend is available.
*/
/*
* Copyright (C) 2006-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
* --------------------------------------------------------------------
*
* This code is based on: noaudio.c QEMU based code.
*
* QEMU Timer based audio emulation
*
* Copyright (c) 2004-2005 Vassili Karpov (malc)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#define LOG_GROUP LOG_GROUP_DRV_HOST_AUDIO
#include <VBox/log.h>
#include "DrvAudio.h"
#include "AudioMixBuffer.h"
#include "VBoxDD.h"
#include <iprt/alloc.h>
#include <iprt/uuid.h> /* For PDMIBASE_2_PDMDRV. */
#include <VBox/vmm/pdmaudioifs.h>
typedef struct NULLAUDIOSTREAMOUT
{
/** Note: Always must come first! */
PDMAUDIOHSTSTRMOUT streamOut;
uint64_t u64TicksLast;
uint64_t csPlayBuffer;
uint8_t *pu8PlayBuffer;
} NULLAUDIOSTREAMOUT, *PNULLAUDIOSTREAMOUT;
typedef struct NULLAUDIOSTREAMIN
{
/** Note: Always must come first! */
PDMAUDIOHSTSTRMIN streamIn;
} NULLAUDIOSTREAMIN, *PNULLAUDIOSTREAMIN;
/**
* NULL audio driver instance data.
* @implements PDMIAUDIOCONNECTOR
*/
typedef struct DRVHOSTNULLAUDIO
{
/** Pointer to the driver instance structure. */
PPDMDRVINS pDrvIns;
/** Pointer to host audio interface. */
PDMIHOSTAUDIO IHostAudio;
} DRVHOSTNULLAUDIO, *PDRVHOSTNULLAUDIO;
/*******************************************PDM_AUDIO_DRIVER******************************/
static DECLCALLBACK(int) drvHostNullAudioGetConf(PPDMIHOSTAUDIO pInterface, PPDMAUDIOBACKENDCFG pCfg)
{
NOREF(pInterface);
AssertPtrReturn(pCfg, VERR_INVALID_POINTER);
pCfg->cbStreamOut = sizeof(NULLAUDIOSTREAMOUT);
pCfg->cbStreamIn = sizeof(NULLAUDIOSTREAMIN);
pCfg->cMaxHstStrmsOut = 1; /* Output */
pCfg->cMaxHstStrmsIn = 2; /* Line input + microphone input. */
return VINF_SUCCESS;
}
static DECLCALLBACK(int) drvHostNullAudioInit(PPDMIHOSTAUDIO pInterface)
{
NOREF(pInterface);
return VINF_SUCCESS;
}
static DECLCALLBACK(int) drvHostNullAudioInitIn(PPDMIHOSTAUDIO pInterface,
PPDMAUDIOHSTSTRMIN pHstStrmIn, PPDMAUDIOSTREAMCFG pCfg,
PDMAUDIORECSOURCE enmRecSource,
uint32_t *pcSamples)
{
NOREF(pInterface);
NOREF(enmRecSource);
/* Just adopt the wanted stream configuration. */
int rc = DrvAudioStreamCfgToProps(pCfg, &pHstStrmIn->Props);
if (RT_SUCCESS(rc))
{
if (pcSamples)
*pcSamples = _1K;
}
return VINF_SUCCESS;
}
static DECLCALLBACK(int) drvHostNullAudioInitOut(PPDMIHOSTAUDIO pInterface,
PPDMAUDIOHSTSTRMOUT pHstStrmOut, PPDMAUDIOSTREAMCFG pCfg,
uint32_t *pcSamples)
{
NOREF(pInterface);
/* Just adopt the wanted stream configuration. */
int rc = DrvAudioStreamCfgToProps(pCfg, &pHstStrmOut->Props);
if (RT_SUCCESS(rc))
{
PNULLAUDIOSTREAMOUT pNullStrmOut = (PNULLAUDIOSTREAMOUT)pHstStrmOut;
pNullStrmOut->u64TicksLast = 0;
pNullStrmOut->csPlayBuffer = _1K;
pNullStrmOut->pu8PlayBuffer = (uint8_t *)RTMemAlloc(_1K << pHstStrmOut->Props.cShift);
if (pNullStrmOut->pu8PlayBuffer)
{
if (pcSamples)
*pcSamples = pNullStrmOut->csPlayBuffer;
}
else
{
rc = VERR_NO_MEMORY;
}
}
return rc;
}
static DECLCALLBACK(bool) drvHostNullAudioIsEnabled(PPDMIHOSTAUDIO pInterface, PDMAUDIODIR enmDir)
{
NOREF(pInterface);
NOREF(enmDir);
return true; /* Always all enabled. */
}
static DECLCALLBACK(int) drvHostNullAudioPlayOut(PPDMIHOSTAUDIO pInterface, PPDMAUDIOHSTSTRMOUT pHstStrmOut,
uint32_t *pcSamplesPlayed)
{
PDRVHOSTNULLAUDIO pDrv = RT_FROM_MEMBER(pInterface, DRVHOSTNULLAUDIO, IHostAudio);
PNULLAUDIOSTREAMOUT pNullStrmOut = (PNULLAUDIOSTREAMOUT)pHstStrmOut;
/* Consume as many samples as would be played at the current frequency since last call. */
uint32_t csLive = AudioMixBufAvail(&pHstStrmOut->MixBuf);
uint64_t u64TicksNow = PDMDrvHlpTMGetVirtualTime(pDrv->pDrvIns);
uint64_t u64TicksElapsed = u64TicksNow - pNullStrmOut->u64TicksLast;
uint64_t u64TicksFreq = PDMDrvHlpTMGetVirtualFreq(pDrv->pDrvIns);
/* Remember when samples were consumed. */
pNullStrmOut->u64TicksLast = u64TicksNow;
/*
* Minimize the rounding error by adding 0.5: samples = int((u64TicksElapsed * samplesFreq) / u64TicksFreq + 0.5).
* If rounding is not taken into account then the playback rate will be consistently lower that expected.
*/
uint64_t cSamplesPlayed = (2 * u64TicksElapsed * pHstStrmOut->Props.uHz + u64TicksFreq) / u64TicksFreq / 2;
/* Don't play more than available. */
if (cSamplesPlayed > csLive)
cSamplesPlayed = csLive;
cSamplesPlayed = RT_MIN(cSamplesPlayed, pNullStrmOut->csPlayBuffer);
uint32_t csRead = 0;
AudioMixBufReadCirc(&pHstStrmOut->MixBuf, pNullStrmOut->pu8PlayBuffer,
AUDIOMIXBUF_S2B(&pHstStrmOut->MixBuf, cSamplesPlayed), &csRead);
AudioMixBufFinish(&pHstStrmOut->MixBuf, csRead);
if (pcSamplesPlayed)
*pcSamplesPlayed = csRead;
return VINF_SUCCESS;
}
static DECLCALLBACK(int) drvHostNullAudioCaptureIn(PPDMIHOSTAUDIO pInterface, PPDMAUDIOHSTSTRMIN pHstStrmIn,
uint32_t *pcSamplesCaptured)
{
/* Never capture anything. */
if (pcSamplesCaptured)
*pcSamplesCaptured = 0;
return VINF_SUCCESS;
}
static DECLCALLBACK(int) drvHostNullAudioControlIn(PPDMIHOSTAUDIO pInterface, PPDMAUDIOHSTSTRMIN pHstStrmIn,
PDMAUDIOSTREAMCMD enmStreamCmd)
{
NOREF(pInterface);
NOREF(pHstStrmIn);
NOREF(enmStreamCmd);
return VINF_SUCCESS;
}
static DECLCALLBACK(int) drvHostNullAudioControlOut(PPDMIHOSTAUDIO pInterface, PPDMAUDIOHSTSTRMOUT pHstStrmOut,
PDMAUDIOSTREAMCMD enmStreamCmd)
{
NOREF(pInterface);
NOREF(pHstStrmOut);
NOREF(enmStreamCmd);
return VINF_SUCCESS;
}
static DECLCALLBACK(int) drvHostNullAudioFiniIn(PPDMIHOSTAUDIO pInterface, PPDMAUDIOHSTSTRMIN pHstStrmIn)
{
return VINF_SUCCESS;
}
static DECLCALLBACK(int) drvHostNullAudioFiniOut(PPDMIHOSTAUDIO pInterface, PPDMAUDIOHSTSTRMOUT pHstStrmOut)
{
PNULLAUDIOSTREAMOUT pNullStrmOut = (PNULLAUDIOSTREAMOUT)pHstStrmOut;
if ( pNullStrmOut
&& pNullStrmOut->pu8PlayBuffer)
{
RTMemFree(pNullStrmOut->pu8PlayBuffer);
}
return VINF_SUCCESS;
}
/**
* @interface_method_impl{PDMIBASE,pfnQueryInterface}
*/
static DECLCALLBACK(void *) drvHostNullAudioQueryInterface(PPDMIBASE pInterface, const char *pszIID)
{
PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
PDRVHOSTNULLAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTNULLAUDIO);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIHOSTAUDIO, &pThis->IHostAudio);
return NULL;
}
static DECLCALLBACK(void) drvHostNullAudioShutdown(PPDMIHOSTAUDIO pInterface)
{
NOREF(pInterface);
}
/**
* Constructs a Null audio driver instance.
*
* @copydoc FNPDMDRVCONSTRUCT
*/
static DECLCALLBACK(int) drvHostNullAudioConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
{
AssertPtrReturn(pDrvIns, VERR_INVALID_POINTER);
/* pCfg is optional. */
PDRVHOSTNULLAUDIO pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTNULLAUDIO);
LogRel(("Audio: Initializing NULL driver\n"));
/*
* Init the static parts.
*/
pThis->pDrvIns = pDrvIns;
/* IBase */
pDrvIns->IBase.pfnQueryInterface = drvHostNullAudioQueryInterface;
/* IHostAudio */
PDMAUDIO_IHOSTAUDIO_CALLBACKS(drvHostNullAudio);
return VINF_SUCCESS;
}
/**
* Char driver registration record.
*/
const PDMDRVREG g_DrvHostNullAudio =
{
/* u32Version */
PDM_DRVREG_VERSION,
/* szName */
"NullAudio",
/* szRCMod */
"",
/* szR0Mod */
"",
/* pszDescription */
"NULL audio host driver",
/* fFlags */
PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
/* fClass. */
PDM_DRVREG_CLASS_AUDIO,
/* cMaxInstances */
~0U,
/* cbInstance */
sizeof(DRVHOSTNULLAUDIO),
/* pfnConstruct */
drvHostNullAudioConstruct,
/* pfnDestruct */
NULL,
/* pfnRelocate */
NULL,
/* pfnIOCtl */
NULL,
/* pfnPowerOn */
NULL,
/* pfnReset */
NULL,
/* pfnSuspend */
NULL,
/* pfnResume */
NULL,
/* pfnAttach */
NULL,
/* pfnDetach */
NULL,
/* pfnPowerOff */
NULL,
/* pfnSoftReset */
NULL,
/* u32EndVersion */
PDM_DRVREG_VERSION
};
|
gpl-2.0
|
scanalesespinoza/battlebit
|
templates/atomic/html/modules.php
|
1998
|
<?php
/**
* @version $Id: modules.php 14276 2010-01-18 14:20:28Z louis $
* @package Joomla.Site
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die;
/**
* This is a file to add template specific chrome to module rendering. To use it you would
* set the style attribute for the given module(s) include in your template to use the style
* for each given modChrome function.
*
* eg. To render a module mod_test in the sliders style, you would use the following include:
* <jdoc:include type="module" name="test" style="slider" />
*
* This gives template designers ultimate control over how modules are rendered.
*
* NOTICE: All chrome wrapping methods should be named: modChrome_{STYLE} and take the same
* two arguments.
*
* This module chrome file creates custom output for modules used with the Atomic template.
* The first function wraps modules using the "container" style in a DIV. The second function
* uses the "bottommodule" style to change the header on the bottom modules to H6. The third
* function uses the "sidebar" style to change the header on the sidebar to H3.
*/
function modChrome_container($module, &$params, &$attribs)
{
if (!empty ($module->content)) : ?>
<div class="container">
<?php echo $module->content; ?>
</div>
<?php endif;
}
function modChrome_bottommodule($module, &$params, &$attribs)
{
if (!empty ($module->content)) : ?>
<?php if ($module->showtitle) : ?>
<h6><?php echo $module->title; ?></h6>
<?php endif; ?>
<?php echo $module->content; ?>
<?php endif;
}
function modChrome_sidebar($module, &$params, &$attribs)
{
if (!empty ($module->content)) : ?>
<?php if ($module->showtitle) : ?>
<h3><?php echo $module->title; ?></h3>
<?php endif; ?>
<?php echo $module->content; ?>
<?php endif;
}
?>
|
gpl-2.0
|
alpinelab/lzd
|
wp-content/themes/minimum/category.php
|
36419
|
<?php get_header(); ?>
<?php
global $wp_query;
global $woocommerce;
$id = $wp_query->get_queried_object_id();
$sidebar = $qode_options['category_blog_sidebar'];
?>
<div class="container">
<div class="title">
<h1><span><?php single_cat_title(''); ?></span></h1>
<div class="woocommerce_cart_items">
<?php if($woocommerce->cart->cart_contents_count > 0 ){ ?>
<a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>">
<img src="<?php bloginfo('template_url'); ?>/img/woocommerce_cart_image.png" /><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> , <?php echo $woocommerce->cart->get_cart_total(); ?>
</a>
<?php }else{ ?>
<a class="cart-contents" href="" ></a>
<?php } ?>
</div>
</div>
</div>
<?php
$revslider = get_post_meta($id, "qode_revolution-slider", true);
if (!empty($revslider)){
echo do_shortcode($revslider);
}
?>
<div class="container">
<?php if(($sidebar == "default")||($sidebar == "")) : ?>
<?php switch ($qode_options['blog_style']) {
case 1: ?>
<div class="posts_holder">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('blog-type-1-big'); ?>
</a>
</div>
<?php } } ?>
<div class="text">
<div class="text_inner">
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a>
<div class="info">
<span class="left"><?php the_time('d M Y'); ?> <?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
</div>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 2: ?>
<div class="posts_holder2">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('full'); ?>
</a>
</div>
<?php } } ?>
<div class="text">
<div class="text_inner">
<span class="date">
<span class="number"><?php the_time('d'); ?></span>
<span class="month"><?php the_time('m'); ?></span>
</span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a> / <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 3: ?>
<div class="posts_holder3 clearfix">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<div class="article_inner">
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('blog-type-3-big'); ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="text">
<div class="text_inner">
<span><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
<span class="right"> <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 4: ?>
<div class="posts_holder3 posts_holder3_v2 clearfix">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<div class="article_inner">
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('blog-type-4-big'); ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="text">
<div class="text_inner">
<span><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
<span class="right"> <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 5: ?>
<div class="posts_holder2 post_single post_list5">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('full'); ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="date"><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></div>
<div class="text">
<div class="text_inner">
<?php the_content(); ?>
</div>
</div>
<div class="info">
<span class="left"><?php the_time('d M Y'); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a> / <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
}
?>
<?php elseif($sidebar == "1" || $sidebar == "2"): ?>
<div class="<?php if($sidebar == "1"):?>two_columns_66_33<?php elseif($sidebar == "2") : ?>two_columns_75_25<?php endif; ?> clearfix">
<div class="column_left">
<div class="column_inner">
<?php switch ($qode_options['blog_style']) {
case 1: ?>
<div class="posts_holder">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if($sidebar == 1) : ?>
<?php the_post_thumbnail('blog-type-1-medium'); ?>
<?php elseif($sidebar == 2) : ?>
<?php the_post_thumbnail('blog-type-1-small'); ?>
<?php endif; ?>
</a>
</div>
<?php } } ?>
<div class="text">
<div class="text_inner">
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a>
<div class="info">
<span class="left"><?php the_time('d M Y'); ?> <?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
</div>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 2: ?>
<div class="posts_holder2">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('full'); ?>
</a>
</div>
<?php } } ?>
<div class="text">
<div class="text_inner">
<span class="date">
<span class="number"><?php the_time('d'); ?></span>
<span class="month"><?php the_time('m'); ?></span>
</span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a> / <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 3: ?>
<div class="posts_holder3 clearfix">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<div class="article_inner">
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if($sidebar == 1) : ?>
<?php the_post_thumbnail('blog-type-3-medium'); ?>
<?php elseif($sidebar == 2) : ?>
<?php the_post_thumbnail('blog-type-3-small'); ?>
<?php endif; ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="text">
<div class="text_inner">
<span><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
<span class="right"> <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 4: ?>
<div class="posts_holder3 posts_holder3_v2 clearfix">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<div class="article_inner">
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if($sidebar == 1) : ?>
<?php the_post_thumbnail('blog-type-4-medium'); ?>
<?php elseif($sidebar == 2) : ?>
<?php the_post_thumbnail('blog-type-4-small'); ?>
<?php endif; ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="text">
<div class="text_inner">
<span><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
<span class="right"> <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 5: ?>
<div class="posts_holder2 post_single post_list5">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('full'); ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="date"><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></div>
<div class="text">
<div class="text_inner">
<?php the_content(); ?>
</div>
</div>
<div class="info">
<span class="left"><?php the_time('d M Y'); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a> / <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
}
?>
</div>
</div>
<div class="column_right">
<?php get_sidebar(); ?>
</div>
</div>
<?php elseif($sidebar == "3" || $sidebar == "4"): ?>
<div class="<?php if($sidebar == "3"):?>two_columns_33_66<?php elseif($sidebar == "4") : ?>two_columns_25_75<?php endif; ?> clearfix">
<div class="column_left">
<?php get_sidebar(); ?>
</div>
<div class="column_right">
<div class="column_inner">
<?php switch ($qode_options['blog_style']) {
case 1: ?>
<div class="posts_holder">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if($sidebar == 3) : ?>
<?php the_post_thumbnail('blog-type-1-medium'); ?>
<?php elseif($sidebar == 4) : ?>
<?php the_post_thumbnail('blog-type-1-small'); ?>
<?php endif; ?>
</a>
</div>
<?php } } ?>
<div class="text">
<div class="text_inner">
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?></p>
<a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a>
<div class="info">
<span class="left"><?php the_time('d M Y'); ?> <?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
</div>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 2: ?>
<div class="posts_holder2">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('full'); ?>
</a>
</div>
<?php } } ?>
<div class="text">
<div class="text_inner">
<span class="date">
<span class="number"><?php the_time('d'); ?></span>
<span class="month"><?php the_time('m'); ?></span>
</span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a> / <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 3: ?>
<div class="posts_holder3 clearfix">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<div class="article_inner">
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if($sidebar == 3) : ?>
<?php the_post_thumbnail('blog-type-3-medium'); ?>
<?php elseif($sidebar == 4) : ?>
<?php the_post_thumbnail('blog-type-3-small'); ?>
<?php endif; ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="text">
<div class="text_inner">
<span><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
<span class="right"> <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 4: ?>
<div class="posts_holder3 posts_holder3_v2 clearfix">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<div class="article_inner">
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if($sidebar == 3) : ?>
<?php the_post_thumbnail('blog-type-4-medium'); ?>
<?php elseif($sidebar == 4) : ?>
<?php the_post_thumbnail('blog-type-4-small'); ?>
<?php endif; ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="text">
<div class="text_inner">
<span><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></span>
<p><?php the_excerpt(); ?></p>
</div>
</div>
<div class="info">
<span class="left"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a></span>
<span class="right"> <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
case 5: ?>
<div class="posts_holder2 post_single post_list5">
<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>
<article <?php post_class(); ?>>
<?php if(get_post_meta(get_the_ID(), "qode_use-slider-instead-of-image", true) == "yes") { ?>
<div class="image">
<?php echo slider_blog(get_the_ID());?>
</div>
<?php } else {?>
<?php if ( has_post_thumbnail() ) { ?>
<div class="image">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail('full'); ?>
</a>
</div>
<?php } } ?>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="date"><?php _e('Posted by','qode'); ?> <?php the_author(); ?> <?php _e('in','qode'); ?> <?php the_category(', '); ?></div>
<div class="text">
<div class="text_inner">
<?php the_content(); ?>
</div>
</div>
<div class="info">
<span class="left"><?php the_time('d M Y'); ?></span>
<span class="right"><a href="<?php comments_link(); ?>"><?php comments_number( __('no comments','qode'), '1 '.__('comment','qode'), '% '.__('comments','qode') ); ?></a> / <a href="<?php the_permalink(); ?>" class="more" title="<?php the_title_attribute(); ?>"><?php _e('READ MORE', 'qode'); ?></a></span>
</div>
</article>
<?php endwhile; ?>
<?php if($qode_options['pagination'] != "0") : ?>
<?php pagination($wp_query->max_num_pages,$wp_query->max_num_pages, $paged); ?>
<?php endif; ?>
<?php else: //If no posts are present ?>
<div class="entry">
<p><?php _e('No posts were found.', 'qode'); ?></p>
</div>
<?php endif; ?>
</div>
<?php break;
}
?>
</div>
</div>
</div>
<?php endif; ?>
</div>
<?php get_footer(); ?>
|
gpl-2.0
|
mulligaj/hubzero-cms
|
core/components/com_collections/admin/controllers/items.php
|
6833
|
<?php
/**
* HUBzero CMS
*
* Copyright 2005-2015 HUBzero Foundation, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* HUBzero is a registered trademark of Purdue University.
*
* @package hubzero-cms
* @author Shawn Rice <zooley@purdue.edu>
* @copyright Copyright 2005-2015 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Collections\Admin\Controllers;
use Components\Collections\Models\Orm\Item;
use Components\Collections\Models\Orm\Asset;
use Hubzero\Component\AdminController;
use Request;
use Notify;
use Route;
use Lang;
use User;
use Date;
use App;
/**
* Controller class for collection items
*/
class Items extends AdminController
{
/**
* Execute a task
*
* @return void
*/
public function execute()
{
$this->registerTask('add', 'edit');
$this->registerTask('apply', 'save');
parent::execute();
}
/**
* Display a list of all entries
*
* @return void
*/
public function displayTask()
{
// Get filters
$filters = array(
'sort' => Request::getState(
$this->_option . '.' . $this->_controller . '.sort',
'filter_order',
'created'
),
'sort_Dir' => Request::getState(
$this->_option . '.' . $this->_controller . '.sortdir',
'filter_order_Dir',
'DESC'
),
'search' => urldecode(Request::getState(
$this->_option . '.' . $this->_controller . '.search',
'search',
''
)),
'type' => urldecode(Request::getState(
$this->_option . '.' . $this->_controller . '.type',
'type',
''
)),
'state' => Request::getState(
$this->_option . '.' . $this->_controller . '.state',
'state',
'-1'
),
'access' => Request::getState(
$this->_option . '.' . $this->_controller . '.access',
'access',
'-1'
)
);
$model = Item::all()
->including(['creator', function ($creator){
$creator->select('*');
}]);
if ($filters['search'])
{
$model->whereLike('title', strtolower((string)$filters['search']));
}
if ($filters['state'] >= 0)
{
$model->whereEquals('state', $filters['state']);
}
if ($filters['access'] >= 0)
{
$model->whereEquals('access', (int)$filters['access']);
}
if ($filters['type'])
{
$model->whereEquals('type', $filters['type']);
}
else
{
$model->where('type', '!=', 'collection');
}
// Get records
$rows = $model
->ordered('filter_order', 'filter_order_Dir')
->paginated('limitstart', 'limit')
->rows();
$types = Item::all()
->select('DISTINCT(type)')
->whereRaw("type != ''")
->whereRaw("type != 'collection'")
->rows();
// Output the HTML
$this->view
->set('filters', $filters)
->set('rows', $rows)
->set('types', $types)
->display();
}
/**
* Edit a collection
*
* @param object $row
* @return void
*/
public function editTask($row=null)
{
if (!User::authorise('core.edit', $this->_option)
&& !User::authorise('core.create', $this->_option))
{
App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR'));
}
Request::setVar('hidemainmenu', 1);
if (!is_object($row))
{
// Incoming
$id = Request::getArray('id', array(0));
if (is_array($id))
{
$id = (!empty($id) ? $id[0] : 0);
}
$row = Item::oneOrNew($id);
}
if ($row->isNew())
{
$row->set('created_by', User::get('id'));
$row->set('created', Date::toSql());
}
// Output the HTML
$this->view
->set('row', $row)
->setLayout('edit')
->display();
}
/**
* Save an entry
*
* @return void
*/
public function saveTask()
{
// Check for request forgeries
Request::checkToken();
if (!User::authorise('core.edit', $this->_option)
&& !User::authorise('core.create', $this->_option))
{
App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR'));
}
// Incoming
$fields = Request::getArray('fields', array(), 'post');
// Initiate extended database class
$row = Item::oneOrNew($fields['id'])->set($fields);
// Store new content
if (!$row->save())
{
Notify::error($row->getError());
return $this->editTask($row);
}
// Save assets
$assets = Request::getArray('assets', array(), 'post');
$k = 1;
foreach ($assets as $i => $asset)
{
$a = Asset::oneOrNew($asset['id']);
$a->set('type', $asset['type']);
$a->set('item_id', $row->get('id'));
$a->set('ordering', $k);
$a->set('filename', $asset['filename']);
$a->set('state', $a::STATE_PUBLISHED);
if (strtolower($a->get('filename')) == 'http://')
{
if (!$a->get('id'))
{
continue;
}
if (!$a->destroy())
{
Notify::error($a->getError());
continue;
}
}
if (!$a->save())
{
Notify::error($a->getError());
continue;
}
$k++;
}
// Process tags
$row->tag(trim(Request::getString('tags', '')));
Notify::success(Lang::txt('COM_COLLECTIONS_POST_SAVED'));
if ($this->getTask() == 'apply')
{
return $this->editTask($row);
}
// Set the redirect
$this->cancelTask();
}
/**
* Delete one or more entries
*
* @return void
*/
public function removeTask()
{
// Check for request forgeries
Request::checkToken();
if (!User::authorise('core.delete', $this->_option))
{
App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR'));
}
// Incoming
$ids = Request::getArray('id', array());
$ids = (!is_array($ids) ? array($ids) : $ids);
$i = 0;
if (count($ids) > 0)
{
// Loop through all the IDs
foreach ($ids as $id)
{
$entry = Item::oneOrFail(intval($id));
// Delete the entry
if (!$entry->delete())
{
Notify::error($entry->getError());
continue;
}
$i++;
}
}
if ($i)
{
Notify::success(Lang::txt('COM_COLLECTIONS_ITEMS_DELETED'));
}
// Set the redirect
$this->cancelTask();
}
}
|
gpl-2.0
|
gforghetti/jenkins-tomcat-wildbook
|
src/main/java/org/ecocean/SinglePhotoVideo.java
|
7335
|
package org.ecocean;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.ecocean.Util;
import org.ecocean.genetics.TissueSample;
import org.ecocean.Encounter;
import org.ecocean.servlet.ServletUtilities;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
import org.apache.commons.io.FilenameUtils;
public class SinglePhotoVideo extends DataCollectionEvent {
private static final long serialVersionUID = 7999349137348568641L;
private PatterningPassport patterningPassport;
private String filename;
private String fullFileSystemPath;
//use for User objects
String correspondingUsername;
//Use for Story objects
String correspondingStoryID;
/*
private String thumbnailFilename;
private String thumbnailFullFileSystemPath;
*/
private static String type = "SinglePhotoVideo";
private String copyrightOwner;
private String copyrightStatement;
private List<Keyword> keywords;
/**
* Empty constructor required for JDO persistence
*/
public SinglePhotoVideo(){}
/*
* Required constructor for instance creation
*/
public SinglePhotoVideo(String correspondingEncounterNumber, String filename, String fullFileSystemPath) {
super(correspondingEncounterNumber, type);
this.filename = filename;
this.fullFileSystemPath = fullFileSystemPath;
}
public SinglePhotoVideo(String correspondingEncounterNumber, File file) {
super(correspondingEncounterNumber, type);
this.filename = file.getName();
this.fullFileSystemPath = file.getAbsolutePath();
}
public SinglePhotoVideo(Encounter enc, FileItem formFile, String context, String dataDir) throws Exception {
//TODO FUTURE: should use context to find out METHOD of storage (e.g. remote, amazon, etc) and switch accordingly?
super(enc.getEncounterNumber(), type);
String encID = enc.getEncounterNumber();
if ((encID == null) || encID.equals("")) {
throw new Exception("called SinglePhotoVideo(enc) with Encounter missing an ID");
}
//TODO generalize this when we encorporate METHOD?
//File dir = new File(dataDir + File.separator + correspondingEncounterNumber.charAt(0) + File.separator + correspondingEncounterNumber.charAt(1), correspondingEncounterNumber);
File dir = new File(enc.dir(dataDir));
if (!dir.exists()) { dir.mkdirs(); }
//String origFilename = new File(formFile.getName()).getName();
this.filename = ServletUtilities.cleanFileName(new File(formFile.getName()).getName());
File file = new File(dir, this.filename);
this.fullFileSystemPath = file.getAbsolutePath();
formFile.write(file); //TODO catch errors and return them, duh
System.out.println("full path??? = " + this.fullFileSystemPath + " WRITTEN!");
}
/**
* Returns the photo or video represented by this object as a java.io.File
* This is a convenience method.
* @return java.io.File
*/
public File getFile(){
if(fullFileSystemPath!=null){
return (new File(fullFileSystemPath));
}
else{return null;}
}
public String asUrl(Encounter enc, String baseDir) {
return "/" + enc.dir(baseDir) + "/" + this.filename;
}
/*
public File getThumbnailFile(){
if(thumbnailFullFileSystemPath!=null){
return (new File(thumbnailFullFileSystemPath));
}
else{return null;}
}
*/
public String getFilename(){return filename;}
public void setFilename(String newName){this.filename=newName;}
public String getFullFileSystemPath(){return fullFileSystemPath;}
public void setFullFileSystemPath(String newPath){this.fullFileSystemPath=newPath;}
public String getCopyrightOwner(){return copyrightOwner;}
public void setCopyrightOwner(String owner){copyrightOwner=owner;}
public String getCopyrightStatement(){return copyrightStatement;}
public void setCopyrightStatement(String statement){copyrightStatement=statement;}
//public String getThumbnailFilename(){return (this.getDataCollectionEventID()+".jpg");}
/*
public void setThumbnailFilename(String newName){this.thumbnailFilename=newName;}
public String getThumbnailFullFileSystemPath(){return thumbnailFullFileSystemPath;}
public void setThumbnailFullFileSystemPath(String newPath){this.thumbnailFullFileSystemPath=newPath;}
*/
public void addKeyword(Keyword dce){
if(keywords==null){keywords=new ArrayList<Keyword>();}
if(!keywords.contains(dce)){keywords.add(dce);}
}
public void removeKeyword(int num){keywords.remove(num);}
public List<Keyword> getKeywords(){return keywords;}
public void removeKeyword(Keyword num){keywords.remove(num);}
public PatterningPassport getPatterningPassport() {
if (patterningPassport == null) {
patterningPassport = new PatterningPassport();
}
return patterningPassport;
}
public File getPatterningPassportFile() {
File f = this.getFile();
String xmlPath;
String dirPath;
if (f != null) {
dirPath = f.getParent();
xmlPath = dirPath + "/" + this.filename.substring(0,this.filename.indexOf(".")) + "_pp.xml";
} else {
return null; // no xml if no image!
}
File xmlFile = new File(xmlPath);
if (xmlFile.isFile() == Boolean.FALSE) {
return null;
}
return xmlFile;
}
/**
* @param patterningPassport the patterningPassport to set
*/
public void setPatterningPassport(PatterningPassport patterningPassport) {
this.patterningPassport = patterningPassport;
}
public String getCorrespondingUsername(){return correspondingUsername;}
public void setCorrespondingUsername(String username){this.correspondingUsername=username;}
public String getCorrespondingStoryID(){return correspondingStoryID;}
public void setCorrespondingStoryID(String userID){this.correspondingStoryID=userID;}
//background scaling of the image to some target path
// true = doing it (background); false = cannot do it (no external command support; not image)
public boolean scaleTo(String context, int width, int height, String targetPath) {
String cmd = CommonConfiguration.getProperty("imageResizeCommand", context);
if ((cmd == null) || cmd.equals("")) return false;
System.out.println("(( starting image proc");
String sourcePath = this.getFullFileSystemPath();
if (!Shepherd.isAcceptableImageFile(sourcePath)) return false;
ImageProcessor iproc = new ImageProcessor(context, "resize", width, height, sourcePath, targetPath, null);
Thread t = new Thread(iproc);
t.start();
System.out.println("yes. out. ))");
return true;
}
public boolean scaleToWatermark(String context, int width, int height, String targetPath, String watermark) {
String cmd = CommonConfiguration.getProperty("imageWatermarkCommand", context);
if ((cmd == null) || cmd.equals("")) return false;
String sourcePath = this.getFullFileSystemPath();
if (!Shepherd.isAcceptableImageFile(sourcePath)) return false;
ImageProcessor iproc = new ImageProcessor(context, "watermark", width, height, sourcePath, targetPath, watermark);
Thread t = new Thread(iproc);
t.start();
return true;
}
}
|
gpl-2.0
|
cristiantanas/MCS-MobilityGenerator
|
MobilityGenerator.py
|
2112
|
#!/usr/bin/env python
import getopt, sys
CODE_PROGRAM_EXIT = 1
CODE_OPTIONS_ERROR = -1
CODE_SHORT_HELP = -2
def usage():
print "-------------------------------------------------------------------------------------"
print "MobilityGenerator.py"
print "Year 2015, v1.0"
print ""
print "Python program that generates the necessary traces in order to simulate an incident "
print "generation experiment given a particular scenario. It generates both user's mobility "
print "and incident events."
print ""
print "Parameters:"
print " # --model [ -m ] : Mobility model used to generate the trace file"
print " # --params [ -p ] : Path of the file containing simulation parameters"
print ""
print "Use examples:"
print " * MobilityGenerator.py --model=GraphWalk --params=barcelona.params"
print " * MobilityGenerator.py -m GraphWalk -p barcelona.params"
print "------------------------------------------------------------------------------------"
sys.exit( CODE_PROGRAM_EXIT )
def generateGraphWalkMobilityModel(withConfigurationFile):
from graphwalk.GraphWalkMobilityModel import generateTrace
generateTrace( withConfigurationFile )
AVAILABLE_MOBILITY_MODELS = {"GraphWalk": generateGraphWalkMobilityModel}
def callMobilityModelTraceGenerator(forModel, withConfigurationFile):
AVAILABLE_MOBILITY_MODELS.get( forModel, lambda: None )( withConfigurationFile )
def main():
# Get command line parameters.
try:
opts = getopt.getopt( sys.argv[1:], "m:p:", ["model=", "params="] )
except getopt.GetoptError as err:
print str( err )
usage()
sys.exit( CODE_OPTIONS_ERROR )
# If no options specified, print short help.
if len( opts[0] ) < 1:
usage()
sys.exit( CODE_SHORT_HELP )
# Parse command line parameters.
mobilityModel = ''
configurationFile = ''
for optname, arg in opts[0]:
if optname in ( "-m", "--model" ):
mobilityModel = arg
elif optname in ( "-p", "--params" ):
configurationFile = arg
else:
assert False, "Invalid parameter name"
callMobilityModelTraceGenerator(mobilityModel, configurationFile)
if __name__ == '__main__':
main()
|
gpl-2.0
|
rmbinder/admidio
|
adm_program/system/classes/conditionparser.php
|
19497
|
<?php
/**
***********************************************************************************************
* @copyright 2004-2016 The Admidio Team
* @see https://www.admidio.org/
* @license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License v2.0 only
***********************************************************************************************
*/
/**
* @class ConditionParser
* @brief Creates from a custom condition syntax a sql condition
*
* The user can write a condition in a special syntax. This class will parse
* that condition and creates a valid SQL statement which can be used in
* another SQL statement to select data with these conditions.
* This class uses AdmExceptions when an error occurred. Make sure you catch these
* exceptions when using the class.
* @par Examples
* @code // create a valid SQL condition out of the special syntax
* $parser = new ConditionParser();
* $sqlCondition = $parser->makeSqlStatement('> 5 AND <= 100', 'usd_value', 'int');
* $sql = 'SELECT * FROM '.TBL_USER_DATA.' WHERE usd_id > 0 AND '.$sqlCondition; @endcode
*/
class ConditionParser
{
private $srcCond; ///< The source condition with the user specific condition
private $destCond; ///< The destination string with the valid sql statement
private $srcCondArray; ///< An array from the string @b mSrcCond where every char is one array element
private $notExistsSql; ///< Stores the sql statement if a record should not exists when user wants to exclude a column
private $openQuotes; ///< Flag if there is a open quote in this condition that must be closed before the next condition will be parsed
/**
* constructor that will initialize variables
*/
public function __construct()
{
$this->srcCond = '';
$this->destCond = '';
$this->srcCondArray = array();
$this->notExistsSql = '';
$this->openQuotes = false;
}
/**
* Starts the "DestCondition"
* @param string $columnType The type of the column. Valid types are @b string, @b int, @b date and @b checkbox
* @param string $columnName The name of the database column for which the condition should be created
* @param string $sourceCondition The user condition string
* @return bool Returns true if "mDestCondition" is complete
*/
private function startDestCond($columnType, $columnName, $sourceCondition)
{
$this->destCond = ' AND '; // Bedingungen fuer das Feld immer mit UND starten
if ($columnType === 'string')
{
$this->destCond .= '( UPPER(' . $columnName . ') ';
}
elseif ($columnType === 'checkbox')
{
// Sonderfall !!!
// bei einer Checkbox kann es nur 1 oder 0 geben und keine komplizierten Verknuepfungen
if ($sourceCondition === '1')
{
$this->destCond .= $columnName . ' = 1 ';
}
else
{
$this->destCond .= '(' . $columnName . ' IS NULL OR ' . $columnName . ' = 0) ';
}
return true;
}
// $columnType = "int" or "date"
else
{
$this->destCond .= '( ' . $columnName . ' ';
}
return false;
}
/**
* Ends the "DestCondition"
*/
private function endDestCond()
{
if ($this->openQuotes)
{
// allways set quote marks for a value because some fields are a varchar in db
// but should only filled with integer
$this->destCond .= '\' ';
}
$this->destCond .= ' ) ';
}
/**
* @param string $columnType
* @param string $sourceCondition
* @return bool Returns true if date search and false if age search
*/
private static function isDateSearch($columnType, $sourceCondition)
{
$sourceCondition = admStrToUpper($sourceCondition);
return $columnType === 'date' && (strpos($sourceCondition, 'J') !== false || strpos($sourceCondition, 'Y') !== false);
}
/**
* Creates a valid date format @b YYYY-MM-DD for the SQL statement
* @param string $date The unformated date from user input e.g. @b 12.04.2012
* @param string $operator The actual operator for the @b date parameter
* @return string String with a SQL valid date format @b YYYY-MM-DD or empty string
*/
private function getFormatDate($date, $operator)
{
global $gPreferences;
// if last char is Y or J then user searches for age
$lastDateChar = admStrToUpper(substr($date, -1));
if ($lastDateChar === 'J' || $lastDateChar === 'Y')
{
$ageCondition = '';
$dateObj = new DateTime();
$years = new DateInterval('P' . substr($date, 0, -1) . 'Y');
$oneYear = new DateInterval('P1Y');
$oneDay = new DateInterval('P1D');
$dateObj->sub($years);
switch ($operator)
{
case '=':
// first remove = from destination condition
$this->destCond = substr($this->destCond, 0, -4);
// now compute the dates for a valid birthday with that age
$dateTo = $dateObj->format('Y-m-d');
$dateObj->sub($oneYear)->add($oneDay);
$dateFrom = $dateObj->format('Y-m-d');
$ageCondition = ' BETWEEN \'' . $dateFrom . '\' AND \'' . $dateTo . '\'';
$this->openQuotes = false;
break;
case '}':
// search for dates that are older than the age
// because the age itself takes 1 year we must add 1 year and 1 day to age
$dateObj->add($oneYear)->add($oneDay);
$ageCondition = $dateObj->format('Y-m-d');
break;
case '{':
// search for dates that are younger than the age
// we must add 1 day to the date because the day itself belongs to the age
$dateObj->add($oneDay);
$ageCondition = $dateObj->format('Y-m-d');
break;
}
return $ageCondition;
}
// validate date and return it in database format
if ($date !== '')
{
$dateObject = DateTime::createFromFormat($gPreferences['system_date'], $date);
if ($dateObject !== false)
{
return $dateObject->format('Y-m-d');
}
}
return '';
}
/**
* Stores an sql statement that checks if a record in a table does exists or not exists.
* This must bei a full subselect that starts with SELECT. The statement is used if
* a condition with EMPTY or NOT EMPTY is used.
* @param string $sqlStatement String with the full subselect
* @par Examples
* @code $parser->setNotExistsStatement('SELECT 1 FROM adm_user_data WHERE usd_usr_id = 1 AND usd_usf_id = 9'); @endcode
*/
public function setNotExistsStatement($sqlStatement)
{
$this->notExistsSql = $sqlStatement;
}
/**
* Creates from a user defined condition a valid SQL condition
* @param string $sourceCondition The user condition string
* @param string $columnName The name of the database column for which the condition should be created
* @param string $columnType The type of the column. Valid types are @b string, @b int, @b date and @b checkbox
* @param string $fieldName The name of the profile field. This is used for error output to the end user
* @throws AdmException LST_NOT_VALID_DATE_FORMAT
* LST_NOT_NUMERIC
* @return string Returns a valid SQL string with the condition for that column
*/
public function makeSqlStatement($sourceCondition, $columnName, $columnType, $fieldName)
{
$conditionComplete = $this->startDestCond($columnType, $columnName, $sourceCondition);
if ($conditionComplete)
{
return $this->destCond;
}
$this->openQuotes = false; // set to true if quotes for conditions are open
$startCondition = true; // gibt an, dass eine neue Bedingung angefangen wurde
$newCondition = true; // in Stringfeldern wird nach einem neuen Wort gesucht -> neue Bedingung
$startOperand = false; // gibt an, ob bei num. oder Datumsfeldern schon <>= angegeben wurde
$date = ''; // Variable speichert bei Datumsfeldern das gesamte Datum
$operator = '='; // saves the actual operator, if no operator is set then = will be default
$this->makeStandardCondition($sourceCondition);
$this->srcCondArray = str_split($this->srcCond);
// Zeichen fuer Zeichen aus dem Bedingungsstring wird hier verarbeitet
foreach ($this->srcCondArray as $character)
{
if ($character === '&' || $character === '|')
{
if ($newCondition)
{
// neue Bedingung, also Verknuepfen
if ($character === '&')
{
$this->destCond .= ' AND ';
}
elseif ($character === '|')
{
$this->destCond .= ' OR ';
}
// Feldname noch dahinter
if ($columnType === 'string')
{
$this->destCond .= ' UPPER(' . $columnName . ') ';
}
else
{
$this->destCond .= ' ' . $columnName . ' ';
}
$startCondition = true;
}
}
// Verleich der Werte wird hier verarbeitet
elseif (in_array($character, array('=', '!', '_', '#', '{', '}', '[', ']'), true))
{
// save actual operator for later use
$operator = $character;
if (!$startCondition)
{
$this->destCond .= ' AND ' . $columnName . ' ';
$startCondition = true;
}
switch ($character)
{
case '=':
if ($columnType === 'string')
{
$this->destCond .= ' LIKE ';
}
else
{
$this->destCond .= ' = ';
}
break;
case '!':
if ($columnType === 'string')
{
$this->destCond .= ' NOT LIKE ';
}
else
{
$this->destCond .= ' <> ';
}
break;
case '_':
$this->destCond .= ' IS NULL ';
if ($this->notExistsSql !== '')
{
$this->destCond .= ' OR NOT EXISTS (' . $this->notExistsSql . ') ';
}
break;
case '#':
$this->destCond .= ' IS NOT NULL ';
if ($this->notExistsSql !== '')
{
$this->destCond .= ' OR EXISTS (' . $this->notExistsSql . ') ';
}
break;
case '{':
// bastwe: invert condition on age search
if (self::isDateSearch($columnType, $sourceCondition))
{
$this->destCond .= ' > ';
}
else
{
$this->destCond .= ' < ';
}
break;
case '}':
// bastwe: invert condition on age search
if (self::isDateSearch($columnType, $sourceCondition))
{
$this->destCond .= ' < ';
}
else
{
$this->destCond .= ' > ';
}
break;
case '[':
// bastwe: invert condition on age search
if (self::isDateSearch($columnType, $sourceCondition))
{
$this->destCond .= ' >= ';
}
else
{
$this->destCond .= ' <= ';
}
break;
case ']':
// bastwe: invert condition on age search
if (self::isDateSearch($columnType, $sourceCondition))
{
$this->destCond .= ' <= ';
}
else
{
$this->destCond .= ' >= ';
}
break;
default:
$this->destCond .= $character;
}
if ($character !== '_' && $character !== '#')
{
// allways set quote marks for a value because some fields are a varchar in db
// but should only filled with integer
$this->destCond .= ' \'';
$this->openQuotes = true;
$startOperand = true;
}
}
elseif ($character === ' ')
{
// pruefen, ob ein neues Wort anfaengt
if (!$newCondition)
{
// if date column than the date will be saved in $date.
// This variable must then be parsed and changed in a valid database format
if ($columnType === 'date' && $date !== '')
{
$formatDate = $this->getFormatDate($date, $operator);
if ($formatDate !== '')
{
$this->destCond .= $formatDate;
}
else
{
throw new AdmException('LST_NOT_VALID_DATE_FORMAT', $fieldName);
}
$date = '';
}
if ($this->openQuotes)
{
// allways set quote marks for a value because some fields are a varchar in db
// but should only filled with integer
$this->destCond .= '\' ';
$this->openQuotes = false;
}
$newCondition = true;
}
}
else
{
// neues Suchwort, aber noch keine Bedingung
if ($newCondition && !$startCondition)
{
if ($columnType === 'string')
{
$this->destCond .= ' AND UPPER(' . $columnName . ') ';
}
else
{
$this->destCond .= ' AND ' . $columnName . ' = ';
}
$this->openQuotes = false;
}
elseif ($newCondition && !$startOperand)
{
// first condition of these column
if ($columnType === 'string')
{
$this->destCond .= ' LIKE \'';
}
else
{
$this->destCond .= ' = \'';
}
$this->openQuotes = true;
}
// Zeichen an Zielstring dranhaengen
if ($columnType === 'date')
{
$date .= $character;
}
elseif ($columnType === 'int' && !is_numeric($character))
{
// if numeric field than only numeric characters are allowed
throw new AdmException('LST_NOT_NUMERIC', $fieldName);
}
else
{
$this->destCond .= $character;
}
$newCondition = false;
$startCondition = false;
}
}
// if date column than the date will be saved in $date.
// This variable must then be parsed and changed in a valid database format
if ($columnType === 'date' && $date !== '')
{
$formatDate = $this->getFormatDate($date, $operator);
if ($formatDate !== '')
{
$this->destCond .= $formatDate;
}
else
{
throw new AdmException('LST_NOT_VALID_DATE_FORMAT', $fieldName);
}
}
$this->endDestCond();
return $this->destCond;
}
/**
* Replace different user conditions with predefined chars that
* represents a special condition e.g. @b ! represents @b != and @b <>
* @param string $sourceCondition The user condition string
* @return string String with the predefined chars for conditions
*/
public function makeStandardCondition($sourceCondition)
{
global $gL10n;
$this->srcCond = admStrToUpper(trim($sourceCondition));
$replaceArray = array(
'*' => '%',
// valid 'not null' is '#'
admStrToUpper($gL10n->get('SYS_NOT_EMPTY')) => ' # ',
' NOT NULL ' => ' # ',
// valid 'null' is '_'
admStrToUpper($gL10n->get('SYS_EMPTY')) => ' _ ',
' NULL ' => ' _ ',
// valid 'is not' is '!'
'{}' => ' ! ',
'!=' => ' ! ',
// valid 'is' is '='
'==' => ' = ',
' LIKE ' => ' = ',
' IS ' => ' = ',
' IST ' => ' = ',
// valid 'less than' is '['
'{=' => ' [ ',
'={' => ' [ ',
// valid 'greater than' is ']'
'}=' => ' ] ',
'=}' => ' ] ',
// valid 'and' is '&'
' AND ' => ' & ',
' UND ' => ' & ',
'&&' => ' & ',
'+' => ' & ',
// valid 'or' is '|'
' OR ' => ' | ',
' ODER ' => ' | ',
'||' => ' | '
);
$this->srcCond = str_replace(array_keys($replaceArray), array_values($replaceArray), $this->srcCond);
return $this->srcCond;
}
}
|
gpl-2.0
|
pjlong/business-time
|
manage.py
|
256
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "business_time.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
gpl-2.0
|
vivianacerrutti/wordpress
|
wp-content/themes/infoway/front-page.php
|
6479
|
<?php
/**
* The template for displaying front page pages.
*
*/
?>
<?php get_header(); ?>
<!--Start Slider Wrapper-->
<div class="slider_wrapper">
<div id="featured">
<!-- First Content -->
<div id="fragment-1" class="ui-tabs-panel" style="">
<?php if (infoway_get_option('infoway_slideimage1') != '') { ?>
<a href="<?php echo infoway_get_option('infoway_slidelink1'); ?>" >
<img src="<?php echo infoway_get_option('infoway_slideimage1'); ?>" alt="Slide 1"/>
</a>
<?php } else { ?>
<a href="#"><img src="<?php echo get_template_directory_uri(); ?>/images/1.jpg" alt=""></a>
<?php } ?>
</div>
</div>
<div class="slider_shadow"></div>
<div class="infotag">
<?php if (infoway_get_option('infoway_main_heading') != '') { ?>
<?php echo stripslashes(infoway_get_option('infoway_main_heading')); ?>
<?php } else { ?>
<p><?php _e('No Cost, Free To Use & With Single Click Installation. Use Infoway Now & Make beautiful Website & Astonish Everyone.','infoway'); ?></p>
<?php } ?>
</div>
</div>
<!--End Slider wrapper-->
<div class="clear"></div>
<div class="contentbox">
<div class="grid_16 alpha">
<div class="feturebox">
<div class="featurebox_inner">
<!-- <div class="grid_5 alpha">-->
<div class="featurebox_desc first">
<?php if (infoway_get_option('infoway_firsthead') != '') { ?>
<h2><a href="<?php echo infoway_get_option('infoway_link1'); ?>"><?php echo stripslashes(infoway_get_option('infoway_firsthead')); ?></a></h2>
<?php } else { ?>
<h2><a href="#"><?php _e('Easy to Customize','infoway'); ?></a></h2>
<?php } ?>
<?php if (infoway_get_option('infoway_firstdesc') != '') { ?>
<p><?php echo stripslashes(infoway_get_option('infoway_firstdesc')); ?></p>
<?php } else { ?>
<p><?php _e('An Infoway is a WordPress theme which is easily customizable. You can customize the theme as per your requirement. The theme provides an exiting benefit to your websites. It also features a clean design and sure you will be more happier to use it','infoway'); ?></p>
<?php } ?>
<a href="<?php echo infoway_get_option('infoway_link1'); ?>" class="readmore"><?php _e( 'Read More', 'infoway' ); ?> <span class="button-tip"></span></a></div>
<!-- </div>-->
<!-- <div class="grid_5">-->
<div class="featurebox_desc second">
<?php if (infoway_get_option('infoway_secondhead') != '') { ?>
<h2><a href="<?php echo infoway_get_option('infoway_link2'); ?>"><?php echo stripslashes(infoway_get_option('infoway_secondhead')); ?></a></h2>
<?php } else { ?>
<h2><a href="<?php echo infoway_get_option('infoway_link2'); ?>"><?php _e('Build Site Quickly','infoway'); ?></a></h2>
<?php } ?>
<?php if (infoway_get_option('infoway_seconddesc') != '') { ?>
<p><?php echo stripslashes(infoway_get_option('infoway_seconddesc')); ?></p>
<?php } else { ?>
<p><?php _e('The Infoway Wordpress Theme is highly optimized for speed, so that your website loads faster as compared to others. The themes is compatible with all major browsers. Also it provides eye captivating appearance to your website.','infoway'); ?></p>
<?php } ?>
<a href="<?php echo infoway_get_option('infoway_link2'); ?>" class="readmore"><?php _e( 'Read More', 'infoway' ); ?> <span class="button-tip"></span></a></div>
<!-- </div>-->
<!-- <div class="grid_5 omega">-->
<div class="featurebox_desc third">
<?php if (infoway_get_option('infoway_thirdhead') != '') { ?>
<h2><a href="<?php echo infoway_get_option('infoway_link3'); ?>"><?php echo stripslashes(infoway_get_option('infoway_thirdhead')); ?></a></h2>
<?php } else { ?>
<h2><a href="<?php echo infoway_get_option('infoway_link3'); ?>"><?php _e('Search Optimized','infoway'); ?></a></h2>
<?php } ?>
<?php if (infoway_get_option('infoway_thirddesc') != '') { ?>
<p><?php echo stripslashes(infoway_get_option('infoway_thirddesc')); ?></p>
<?php } else { ?>
<p><?php _e('A Premium WordPress Theme with single click installation. Just a click and your website is ready to use. Infoway theme is better suitable for any business or personal website. The theme is compatible with various niches.','infoway'); ?></p>
<?php } ?>
<a href="<?php echo infoway_get_option('infoway_link3'); ?>" class="readmore"><?php _e( 'Read More', 'infoway' ); ?> <span class="button-tip"></span></a></div>
<!--</div>-->
</div>
</div>
<div class="clear"></div>
</div>
<div class="grid_8 omega">
<div class="signinwidgetarea">
<?php if (is_active_sidebar('home-page-right-feature-widget-area')) : ?>
<div class="signinformbox1 widget">
<?php dynamic_sidebar('home-page-right-feature-widget-area'); ?>
</div>
</div>
<?php else : ?>
<div class="signinformbox1">
<div class="signupForm">
<img src="<?php echo get_template_directory_uri(); ?>/images/widgit-area.png" />
</div>
</div>
</div>
<?php endif; ?>
</div>
</div>
<div class="testimonial">
<div class="grid_24">
<?php if (infoway_get_option('infoway_testimonial_head') != '') { ?>
<h2><?php echo stripslashes(infoway_get_option('infoway_testimonial_head')); ?></h2>
<?php } else { ?>
<h2><?php _e('What Our Clients Say','infoway'); ?></h2>
<?php } ?>
<?php if (infoway_get_option('infoway_testimonial_desc') != '') { ?>
<p><?php echo stripslashes(infoway_get_option('infoway_testimonial_desc')); ?></p>
<?php } else { ?>
<p><?php _e('Infoway was one of the most easiest theme to work with. My Clients loved their websites built using Infoway Theme. I highly recommend it to anyone want to build a business site.','infoway'); ?></p>
<?php } ?>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
|
gpl-2.0
|
sektioneins/sandbox_toolkit
|
sb2dot/outputdot.py
|
2858
|
#
# sb2dot - a sandbox binary profile to dot convertor for iOS 9 and OS X 10.11
# Copyright (C) 2015 Stefan Esser / SektionEins GmbH <stefan@sektioneins.de>
# uses and extends code from Dionysus Blazakis with his permission
#
# module: outputdot.py
# task: cheap .dot file generator
#
# 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.
#
import os
def dump_node_to_dot(g, u, visited):
if visited.has_key(u):
return ""
tag = g.getTag(u)
tag = str(tag)
tag = tag.replace("\\", "\\\\")
tag = tag.replace("\"", "\\\"")
tag = tag.replace("\0", "")
edges = list(g.edges[u])
visited[u] = True;
out = "n%u [label=\"%s\"];\n" % (u, tag)
if len(edges) == 0:
return out
out+= "n%u -> n%u [color=\"green\"];\n" % (u, edges[0]);
out+= "n%u -> n%u [color=\"red\"];\n" % (u, edges[1]);
out+=dump_node_to_dot(g, edges[0], visited)
out+=dump_node_to_dot(g, edges[1], visited)
return out;
def dump_to_dot(g, offset, name, cleanname, profile_name):
u = offset * 8
visited = {}
orig_name = name
if len(name) > 128:
name = name[0:128]
name = name + ".dot"
name = name.replace("*", "")
name = name.replace(" ", "_")
cleanname = cleanname.replace("\\", "\\\\")
cleanname = cleanname.replace("\"", "\\\"")
cleanname = cleanname.replace("\0", "")
profile_name = os.path.basename(profile_name)
profile_name = profile_name.replace("\\", "\\\\")
profile_name = profile_name.replace("\"", "\\\"")
profile_name = profile_name.replace("\0", "")
f = open(profile_name + "_" + name, 'w')
print "[+] generating " + profile_name + "_" + name
f.write("digraph sandbox_decision { rankdir=HR; labelloc=\"t\";label=\"sandbox decision graph for\n\n%s\n\nextracted from %s\n\n\n\"; \n" % (cleanname, profile_name))
out = "n0 [label=\"%s\";shape=\"doubleoctagon\"];\n" % (cleanname)
out+= "n0 -> n%u [color=\"black\"];\n" % (u);
out = out + dump_node_to_dot(g, u, visited)
f.write(out)
f.write("} \n")
f.close()
|
gpl-2.0
|
AlekSi/Jabbin
|
src/tools/yastuff/yawidgets/yawindowbackground.cpp
|
5613
|
/*
* yawindowbackground.cpp
* Copyright (C) 2008 Yandex LLC (Michail Pishchagin)
*
* 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "yawindowbackground.h"
#include <QDir>
#include <QPainter>
#include "psioptions.h"
#include "yavisualutil.h"
YaWindowBackground::Background::Background(const QString& fileName)
: fileName_(fileName)
{
static QMap<QString, QColor> tabBackgroundColors;
if (tabBackgroundColors.isEmpty()) {
tabBackgroundColors["carbon.png"] = QColor(0xE5, 0xE5, 0xE5);
tabBackgroundColors["orange.png"] = QColor(0xFF, 0xF4, 0xC2);
tabBackgroundColors["pinky.png"] = QColor(0xFF, 0xDB, 0xE5);
tabBackgroundColors["seawater.png"] = QColor(0xDC, 0xFF, 0xDE);
tabBackgroundColors["silver.png"] = QColor(0xDA, 0xD0, 0xE8);
tabBackgroundColors["sky.png"] = QColor(0xD5, 0xFC, 0xFF);
tabBackgroundColors["office.png"] = Ya::VisualUtil::blueBackgroundColor();
}
top_ = QPixmap(fileName);
bottom_ = top_.copy(0, top_.height() - 1,
top_.width(), 1);
QFileInfo fi(fileName);
Q_ASSERT(tabBackgroundColors.contains(fi.fileName()));
tabBackgroundColor_ = tabBackgroundColors[fi.fileName()];
}
static QList<YaWindowBackground::Mode> initializedModes_;
QVector<YaWindowBackground::Background> YaWindowBackground::backgrounds_;
int YaWindowBackground::officeBackground_ = -1;
YaWindowBackground::YaWindowBackground()
{
init(Random);
}
YaWindowBackground::YaWindowBackground(Mode mode)
{
init(mode);
}
QDir YaWindowBackground::dir()
{
return QDir(":images/chat-window");
}
QString YaWindowBackground::firstBackground()
{
return dir().absoluteFilePath("orange.png");
}
QString YaWindowBackground::officeBackground()
{
return dir().absoluteFilePath("office.png");
}
QString YaWindowBackground::randomBackground()
{
QStringList nameFilters;
nameFilters << "*.png";
QStringList entries = dir().entryList(nameFilters);
QFileInfo fi(officeBackground());
entries.remove(fi.fileName());
return dir().absoluteFilePath(entries[rand() % entries.count()]);
}
void YaWindowBackground::init(Mode mode)
{
mode_ = mode;
background_ = -1;
if (mode == Random) {
init(randomBackground());
}
else if (mode == Roster) {
init(firstBackground());
}
else if (mode == Chat) {
// first opened chat uses firstBackground()
if (!initializedModes_.contains(mode)) {
initializedModes_.append(mode);
init(firstBackground());
mode_ = ChatFirst;
}
else {
init(randomBackground());
}
}
Q_ASSERT(background_ >= 0);
}
void YaWindowBackground::ensureBackgrounds()
{
if (!backgrounds_.isEmpty())
return;
QStringList nameFilters;
nameFilters << "*.png";
foreach(QString entry, dir().entryList(nameFilters)) {
Background background(dir().absoluteFilePath(entry));
if (background.fileName().startsWith("office") && background.fileName() != officeBackground()) {
Q_ASSERT(officeBackground().startsWith("office"));
continue;
}
if (background.fileName() == officeBackground()) {
officeBackground_ = backgrounds_.count();
}
backgrounds_.append(background);
}
Q_ASSERT(officeBackground_ != -1);
}
void YaWindowBackground::init(const QString& fileName)
{
ensureBackgrounds();
for (int i = 0; i < backgrounds_.count(); ++i) {
if (backgrounds_[i].fileName() == fileName) {
background_ = i;
break;
}
}
Q_ASSERT(background_ >= 0);
}
const YaWindowBackground::Background& YaWindowBackground::background() const
{
currentBackground_ = backgrounds_[background_];
if (mode_ == Chat || mode_ == ChatFirst) {
QString chatBackground = PsiOptions::instance()->getOption("options.ya.chat-background").toString();
if (chatBackground != "random") {
foreach(Background b, backgrounds_) {
QFileInfo fi(b.fileName());
if (fi.fileName() == chatBackground) {
currentBackground_ = b;
break;
}
}
}
}
else {
if (PsiOptions::instance()->getOption("options.ya.office-background").toBool()) {
return backgrounds_[officeBackground_];
}
}
return currentBackground_;
}
void YaWindowBackground::paint(QPainter* p, const QRect& rect, bool isActiveWindow) const
{
QRect pixmapRect(rect);
pixmapRect.setHeight(background().top().height());
p->save();
if (!isActiveWindow) {
p->fillRect(rect, Qt::white);
p->setOpacity(0.75);
}
QRect plainRect(rect);
plainRect.setTop(pixmapRect.bottom());
p->drawTiledPixmap(pixmapRect, background().top());
p->drawTiledPixmap(plainRect, background().bottom());
p->restore();
}
QString YaWindowBackground::name() const
{
QFileInfo fi(background().fileName());
return fi.fileName();
}
QColor YaWindowBackground::tabBackgroundColor() const
{
return background().tabBackgroundColor();
}
QStringList YaWindowBackground::funnyBackgrounds()
{
QStringList result;
foreach(Background b, backgrounds_) {
if (b.fileName() == officeBackground())
continue;
QFileInfo fi(b.fileName());
result << fi.fileName();
}
return result;
}
|
gpl-2.0
|
misto/worked
|
lib/worked/graph.rb
|
753
|
require 'rubygems'
require 'gruff'
require 'worked/reader'
module Worked
class Graph
def self.create_weekly entries, output_file
create(entries, output_file)
end
def self.create_daily entries, output_file
create(entries, output_file)
end
private
def self.create entries, output_file
g = Gruff::Bar.new
g.title = "My Work Hours"
g.y_axis_increment = 2
g.y_axis_label = "Hours"
g.x_axis_label = "Week of the Year"
g.data("Total: #{entries.sum{|e| e.hours.to_f}.to_i.to_s} Hours", entries.collect {|e| e.hours.to_f})
g.minimum_value = 0
g.labels = entries.inject({}) {|h, e| h.merge( { h.size => e.date.to_s }) }
g.write output_file
end
end
end
|
gpl-2.0
|
gburca/mediatomb
|
src/iohandler/file_io_handler.cc
|
2548
|
/*MT*
MediaTomb - http://www.mediatomb.cc/
file_io_handler.cc - this file is part of MediaTomb.
Copyright (C) 2005 Gena Batyan <bgeradz@mediatomb.cc>,
Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc>
Copyright (C) 2006-2010 Gena Batyan <bgeradz@mediatomb.cc>,
Sergey 'Jin' Bostandzhyan <jin@mediatomb.cc>,
Leonhard Wimmer <leo@mediatomb.cc>
MediaTomb 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.
MediaTomb 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
version 2 along with MediaTomb; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
$Id$
*/
/// \file file_io_handler.cc
#include "file_io_handler.h" // API
#include <cstdio>
#include <utility>
#include "cds_objects.h"
#include "server.h"
FileIOHandler::FileIOHandler(fs::path filename)
: filename(std::move(filename))
, f(nullptr)
{
}
void FileIOHandler::open(enum UpnpOpenFileMode mode)
{
if (mode == UPNP_READ) {
#ifdef __linux__
f = ::fopen(filename.c_str(), "rbe");
#else
f = ::fopen(filename.c_str(), "rb");
#endif
} else {
throw_std_runtime_error("open: UpnpOpenFileMode mode not supported");
}
if (f == nullptr) {
throw_std_runtime_error("failed to open: " + filename.string());
}
}
size_t FileIOHandler::read(char* buf, size_t length)
{
size_t ret = 0;
ret = fread(buf, sizeof(char), length, f);
if (ret == 0) {
if (feof(f))
return 0;
if (ferror(f))
return -1;
}
return ret;
}
size_t FileIOHandler::write(char* buf, size_t length)
{
size_t ret = 0;
ret = fwrite(buf, sizeof(char), length, f);
return ret;
}
void FileIOHandler::seek(off_t offset, int whence)
{
if (fseeko(f, offset, whence) != 0) {
throw_std_runtime_error("fseek failed");
}
}
off_t FileIOHandler::tell()
{
return ftello(f);
}
void FileIOHandler::close()
{
if (fclose(f) != 0) {
throw_std_runtime_error("fclose failed");
}
f = nullptr;
}
|
gpl-2.0
|
xabiamu/Daltonic
|
src/es/capsule/daltonic/MainActivity.java
|
846
|
package es.capsule.daltonic;
import java.nio.IntBuffer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap bmp = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
IntBuffer buffer = IntBuffer.allocate(bmp.getWidth() * bmp.getHeight());
buffer.rewind();
while ( buffer.position() < buffer.limit() ) {
buffer.put( Color.BLUE );
}
buffer.rewind();
bmp.copyPixelsFromBuffer(buffer);
ImageView view = new ImageView(this);
view.setImageBitmap(bmp);
setContentView(view);
}
}
|
gpl-2.0
|
MaxKellermann/xbmc
|
xbmc/threads/platform/ThreadImpl.cpp
|
1055
|
/*
* Copyright (C) 2005-2013 Team XBMC
* http://kodi.tv
*
* 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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#if (defined TARGET_POSIX)
#include "threads/platform/pthreads/ThreadImpl.cpp"
#if defined(TARGET_DARWIN_IOS)
#include "threads/platform/darwin/ThreadSchedImpl.cpp"
#else
#include "threads/platform/linux/ThreadSchedImpl.cpp"
#endif
#elif (defined TARGET_WINDOWS)
#include "threads/platform/win/ThreadImpl.cpp"
#endif
|
gpl-2.0
|
FernandoS27/dynarmic
|
src/backend_x64/hostloc.cpp
|
647
|
/* This file is part of the dynarmic project.
* Copyright (c) 2016 MerryMage
* This software may be used and distributed according to the terms of the GNU
* General Public License version 2 or any later version.
*/
#include <xbyak.h>
#include "backend_x64/hostloc.h"
namespace Dynarmic {
namespace BackendX64 {
Xbyak::Reg64 HostLocToReg64(HostLoc loc) {
ASSERT(HostLocIsGPR(loc));
return Xbyak::Reg64(static_cast<int>(loc));
}
Xbyak::Xmm HostLocToXmm(HostLoc loc) {
ASSERT(HostLocIsXMM(loc));
return Xbyak::Xmm(static_cast<int>(loc) - static_cast<int>(HostLoc::XMM0));
}
} // namespace BackendX64
} // namespace Dynarmic
|
gpl-2.0
|
kstover/tmnt-tutorial
|
admin.js
|
73
|
jQuery( document ).ready( function( $ ) {
/**
* JS goes here
*/
} );
|
gpl-2.0
|
mattsteele/garbanzo.dev
|
wp-content/plugins/store-locator-le/include/class.themes.admin.php
|
16366
|
<?php
/**
* The wpCSL Themes Admin Class
*
* @package wpCSL\Themes\Admin
* @author Lance Cleveland <lance@charlestonsw.com>
* @copyright 2014 Charleston Software Associates, LLC
*
*/
class PluginThemeAdmin {
//-------------------------------------
// Properties
//-------------------------------------
/**
* The theme CSS directory, absolute.
*
* @var string $css_dir
*/
public $css_dir;
/**
* The theme CSS URL, absolute.
*
* @var string $css_url
*/
public $css_url;
/**
* The current theme slug.
*
* @var string $current_slug
*/
private $current_slug;
/**
* Plugin notifications system.
*
* @var \wpCSL_notifications__slplus $notifications
*/
public $notifications;
/**
* The CSS and name space prefix for the plugin.
*
* @var string $prefix
*/
public $prefix;
/**
* The base SLPlus object.
*
* @var \SLPlus
*/
public $slplus;
/**
* Full web address to the support web pages.
*
* @var string $support_url
*/
private $support_url;
/**
* A named array containing meta data about the CSS theme.
*
* @var mixed[] $themeDetails
*/
private $themeDetails;
/**
* The array of theme meta data option fields in slug => full_text format.
*
* @var mixed[] $theme_options_fields
*/
private $theme_option_fields;
//-------------------------------------
// Methods
//-------------------------------------
/**
* Theme constructor.
*
* @param mixed[] $params named array of properties, only set if property exists.
*/
function __construct($params) {
foreach ($params as $property => $value) {
if ( property_exists($this,$property) ) { $this->$property = $value; }
}
}
/**
* Build an HTML string to show under the theme selection box.
*
* @return string
*/
private function createstring_ThemeDetails() {
$HTML = "<div id='{$this->current_slug}_details' class='theme_details'>";
// Description
//
$HTML .= $this->slplus->helper->create_SubheadingLabel(__('About This Theme','csa-slplus'));
if ( empty ( $this->themeDetails[$this->current_slug]['description'] ) ) {
$HTML .= __('No description has been set for this theme.','csa-slplus');
} else {
$HTML .= $this->themeDetails[$this->current_slug]['description'];
}
$HTML .=
'<p>' .
__('Learn more about changing the Store Locator Plus interface via the ' , 'csa-slplus') .
sprintf(
'<a href="%s" target="csa">%s</a>',
$this->support_url . 'user-experience/view/themes-custom-css/',
__('Custom Themes documentation.','csa-slplus')
) .
'</p>';
// Add On Packs
//
if ( ! empty( $this->themeDetails[$this->current_slug]['add-ons'] ) ) {
// List The Add On Packs Wanted
//
$HTML.= $this->slplus->helper->create_SubheadingLabel(__('Add On Packs','csa-slplus'));
$active_HTML = '';
$inactive_HTML = '';
$this->slplus->createobject_AddOnManager();
$addon_list = explode(',',$this->themeDetails[$this->current_slug]['add-ons']);
foreach ($addon_list as $slug) {
$slug = trim(strtolower($slug));
if ( isset( $this->slplus->add_ons->available[$slug] ) ) {
// Show Active Add Ons
//
if ( $this->slplus->add_ons->available[$slug]['active'] ) {
$active_HTML.=
"<li class='product active'>" .
$this->slplus->add_ons->available[$slug]['link'] .
'</li>'
;
// Add to inactive HTML string
//
} else {
$inactive_HTML .=
"<li class='product inactive'>" .
$this->slplus->add_ons->available[$slug]['link'] .
'</li>'
;
}
}
}
$HTML .= '</ul>';
// Add active add on pack list
//
if ( ! empty ( $active_HTML ) ) {
$HTML .=
__( 'This theme will make use of these add-on packs:', 'csa-slplus' ) .
'<ul>' .
$active_HTML .
'</ul>'
;
}
// Add inactive add on pack list
//
if ( ! empty( $inactive_HTML ) ) {
$HTML .=
__( 'This theme works best if you activate the following add-on packs:', 'csa-slplus' ) .
'<ul>' .
$inactive_HTML .
'</ul>'
;
}
// Add the options section
//
$HTML .= $this->createstring_ThemeOptions();
}
$HTML .= '</div>';
return $HTML;
}
/**
* Create the HTML string that shows the preferred settings section on the Style interface.
*
* @return string
*/
private function createstring_ThemeOptions() {
// Add An Apply Settings Button
//
$save_message = __('Settings have been made. Click Save Settings to activate or the User Exprience tab to cancel.','csa-slplus');
$HTML =
$this->slplus->helper->create_SubheadingLabel(__('Preferred Settings','csa-slplus')) .
'<a href="#" '.
'class="like-a-button" ' .
"onClick='AdminUI.set_ThemeOptions(\"$save_message\"); return false;' ".
'>'.
__('Change Layout','csa-slplus').
'</a>' .
__('Click the button above to change your layout options and make the most of this theme: ','csa-slplus') .
'<br/>'
;
$this->setup_ThemeOptionFields();
foreach ( $this->theme_option_fields as $option_slug => $option_settings ) {
if ( ! empty ( $this->themeDetails[$this->current_slug][$option_slug] ) ) {
$activity_class =
( isset( $this->slplus->add_ons->available[$option_settings['slug']] ) &&
$this->slplus->add_ons->available[$option_settings['slug']]['active'] ) ?
'active' :
'inactive' ;
$HTML .=
"<div class='theme_option {$option_settings['slug']} $activity_class'> " .
"<span class='theme_option_label'>{$option_settings['name']}</span>" .
"<pre class='theme_option_value' settings_field='{$option_settings['field']}'>" .
esc_textarea($this->themeDetails[$this->current_slug][$option_slug]) .
'</pre>' .
'</div>'
;
}
}
$HTML .= '</ul>';
return $HTML;
}
/**
* Extract the label & key from a CSS file header.
*
* @param string $filename - a fully qualified path to a CSS file
* @return mixed - a named array of the data.
*/
private function get_ThemeInfo ($filename) {
$dataBack = array();
if ($filename != '') {
$default_headers =
array(
'add-ons' => 'add-ons',
'description' => 'description',
'file' => 'file',
'label' => 'label',
);
$all_headers = $this->setup_PluginThemeHeaders($default_headers);
$dataBack = get_file_data($filename,$all_headers,'plugin_theme');
$dataBack['file'] = preg_replace('/.css$/','',$dataBack['file']);
}
return $dataBack;
}
/**
* Add the theme settings to the admin panel.
*
* @param \wpCSL_settings__slplus $settingsObj
* @return type
*/
public function add_settings($settingsObj = null,$section=null,$group=null) {
if ($settingsObj == null) {
$settingsObj = $this->settings;
}
// Exit is directory does not exist
//
if (!is_dir($this->css_dir)) {
if (isset($this->notifications)) {
$this->notifications->add_notice(
2,
sprintf( __('The theme directory:<br/>%s<br/>is missing. ', 'csa-slplus'), $this->css_dir ) .
__( 'Create it to enable themes and get rid of this message.', 'csa-slplus' )
);
}
return;
}
// The Themes
// No themes? Force the default at least
//
$themeArray = get_option($this->prefix.'-theme_array');
if (count($themeArray, COUNT_RECURSIVE) < 2) {
$themeArray = array('Default' => 'default');
}
// Remove from drop down list if theme file does not exist in the plugin dir
//
foreach( $themeArray as $k => $theme ){
if( ! file_exists( $this->css_dir . $theme . '.css' ) ){
unset( $themeArray[$k] );
}
}
// Check for theme files
//
$lastNewThemeDate = get_option($this->prefix.'-theme_lastupdated');
$newEntry = array();
if ($dh = opendir($this->css_dir)) {
while (($file = readdir($dh)) !== false) {
if ( ! is_readable( $this->css_dir.$file ) ) { continue; }
// If not a hidden file
//
if (!preg_match('/^\./',$file)) {
$thisFileModTime = filemtime($this->css_dir.$file);
// We have a new theme file possibly...
//
if ($thisFileModTime > $lastNewThemeDate) {
$newEntry = $this->get_ThemeInfo($this->css_dir.$file);
$themeArray = array_merge($themeArray, array($newEntry['label'] => $newEntry['file']));
update_option($this->prefix.'-theme_lastupdated', $thisFileModTime);
}
}
}
closedir($dh);
}
// Remove empties and sort
$themeArray = array_filter($themeArray);
uksort($themeArray , 'strcasecmp' );
// Delete the default theme if we have specific ones
//
$resetDefault = false;
if ((count($themeArray, COUNT_RECURSIVE) > 1) && isset($themeArray['Default'])){
unset($themeArray['Default']);
$resetDefault = true;
}
// We added at least one new theme
//
if ((count($newEntry, COUNT_RECURSIVE) > 1) || $resetDefault) {
update_option($this->prefix.'-theme_array',$themeArray);
}
if ($section==null) { $section = 'Display Settings'; }
$settingsObj->add_itemToGroup(
array(
'section' => $section ,
'group' => $group ,
'label' => __('Select A Theme','csa-slplus') ,
'setting' => 'theme' ,
'type' => 'list' ,
'custom' => $themeArray ,
'value' => $this->slplus->defaults['theme'] ,
'description' =>
__('How should the plugin UI elements look? ','csa-slplus') .
sprintf(
__('Learn more in the <a href="%s" target="csa">online documentation</a>.','csa-slplus'),
$this->support_url . 'user-experience/view/themes-custom-css/'
),
'onChange' => "AdminUI.show_ThemeDetails(this);"
)
);
// Add Theme Details Divs
//
$settingsObj->add_ItemToGroup(
array(
'section' => $section ,
'group' => $group ,
'setting' => 'themedesc' ,
'type' => 'subheader' ,
'label' => '',
'description' => $this->setup_ThemeDetails($themeArray),
'show_label' => false
));
}
/**
* Add the theme-specific headers to the get_file_data header processor.
*
* @param string[] $headers
*/
private function setup_PluginThemeHeaders($headers) {
$this->setup_ThemeOptionFields();
$option_headers = array();
foreach ( $this->theme_option_fields as $option_slug => $option_settings ) {
$option_headers[$option_slug] = $option_settings['name'];
}
return array_merge($headers,$option_headers);
}
/**
* Setup the array of theme meta data options fields.
*/
private function setup_ThemeOptionFields() {
if ( count($this->theme_option_fields) > 0 ) { return; }
$this->theme_option_fields =
array(
'PRO.layout' => array(
'slug' => 'slp-pro',
'name' => 'Pro Pack Locator Layout',
'field' => 'csl-slplus-layout'
),
'EM.layout' => array(
'slug' => 'slp-enhanced-map',
'name' => 'Enhanced Map Bubble Layout',
'field' => 'bubblelayout'
),
'ER.layout' => array(
'slug' => 'slp-enhanced-results',
'name' => 'Enhanced Results Results Layout',
'field' => 'csl-slplus-ER-options[resultslayout]'
),
'ES.layout' => array(
'slug' => 'slp-enhanced-search',
'name' => 'Enhanced Search Search Layout',
'field' => 'csl-slplus-ES-options[searchlayout]'
),
);
}
/**
* Create the details divs for the SLP themes.
*
* @param mixed[] $themeArray
* @return string the div HTML
*/
private function setup_ThemeDetails($themeArray) {
$HTML = '';
$newDetails = false;
// Get an array of metadata for each theme present.
//
$this->themeDetails = get_option($this->prefix.'-theme_details');
// Check all our themes for details
//
foreach ($themeArray as $label=>$theme_slug) {
// No details? Read from the CSS File.
//
if (
!isset($this->themeDetails[$theme_slug]) || empty($this->themeDetails[$theme_slug]) ||
!isset($this->themeDetails[$theme_slug]['label']) || empty($this->themeDetails[$theme_slug]['label'])
) {
if ( is_readable( $this->css_dir . $theme_slug . '.css' ) ) {
$themeData = $this->get_ThemeInfo( $this->css_dir . $theme_slug . '.css' );
$themeData['fqfname'] = $this->css_dir . $theme_slug . '.css';
$this->themeDetails[ $theme_slug ] = $themeData;
$newDetails = true;
}
}
$this->current_slug = $theme_slug;
$HTML .= $this->createstring_ThemeDetails();
}
// If we read new details, go save to disk.
//
if ($newDetails) {
update_option($this->prefix.'-theme_details',$this->themeDetails);
}
return $HTML;
}
}
|
gpl-2.0
|
shellposhy/cms
|
src/main/java/cn/com/cms/library/service/LibraryCopyService.java
|
4981
|
package cn.com.cms.library.service;
import java.util.List;
import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import cn.com.cms.data.dao.BaseDbDao;
import cn.com.cms.data.dao.DataTableMapper;
import cn.com.cms.data.model.DataField;
import cn.com.cms.data.model.DataTable;
import cn.com.cms.data.service.DataCopyService;
import cn.com.cms.data.service.DataFieldService;
import cn.com.cms.framework.base.CmsData;
import cn.com.cms.framework.base.Node;
import cn.com.cms.framework.base.table.FieldCodes;
import cn.com.cms.framework.esb.jms.listener.DataCopyListener;
import cn.com.cms.framework.esb.jms.model.TaskMessage;
import cn.com.cms.library.constant.ELibraryCopyType;
import cn.com.cms.library.constant.EStatus;
import cn.com.cms.library.dao.LibraryMapper;
import cn.com.cms.library.model.BaseLibrary;
import cn.com.cms.system.contant.ETaskStatus;
import cn.com.cms.system.model.Task;
import cn.com.people.data.util.SimpleLock;
/**
* 数据库复制和同步服务类
*
* @author shishb
* @version 1.0
*/
@Service
public class LibraryCopyService<T extends BaseLibrary<T>> extends DataCopyListener {
private static final Logger logger = Logger.getLogger(LibraryCopyService.class.getName());
@Resource
private LibraryMapper<T> libraryMapper;
@Resource
private DataTableMapper dataTableMapper;
@Resource
private DataFieldService dataFieldService;
@Resource
private LibraryDataService libraryDataService;
@Resource
private BaseDbDao dbDao;
@Resource
private DataCopyService dataCopyService;
/**
* receive
*
* @param message
* @see javax.jms.MessageListener#onMessage(javax.jms.Message)
*/
public void onMessage(Message message) {
logger.debug("====library.data.copy.JMS.onMessage====");
ObjectMessage om = (ObjectMessage) message;
TaskMessage taskMessage = null;
try {
taskMessage = (TaskMessage) om.getObject();
} catch (JMSException e) {
logger.error("消息服务出错", e);
e.printStackTrace();
}
Task task = taskMessage.getTask();
Integer type = (Integer) taskMessage.get("type");
Integer source = task.getBaseId();
Integer target = Integer.valueOf(task.getAim());
String context = task.getContext();
task.setTaskStatus(ETaskStatus.Executing);
task.setProgress(1);
this.updateTaskStatus(task);
List<DataField> targetFieldList = findFieldsByDBId(target);
List<DataField> sourceFieldList = findFieldsByDBId(source);
List<CmsData> sourceDatas = wrapSourceData(context);
List<CmsData> datas = dataCopyService.wrapData(source, target, sourceDatas, sourceFieldList, targetFieldList);
switch (ELibraryCopyType.valueof(type)) {
case Copy:// copy data
if (!SimpleLock.lock("DataBase." + source)) {
logger.warn("数据库已经被锁定");
}
try {
libraryDataService.save(datas, targetFieldList);
} catch (Exception e) {
e.printStackTrace();
} finally {
task.setProgress(100);
task.setTaskStatus(ETaskStatus.Finish);
this.updateTaskStatus(task);
libraryMapper.updateTask(source, null);
libraryMapper.updateStatus(source, EStatus.Normal);
SimpleLock.unLock("DataBase." + source);
}
break;
case Movie:// move data
if (!SimpleLock.lock("DataBase." + target)) {
logger.warn("数据库已经被锁定");
}
try {
libraryDataService.save(datas, targetFieldList);
// delete data
if (null != sourceDatas && sourceDatas.size() > 0) {
for (CmsData data : sourceDatas) {
libraryDataService.deleteIndex(source, (String) data.get(FieldCodes.UUID));
DataTable dataTable = libraryDataService.getDataTable(source);
dbDao.delete(dataTable.getName(), (Integer) data.get(FieldCodes.ID));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
task.setProgress(100);
task.setTaskStatus(ETaskStatus.Finish);
this.updateTaskStatus(task);
libraryMapper.updateTask(target, null);
libraryMapper.updateStatus(target, EStatus.Normal);
SimpleLock.unLock("DataBase." + target);
}
break;
default:
break;
}
}
/**
* Find the database data field list
*
* @param libId
* @return
*/
public List<DataField> findFieldsByDBId(Integer libId) {
return dataFieldService.findFieldsByDBId(libId);
}
/**
* Wrap the source Cms Data
*
* @param context
* <code>e.g. 1_3,2_3,3_3</code>
* @return
*/
public List<CmsData> wrapSourceData(String context) {
List<CmsData> result = null;
List<Node<Integer, Integer>> nodes = dataCopyService.copyNode(context);
if (null != nodes && nodes.size() > 0) {
result = Lists.newArrayList();
for (Node<Integer, Integer> node : nodes) {
CmsData cmsData = libraryDataService.find(node.getName(), node.getId());
if (null != cmsData)
result.add(cmsData);
}
}
return result;
}
}
|
gpl-2.0
|
Karniyarik/karniyarik
|
karniyarik-wng/src/main/java/net/sourceforge/wurfl/wng/component/ValidatorVisitor.java
|
501
|
/*
* This file is released under the GNU General Public License.
* Refer to the COPYING file distributed with this package.
*
* Copyright (c) 2008-2009 WURFL-Pro srl
*/
package net.sourceforge.wurfl.wng.component;
/**
* This visitor calls validate on each visited component.
*
* @author Filippo De Luca
*
* @version $Id$
*/
public class ValidatorVisitor implements ComponentVisitor {
public void visit(Component component) throws ComponentException {
component.validate();
}
}
|
gpl-2.0
|
alexsh/Telegram
|
TMessagesProj/src/main/java/org/telegram/ui/FilterUsersActivity.java
|
69772
|
/*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.StateListAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Outline;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.ScrollView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ActionBar.ThemeDescription;
import org.telegram.ui.Adapters.SearchAdapterHelper;
import org.telegram.ui.Cells.GraySectionCell;
import org.telegram.ui.Cells.GroupCreateUserCell;
import org.telegram.ui.Components.CombinedDrawable;
import org.telegram.ui.Components.EditTextBoldCursor;
import org.telegram.ui.Components.EmptyTextProgressView;
import org.telegram.ui.Components.GroupCreateSpan;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.RecyclerListView;
import java.util.ArrayList;
import androidx.annotation.Keep;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class FilterUsersActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, View.OnClickListener {
private ScrollView scrollView;
private SpansContainer spansContainer;
private EditTextBoldCursor editText;
private RecyclerListView listView;
private EmptyTextProgressView emptyView;
private GroupCreateAdapter adapter;
private FilterUsersActivityDelegate delegate;
private AnimatorSet currentDoneButtonAnimation;
private ImageView floatingButton;
private boolean ignoreScrollEvent;
private int selectedCount;
private int containerHeight;
//private boolean doneButtonVisible;
private boolean isInclude;
private int filterFlags;
private ArrayList<Integer> initialIds;
private boolean searchWas;
private boolean searching;
private SparseArray<GroupCreateSpan> selectedContacts = new SparseArray<>();
private ArrayList<GroupCreateSpan> allSpans = new ArrayList<>();
private GroupCreateSpan currentDeletingSpan;
private int fieldY;
private final static int done_button = 1;
private static class ItemDecoration extends RecyclerView.ItemDecoration {
private boolean single;
private int skipRows;
public void setSingle(boolean value) {
single = value;
}
@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
int width = parent.getWidth();
int top;
int childCount = parent.getChildCount() - (single ? 0 : 1);
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
View nextChild = i < childCount - 1 ? parent.getChildAt(i + 1) : null;
int position = parent.getChildAdapterPosition(child);
if (position < skipRows || child instanceof GraySectionCell || nextChild instanceof GraySectionCell) {
continue;
}
top = child.getBottom();
canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(72), top, width - (LocaleController.isRTL ? AndroidUtilities.dp(72) : 0), top, Theme.dividerPaint);
}
}
@Override
public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
/*int position = parent.getChildAdapterPosition(view);
if (position == 0 || !searching && position == 1) {
return;
}*/
outRect.top = 1;
}
}
public interface FilterUsersActivityDelegate {
void didSelectChats(ArrayList<Integer> ids, int flags);
}
private class SpansContainer extends ViewGroup {
private AnimatorSet currentAnimation;
private boolean animationStarted;
private ArrayList<Animator> animators = new ArrayList<>();
private View addingSpan;
private View removingSpan;
public SpansContainer(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
int width = MeasureSpec.getSize(widthMeasureSpec);
int maxWidth = width - AndroidUtilities.dp(26);
int currentLineWidth = 0;
int y = AndroidUtilities.dp(10);
int allCurrentLineWidth = 0;
int allY = AndroidUtilities.dp(10);
int x;
for (int a = 0; a < count; a++) {
View child = getChildAt(a);
if (!(child instanceof GroupCreateSpan)) {
continue;
}
child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(32), MeasureSpec.EXACTLY));
if (child != removingSpan && currentLineWidth + child.getMeasuredWidth() > maxWidth) {
y += child.getMeasuredHeight() + AndroidUtilities.dp(8);
currentLineWidth = 0;
}
if (allCurrentLineWidth + child.getMeasuredWidth() > maxWidth) {
allY += child.getMeasuredHeight() + AndroidUtilities.dp(8);
allCurrentLineWidth = 0;
}
x = AndroidUtilities.dp(13) + currentLineWidth;
if (!animationStarted) {
if (child == removingSpan) {
child.setTranslationX(AndroidUtilities.dp(13) + allCurrentLineWidth);
child.setTranslationY(allY);
} else if (removingSpan != null) {
if (child.getTranslationX() != x) {
animators.add(ObjectAnimator.ofFloat(child, View.TRANSLATION_X, x));
}
if (child.getTranslationY() != y) {
animators.add(ObjectAnimator.ofFloat(child, View.TRANSLATION_Y, y));
}
} else {
child.setTranslationX(x);
child.setTranslationY(y);
}
}
if (child != removingSpan) {
currentLineWidth += child.getMeasuredWidth() + AndroidUtilities.dp(9);
}
allCurrentLineWidth += child.getMeasuredWidth() + AndroidUtilities.dp(9);
}
int minWidth;
if (AndroidUtilities.isTablet()) {
minWidth = AndroidUtilities.dp(530 - 26 - 18 - 57 * 2) / 3;
} else {
minWidth = (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(26 + 18 + 57 * 2)) / 3;
}
if (maxWidth - currentLineWidth < minWidth) {
currentLineWidth = 0;
y += AndroidUtilities.dp(32 + 8);
}
if (maxWidth - allCurrentLineWidth < minWidth) {
allY += AndroidUtilities.dp(32 + 8);
}
editText.measure(MeasureSpec.makeMeasureSpec(maxWidth - currentLineWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(32), MeasureSpec.EXACTLY));
if (!animationStarted) {
int currentHeight = allY + AndroidUtilities.dp(32 + 10);
int fieldX = currentLineWidth + AndroidUtilities.dp(16);
fieldY = y;
if (currentAnimation != null) {
int resultHeight = y + AndroidUtilities.dp(32 + 10);
if (containerHeight != resultHeight) {
animators.add(ObjectAnimator.ofInt(FilterUsersActivity.this, "containerHeight", resultHeight));
}
if (editText.getTranslationX() != fieldX) {
animators.add(ObjectAnimator.ofFloat(editText, View.TRANSLATION_X, fieldX));
}
if (editText.getTranslationY() != fieldY) {
animators.add(ObjectAnimator.ofFloat(editText, View.TRANSLATION_Y, fieldY));
}
editText.setAllowDrawCursor(false);
currentAnimation.playTogether(animators);
currentAnimation.start();
animationStarted = true;
} else {
containerHeight = currentHeight;
editText.setTranslationX(fieldX);
editText.setTranslationY(fieldY);
}
} else if (currentAnimation != null) {
if (!ignoreScrollEvent && removingSpan == null) {
editText.bringPointIntoView(editText.getSelectionStart());
}
}
setMeasuredDimension(width, containerHeight);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int count = getChildCount();
for (int a = 0; a < count; a++) {
View child = getChildAt(a);
child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
}
}
public void addSpan(final GroupCreateSpan span, boolean animated) {
allSpans.add(span);
int uid = span.getUid();
if (uid > Integer.MIN_VALUE + 7) {
selectedCount++;
}
selectedContacts.put(uid, span);
editText.setHintVisible(false);
if (currentAnimation != null) {
currentAnimation.setupEndValues();
currentAnimation.cancel();
}
animationStarted = false;
if (animated) {
currentAnimation = new AnimatorSet();
currentAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
addingSpan = null;
currentAnimation = null;
animationStarted = false;
editText.setAllowDrawCursor(true);
}
});
currentAnimation.setDuration(150);
addingSpan = span;
animators.clear();
animators.add(ObjectAnimator.ofFloat(addingSpan, View.SCALE_X, 0.01f, 1.0f));
animators.add(ObjectAnimator.ofFloat(addingSpan, View.SCALE_Y, 0.01f, 1.0f));
animators.add(ObjectAnimator.ofFloat(addingSpan, View.ALPHA, 0.0f, 1.0f));
}
addView(span);
}
public void removeSpan(final GroupCreateSpan span) {
ignoreScrollEvent = true;
int uid = span.getUid();
if (uid > Integer.MIN_VALUE + 7) {
selectedCount--;
}
selectedContacts.remove(uid);
allSpans.remove(span);
span.setOnClickListener(null);
if (currentAnimation != null) {
currentAnimation.setupEndValues();
currentAnimation.cancel();
}
animationStarted = false;
currentAnimation = new AnimatorSet();
currentAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
removeView(span);
removingSpan = null;
currentAnimation = null;
animationStarted = false;
editText.setAllowDrawCursor(true);
if (allSpans.isEmpty()) {
editText.setHintVisible(true);
}
}
});
currentAnimation.setDuration(150);
removingSpan = span;
animators.clear();
animators.add(ObjectAnimator.ofFloat(removingSpan, View.SCALE_X, 1.0f, 0.01f));
animators.add(ObjectAnimator.ofFloat(removingSpan, View.SCALE_Y, 1.0f, 0.01f));
animators.add(ObjectAnimator.ofFloat(removingSpan, View.ALPHA, 1.0f, 0.0f));
requestLayout();
}
}
public FilterUsersActivity(boolean include, ArrayList<Integer> arrayList, int flags) {
super();
isInclude = include;
filterFlags = flags;
initialIds = arrayList;
}
@Override
public boolean onFragmentCreate() {
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.contactsDidLoad);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.chatDidCreated);
return super.onFragmentCreate();
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.contactsDidLoad);
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.updateInterfaces);
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.chatDidCreated);
}
@Override
public void onClick(View v) {
GroupCreateSpan span = (GroupCreateSpan) v;
if (span.isDeleting()) {
currentDeletingSpan = null;
spansContainer.removeSpan(span);
if (span.getUid() == Integer.MIN_VALUE) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
} else if (span.getUid() == Integer.MIN_VALUE + 1) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
} else if (span.getUid() == Integer.MIN_VALUE + 2) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_GROUPS;
} else if (span.getUid() == Integer.MIN_VALUE + 3) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
} else if (span.getUid() == Integer.MIN_VALUE + 4) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_BOTS;
} else if (span.getUid() == Integer.MIN_VALUE + 5) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
} else if (span.getUid() == Integer.MIN_VALUE + 6) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
} else if (span.getUid() == Integer.MIN_VALUE + 7) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
}
updateHint();
checkVisibleRows();
} else {
if (currentDeletingSpan != null) {
currentDeletingSpan.cancelDeleteAnimation();
}
currentDeletingSpan = span;
span.startDeleteAnimation();
}
}
@Override
public View createView(Context context) {
searching = false;
searchWas = false;
allSpans.clear();
selectedContacts.clear();
currentDeletingSpan = null;
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
if (isInclude) {
actionBar.setTitle(LocaleController.getString("FilterAlwaysShow", R.string.FilterAlwaysShow));
} else {
actionBar.setTitle(LocaleController.getString("FilterNeverShow", R.string.FilterNeverShow));
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == done_button) {
onDonePressed(true);
}
}
});
fragmentView = new ViewGroup(context) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
int maxSize;
if (AndroidUtilities.isTablet() || height > width) {
maxSize = AndroidUtilities.dp(144);
} else {
maxSize = AndroidUtilities.dp(56);
}
scrollView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(maxSize, MeasureSpec.AT_MOST));
listView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height - scrollView.getMeasuredHeight(), MeasureSpec.EXACTLY));
emptyView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height - scrollView.getMeasuredHeight(), MeasureSpec.EXACTLY));
if (floatingButton != null) {
int w = AndroidUtilities.dp(Build.VERSION.SDK_INT >= 21 ? 56 : 60);
floatingButton.measure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY));
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
scrollView.layout(0, 0, scrollView.getMeasuredWidth(), scrollView.getMeasuredHeight());
listView.layout(0, scrollView.getMeasuredHeight(), listView.getMeasuredWidth(), scrollView.getMeasuredHeight() + listView.getMeasuredHeight());
emptyView.layout(0, scrollView.getMeasuredHeight(), emptyView.getMeasuredWidth(), scrollView.getMeasuredHeight() + emptyView.getMeasuredHeight());
if (floatingButton != null) {
int l = LocaleController.isRTL ? AndroidUtilities.dp(14) : (right - left) - AndroidUtilities.dp(14) - floatingButton.getMeasuredWidth();
int t = bottom - top - AndroidUtilities.dp(14) - floatingButton.getMeasuredHeight();
floatingButton.layout(l, t, l + floatingButton.getMeasuredWidth(), t + floatingButton.getMeasuredHeight());
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == listView || child == emptyView) {
parentLayout.drawHeaderShadow(canvas, scrollView.getMeasuredHeight());
}
return result;
}
};
ViewGroup frameLayout = (ViewGroup) fragmentView;
scrollView = new ScrollView(context) {
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
if (ignoreScrollEvent) {
ignoreScrollEvent = false;
return false;
}
rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY());
rectangle.top += fieldY + AndroidUtilities.dp(20);
rectangle.bottom += fieldY + AndroidUtilities.dp(50);
return super.requestChildRectangleOnScreen(child, rectangle, immediate);
}
};
scrollView.setVerticalScrollBarEnabled(false);
AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_windowBackgroundWhite));
frameLayout.addView(scrollView);
spansContainer = new SpansContainer(context);
scrollView.addView(spansContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
spansContainer.setOnClickListener(v -> {
editText.clearFocus();
editText.requestFocus();
AndroidUtilities.showKeyboard(editText);
});
editText = new EditTextBoldCursor(context) {
@Override
public boolean onTouchEvent(MotionEvent event) {
if (currentDeletingSpan != null) {
currentDeletingSpan.cancelDeleteAnimation();
currentDeletingSpan = null;
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (!AndroidUtilities.showKeyboard(this)) {
clearFocus();
requestFocus();
}
}
return super.onTouchEvent(event);
}
};
editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
editText.setHintColor(Theme.getColor(Theme.key_groupcreate_hintText));
editText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
editText.setCursorColor(Theme.getColor(Theme.key_groupcreate_cursor));
editText.setCursorWidth(1.5f);
editText.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
editText.setSingleLine(true);
editText.setBackgroundDrawable(null);
editText.setVerticalScrollBarEnabled(false);
editText.setHorizontalScrollBarEnabled(false);
editText.setTextIsSelectable(false);
editText.setPadding(0, 0, 0, 0);
editText.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
editText.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
spansContainer.addView(editText);
editText.setHintText(LocaleController.getString("SearchForPeopleAndGroups", R.string.SearchForPeopleAndGroups));
editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
//editText.setOnEditorActionListener((v, actionId, event) -> actionId == EditorInfo.IME_ACTION_DONE && onDonePressed(true));
editText.setOnKeyListener(new View.OnKeyListener() {
private boolean wasEmpty;
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
wasEmpty = editText.length() == 0;
} else if (event.getAction() == KeyEvent.ACTION_UP && wasEmpty && !allSpans.isEmpty()) {
GroupCreateSpan span = allSpans.get(allSpans.size() - 1);
spansContainer.removeSpan(span);
if (span.getUid() == Integer.MIN_VALUE) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
} else if (span.getUid() == Integer.MIN_VALUE + 1) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
} else if (span.getUid() == Integer.MIN_VALUE + 2) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_GROUPS;
} else if (span.getUid() == Integer.MIN_VALUE + 3) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
} else if (span.getUid() == Integer.MIN_VALUE + 4) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_BOTS;
} else if (span.getUid() == Integer.MIN_VALUE + 5) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
} else if (span.getUid() == Integer.MIN_VALUE + 6) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
} else if (span.getUid() == Integer.MIN_VALUE + 7) {
filterFlags &=~ MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
}
updateHint();
checkVisibleRows();
return true;
}
}
return false;
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editText.length() != 0) {
if (!adapter.searching) {
searching = true;
searchWas = true;
adapter.setSearching(true);
listView.setFastScrollVisible(false);
listView.setVerticalScrollBarEnabled(true);
emptyView.setText(LocaleController.getString("NoResult", R.string.NoResult));
emptyView.showProgress();
}
adapter.searchDialogs(editText.getText().toString());
} else {
closeSearch();
}
}
});
emptyView = new EmptyTextProgressView(context);
if (ContactsController.getInstance(currentAccount).isLoadingContacts()) {
emptyView.showProgress();
} else {
emptyView.showTextView();
}
emptyView.setShowAtCenter(true);
emptyView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
frameLayout.addView(emptyView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
listView = new RecyclerListView(context);
listView.setFastScrollEnabled();
listView.setEmptyView(emptyView);
listView.setAdapter(adapter = new GroupCreateAdapter(context));
listView.setLayoutManager(linearLayoutManager);
listView.setVerticalScrollBarEnabled(false);
listView.setVerticalScrollbarPosition(LocaleController.isRTL ? View.SCROLLBAR_POSITION_LEFT : View.SCROLLBAR_POSITION_RIGHT);
listView.addItemDecoration(new ItemDecoration());
frameLayout.addView(listView);
listView.setOnItemClickListener((view, position) -> {
if (view instanceof GroupCreateUserCell) {
GroupCreateUserCell cell = (GroupCreateUserCell) view;
Object object = cell.getObject();
int id;
if (object instanceof String) {
int flag;
if (isInclude) {
if (position == 1) {
flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
id = Integer.MIN_VALUE;
} else if (position == 2) {
flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
id = Integer.MIN_VALUE + 1;
} else if (position == 3) {
flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
id = Integer.MIN_VALUE + 2;
} else if (position == 4) {
flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
id = Integer.MIN_VALUE + 3;
} else {
flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
id = Integer.MIN_VALUE + 4;
}
} else {
if (position == 1) {
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
id = Integer.MIN_VALUE + 5;
} else if (position == 2) {
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
id = Integer.MIN_VALUE + 6;
} else {
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
id = Integer.MIN_VALUE + 7;
}
}
if (cell.isChecked()) {
filterFlags &=~ flag;
} else {
filterFlags |= flag;
}
} else {
if (object instanceof TLRPC.User) {
id = ((TLRPC.User) object).id;
} else if (object instanceof TLRPC.Chat) {
id = -((TLRPC.Chat) object).id;
} else {
return;
}
}
boolean exists;
if (exists = selectedContacts.indexOfKey(id) >= 0) {
GroupCreateSpan span = selectedContacts.get(id);
spansContainer.removeSpan(span);
} else {
if (!(object instanceof String) && selectedCount >= 100) {
return;
}
if (object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) object;
MessagesController.getInstance(currentAccount).putUser(user, !searching);
} else if (object instanceof TLRPC.Chat) {
TLRPC.Chat chat = (TLRPC.Chat) object;
MessagesController.getInstance(currentAccount).putChat(chat, !searching);
}
GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
spansContainer.addSpan(span, true);
span.setOnClickListener(FilterUsersActivity.this);
}
updateHint();
if (searching || searchWas) {
AndroidUtilities.showKeyboard(editText);
} else {
cell.setChecked(!exists, true);
}
if (editText.length() > 0) {
editText.setText(null);
}
}
});
listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
AndroidUtilities.hideKeyboard(editText);
}
}
});
floatingButton = new ImageView(context);
floatingButton.setScaleType(ImageView.ScaleType.CENTER);
Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_chats_actionBackground), Theme.getColor(Theme.key_chats_actionPressedBackground));
if (Build.VERSION.SDK_INT < 21) {
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
drawable = combinedDrawable;
}
floatingButton.setBackgroundDrawable(drawable);
floatingButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_actionIcon), PorterDuff.Mode.MULTIPLY));
floatingButton.setImageResource(R.drawable.floating_check);
if (Build.VERSION.SDK_INT >= 21) {
StateListAnimator animator = new StateListAnimator();
animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
animator.addState(new int[]{}, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
floatingButton.setStateListAnimator(animator);
floatingButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
}
});
}
frameLayout.addView(floatingButton);
floatingButton.setOnClickListener(v -> onDonePressed(true));
/*floatingButton.setVisibility(View.INVISIBLE);
floatingButton.setScaleX(0.0f);
floatingButton.setScaleY(0.0f);
floatingButton.setAlpha(0.0f);*/
floatingButton.setContentDescription(LocaleController.getString("Next", R.string.Next));
for (int position = 1, N = (isInclude ? 5 : 3); position <= N; position++) {
int id;
int flag;
Object object;
if (isInclude) {
if (position == 1) {
object = "contacts";
flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
} else if (position == 2) {
object = "non_contacts";
flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
} else if (position == 3) {
object = "groups";
flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
} else if (position == 4) {
object = "channels";
flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
} else {
object = "bots";
flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
}
} else {
if (position == 1) {
object = "muted";
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
} else if (position == 2) {
object = "read";
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
} else {
object = "archived";
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
}
}
if ((filterFlags & flag) != 0) {
GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
spansContainer.addSpan(span, false);
span.setOnClickListener(FilterUsersActivity.this);
}
}
if (initialIds != null && !initialIds.isEmpty()) {
TLObject object;
for (int a = 0, N = initialIds.size(); a < N; a++) {
Integer id = initialIds.get(a);
if (id > 0) {
object = getMessagesController().getUser(id);
} else {
object = getMessagesController().getChat(-id);
}
if (object == null) {
continue;
}
GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
spansContainer.addSpan(span, false);
span.setOnClickListener(FilterUsersActivity.this);
}
}
updateHint();
return fragmentView;
}
@Override
public void onResume() {
super.onResume();
if (editText != null) {
editText.requestFocus();
}
AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.contactsDidLoad) {
if (emptyView != null) {
emptyView.showTextView();
}
if (adapter != null) {
adapter.notifyDataSetChanged();
}
} else if (id == NotificationCenter.updateInterfaces) {
if (listView != null) {
int mask = (Integer) args[0];
int count = listView.getChildCount();
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof GroupCreateUserCell) {
((GroupCreateUserCell) child).update(mask);
}
}
}
}
} else if (id == NotificationCenter.chatDidCreated) {
removeSelfFromStack();
}
}
@Keep
public void setContainerHeight(int value) {
containerHeight = value;
if (spansContainer != null) {
spansContainer.requestLayout();
}
}
@Keep
public int getContainerHeight() {
return containerHeight;
}
private void checkVisibleRows() {
int count = listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof GroupCreateUserCell) {
GroupCreateUserCell cell = (GroupCreateUserCell) child;
Object object = cell.getObject();
int id;
if (object instanceof String) {
String str = (String) object;
switch (str) {
case "contacts":
id = Integer.MIN_VALUE;
break;
case "non_contacts":
id = Integer.MIN_VALUE + 1;
break;
case "groups":
id = Integer.MIN_VALUE + 2;
break;
case "channels":
id = Integer.MIN_VALUE + 3;
break;
case "bots":
id = Integer.MIN_VALUE + 4;
break;
case "muted":
id = Integer.MIN_VALUE + 5;
break;
case "read":
id = Integer.MIN_VALUE + 6;
break;
case "archived":
default:
id = Integer.MIN_VALUE + 7;
break;
}
} else if (object instanceof TLRPC.User) {
id = ((TLRPC.User) object).id;
} else if (object instanceof TLRPC.Chat) {
id = -((TLRPC.Chat) object).id;
} else {
id = 0;
}
if (id != 0) {
cell.setChecked(selectedContacts.indexOfKey(id) >= 0, true);
cell.setCheckBoxEnabled(true);
}
}
}
}
private boolean onDonePressed(boolean alert) {
/*if (!doneButtonVisible || selectedContacts.size() == 0) {
return false;
}*/
ArrayList<Integer> result = new ArrayList<>();
for (int a = 0; a < selectedContacts.size(); a++) {
int uid = selectedContacts.keyAt(a);
if (uid <= Integer.MIN_VALUE + 7) {
continue;
}
result.add(selectedContacts.keyAt(a));
}
if (delegate != null) {
delegate.didSelectChats(result, filterFlags);
}
finishFragment();
return true;
}
private void closeSearch() {
searching = false;
searchWas = false;
adapter.setSearching(false);
adapter.searchDialogs(null);
listView.setFastScrollVisible(true);
listView.setVerticalScrollBarEnabled(false);
emptyView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
}
private void updateHint() {
if (selectedCount == 0) {
actionBar.setSubtitle(LocaleController.formatString("MembersCountZero", R.string.MembersCountZero, LocaleController.formatPluralString("Chats", 100)));
} else {
actionBar.setSubtitle(String.format(LocaleController.getPluralString("MembersCountSelected", selectedCount), selectedCount, 100));
}
}
public void setDelegate(FilterUsersActivityDelegate filterUsersActivityDelegate) {
delegate = filterUsersActivityDelegate;
}
public class GroupCreateAdapter extends RecyclerListView.FastScrollAdapter {
private Context context;
private ArrayList<Object> searchResult = new ArrayList<>();
private ArrayList<CharSequence> searchResultNames = new ArrayList<>();
private SearchAdapterHelper searchAdapterHelper;
private Runnable searchRunnable;
private boolean searching;
private ArrayList<TLObject> contacts = new ArrayList<>();
private final int usersStartRow = isInclude ? 7 : 5;
public GroupCreateAdapter(Context ctx) {
context = ctx;
boolean hasSelf = false;
ArrayList<TLRPC.Dialog> dialogs = getMessagesController().getAllDialogs();
for (int a = 0, N = dialogs.size(); a < N; a++) {
TLRPC.Dialog dialog = dialogs.get(a);
int lowerId = (int) dialog.id;
if (lowerId == 0) {
continue;
}
if (lowerId > 0) {
TLRPC.User user = getMessagesController().getUser(lowerId);
if (user != null) {
contacts.add(user);
if (UserObject.isUserSelf(user)) {
hasSelf = true;
}
}
} else {
TLRPC.Chat chat = getMessagesController().getChat(-lowerId);
if (chat != null) {
contacts.add(chat);
}
}
}
if (!hasSelf) {
TLRPC.User user = getMessagesController().getUser(getUserConfig().clientUserId);
contacts.add(0, user);
}
searchAdapterHelper = new SearchAdapterHelper(false);
searchAdapterHelper.setAllowGlobalResults(false);
searchAdapterHelper.setDelegate((searchId) -> {
if (searchRunnable == null && !searchAdapterHelper.isSearchInProgress()) {
emptyView.showTextView();
}
notifyDataSetChanged();
});
}
public void setSearching(boolean value) {
if (searching == value) {
return;
}
searching = value;
notifyDataSetChanged();
}
@Override
public String getLetter(int position) {
return null;
}
@Override
public int getItemCount() {
int count;
if (searching) {
count = searchResult.size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
int globalCount = searchAdapterHelper.getGlobalSearch().size();
count += localServerCount + globalCount;
return count;
} else {
if (isInclude) {
count = 7;
} else {
count = 5;
}
count += contacts.size();
}
return count;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case 1:
view = new GroupCreateUserCell(context, 1, 0, true);
break;
case 2:
default:
view = new GraySectionCell(context);
break;
}
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 1: {
GroupCreateUserCell cell = (GroupCreateUserCell) holder.itemView;
Object object;
CharSequence username = null;
CharSequence name = null;
if (searching) {
int localCount = searchResult.size();
int globalCount = searchAdapterHelper.getGlobalSearch().size();
int localServerCount = searchAdapterHelper.getLocalServerSearch().size();
if (position >= 0 && position < localCount) {
object = searchResult.get(position);
} else if (position >= localCount && position < localServerCount + localCount) {
object = searchAdapterHelper.getLocalServerSearch().get(position - localCount);
} else if (position > localCount + localServerCount && position < globalCount + localCount + localServerCount) {
object = searchAdapterHelper.getGlobalSearch().get(position - localCount - localServerCount);
} else {
object = null;
}
if (object != null) {
String objectUserName;
if (object instanceof TLRPC.User) {
objectUserName = ((TLRPC.User) object).username;
} else {
objectUserName = ((TLRPC.Chat) object).username;
}
if (position < localCount) {
name = searchResultNames.get(position);
if (name != null && !TextUtils.isEmpty(objectUserName)) {
if (name.toString().startsWith("@" + objectUserName)) {
username = name;
name = null;
}
}
} else if (position > localCount && !TextUtils.isEmpty(objectUserName)) {
String foundUserName = searchAdapterHelper.getLastFoundUsername();
if (foundUserName.startsWith("@")) {
foundUserName = foundUserName.substring(1);
}
try {
int index;
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
spannableStringBuilder.append("@");
spannableStringBuilder.append(objectUserName);
if ((index = AndroidUtilities.indexOfIgnoreCase(objectUserName, foundUserName)) != -1) {
int len = foundUserName.length();
if (index == 0) {
len++;
} else {
index++;
}
spannableStringBuilder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText4)), index, index + len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
username = spannableStringBuilder;
} catch (Exception e) {
username = objectUserName;
}
}
}
} else {
if (position < usersStartRow) {
int flag;
if (isInclude) {
if (position == 1) {
name = LocaleController.getString("FilterContacts", R.string.FilterContacts);
object = "contacts";
flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
} else if (position == 2) {
name = LocaleController.getString("FilterNonContacts", R.string.FilterNonContacts);
object = "non_contacts";
flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
} else if (position == 3) {
name = LocaleController.getString("FilterGroups", R.string.FilterGroups);
object = "groups";
flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
} else if (position == 4) {
name = LocaleController.getString("FilterChannels", R.string.FilterChannels);
object = "channels";
flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
} else {
name = LocaleController.getString("FilterBots", R.string.FilterBots);
object = "bots";
flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
}
} else {
if (position == 1) {
name = LocaleController.getString("FilterMuted", R.string.FilterMuted);
object = "muted";
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
} else if (position == 2) {
name = LocaleController.getString("FilterRead", R.string.FilterRead);
object = "read";
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
} else {
name = LocaleController.getString("FilterArchived", R.string.FilterArchived);
object = "archived";
flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
}
}
cell.setObject(object, name, null);
cell.setChecked((filterFlags & flag) == flag, false);
cell.setCheckBoxEnabled(true);
return;
}
object = contacts.get(position - usersStartRow);
}
int id;
if (object instanceof TLRPC.User) {
id = ((TLRPC.User) object).id;
} else if (object instanceof TLRPC.Chat) {
id = -((TLRPC.Chat) object).id;
} else {
id = 0;
}
if (!searching) {
StringBuilder builder = new StringBuilder();
ArrayList<MessagesController.DialogFilter> filters = getMessagesController().dialogFilters;
for (int a = 0, N = filters.size(); a < N; a++) {
MessagesController.DialogFilter filter = filters.get(a);
if (filter.includesDialog(getAccountInstance(), id)) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(filter.name);
}
}
username = builder;
}
cell.setObject(object, name, username);
if (id != 0) {
cell.setChecked(selectedContacts.indexOfKey(id) >= 0, false);
cell.setCheckBoxEnabled(true);
}
break;
}
case 2: {
GraySectionCell cell = (GraySectionCell) holder.itemView;
if (position == 0) {
cell.setText(LocaleController.getString("FilterChatTypes", R.string.FilterChatTypes));
} else {
cell.setText(LocaleController.getString("FilterChats", R.string.FilterChats));
}
break;
}
}
}
@Override
public int getItemViewType(int position) {
if (searching) {
return 1;
} else {
if (isInclude) {
if (position == 0 || position == 6) {
return 2;
}
} else {
if (position == 0 || position == 4) {
return 2;
}
}
return 1;
}
}
@Override
public int getPositionForScrollProgress(float progress) {
return (int) (getItemCount() * progress);
}
@Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
if (holder.itemView instanceof GroupCreateUserCell) {
((GroupCreateUserCell) holder.itemView).recycle();
}
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
return holder.getItemViewType() == 1;
}
public void searchDialogs(final String query) {
if (searchRunnable != null) {
Utilities.searchQueue.cancelRunnable(searchRunnable);
searchRunnable = null;
}
if (query == null) {
searchResult.clear();
searchResultNames.clear();
searchAdapterHelper.mergeResults(null);
searchAdapterHelper.queryServerSearch(null, true, true, false, false, false, 0, false, 0, 0);
notifyDataSetChanged();
} else {
Utilities.searchQueue.postRunnable(searchRunnable = () -> AndroidUtilities.runOnUIThread(() -> {
searchAdapterHelper.queryServerSearch(query, true, true, true, true, false, 0, false, 0, 0);
Utilities.searchQueue.postRunnable(searchRunnable = () -> {
String search1 = query.trim().toLowerCase();
if (search1.length() == 0) {
updateSearchResults(new ArrayList<>(), new ArrayList<>());
return;
}
String search2 = LocaleController.getInstance().getTranslitString(search1);
if (search1.equals(search2) || search2.length() == 0) {
search2 = null;
}
String[] search = new String[1 + (search2 != null ? 1 : 0)];
search[0] = search1;
if (search2 != null) {
search[1] = search2;
}
ArrayList<Object> resultArray = new ArrayList<>();
ArrayList<CharSequence> resultArrayNames = new ArrayList<>();
for (int a = 0; a < contacts.size(); a++) {
TLObject object = contacts.get(a);
String username;
final String[] names = new String[3];
if (object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) object;
names[0] = ContactsController.formatName(user.first_name, user.last_name).toLowerCase();
username = user.username;
if (UserObject.isReplyUser(user)) {
names[2] = LocaleController.getString("RepliesTitle", R.string.RepliesTitle).toLowerCase();
} else if (user.self) {
names[2] = LocaleController.getString("SavedMessages", R.string.SavedMessages).toLowerCase();
}
} else {
TLRPC.Chat chat = (TLRPC.Chat) object;
names[0] = chat.title.toLowerCase();
username = chat.username;
}
names[1] = LocaleController.getInstance().getTranslitString(names[0]);
if (names[0].equals(names[1])) {
names[1] = null;
}
int found = 0;
for (String q : search) {
for (int i = 0; i < names.length; i++) {
final String name = names[i];
if (name != null && (name.startsWith(q) || name.contains(" " + q))) {
found = 1;
break;
}
}
if (found == 0 && username != null && username.toLowerCase().startsWith(q)) {
found = 2;
}
if (found != 0) {
if (found == 1) {
if (object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) object;
resultArrayNames.add(AndroidUtilities.generateSearchName(user.first_name, user.last_name, q));
} else {
TLRPC.Chat chat = (TLRPC.Chat) object;
resultArrayNames.add(AndroidUtilities.generateSearchName(chat.title, null, q));
}
} else {
resultArrayNames.add(AndroidUtilities.generateSearchName("@" + username, null, "@" + q));
}
resultArray.add(object);
break;
}
}
}
updateSearchResults(resultArray, resultArrayNames);
});
}), 300);
}
}
private void updateSearchResults(final ArrayList<Object> users, final ArrayList<CharSequence> names) {
AndroidUtilities.runOnUIThread(() -> {
if (!searching) {
return;
}
searchRunnable = null;
searchResult = users;
searchResultNames = names;
searchAdapterHelper.mergeResults(searchResult);
if (searching && !searchAdapterHelper.isSearchInProgress()) {
emptyView.showTextView();
}
notifyDataSetChanged();
});
}
}
@Override
public ArrayList<ThemeDescription> getThemeDescriptions() {
ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>();
ThemeDescription.ThemeDescriptionDelegate cellDelegate = () -> {
if (listView != null) {
int count = listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof GroupCreateUserCell) {
((GroupCreateUserCell) child).update(0);
}
}
}
};
themeDescriptions.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundWhite));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_actionBarDefault));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector));
themeDescriptions.add(new ThemeDescription(scrollView, ThemeDescription.FLAG_LISTGLOWCOLOR, null, null, null, null, Theme.key_windowBackgroundWhite));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_SELECTOR, null, null, null, null, Theme.key_listSelector));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_FASTSCROLL, null, null, null, null, Theme.key_fastScrollActive));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_FASTSCROLL, null, null, null, null, Theme.key_fastScrollInactive));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_FASTSCROLL, null, null, null, null, Theme.key_fastScrollText));
themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{View.class}, Theme.dividerPaint, null, null, Theme.key_divider));
themeDescriptions.add(new ThemeDescription(emptyView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_emptyListPlaceholder));
themeDescriptions.add(new ThemeDescription(emptyView, ThemeDescription.FLAG_PROGRESSBAR, null, null, null, null, Theme.key_progressCircle));
themeDescriptions.add(new ThemeDescription(editText, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteBlackText));
themeDescriptions.add(new ThemeDescription(editText, ThemeDescription.FLAG_HINTTEXTCOLOR, null, null, null, null, Theme.key_groupcreate_hintText));
themeDescriptions.add(new ThemeDescription(editText, ThemeDescription.FLAG_CURSORCOLOR, null, null, null, null, Theme.key_groupcreate_cursor));
themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{GraySectionCell.class}, new String[]{"textView"}, null, null, null, Theme.key_graySectionText));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_CELLBACKGROUNDCOLOR, new Class[]{GraySectionCell.class}, null, null, null, Theme.key_graySection));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"textView"}, null, null, null, Theme.key_groupcreate_sectionText));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkbox));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkboxDisabled));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkboxCheck));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR | ThemeDescription.FLAG_CHECKTAG, new Class[]{GroupCreateUserCell.class}, new String[]{"statusTextView"}, null, null, null, Theme.key_windowBackgroundWhiteBlueText));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR | ThemeDescription.FLAG_CHECKTAG, new Class[]{GroupCreateUserCell.class}, new String[]{"statusTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText));
themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{GroupCreateUserCell.class}, null, Theme.avatarDrawables, null, Theme.key_avatar_text));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundRed));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundOrange));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundViolet));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundGreen));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundCyan));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundBlue));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundPink));
themeDescriptions.add(new ThemeDescription(spansContainer, 0, new Class[]{GroupCreateSpan.class}, null, null, null, Theme.key_groupcreate_spanBackground));
themeDescriptions.add(new ThemeDescription(spansContainer, 0, new Class[]{GroupCreateSpan.class}, null, null, null, Theme.key_groupcreate_spanText));
themeDescriptions.add(new ThemeDescription(spansContainer, 0, new Class[]{GroupCreateSpan.class}, null, null, null, Theme.key_groupcreate_spanDelete));
themeDescriptions.add(new ThemeDescription(spansContainer, 0, new Class[]{GroupCreateSpan.class}, null, null, null, Theme.key_avatar_backgroundBlue));
return themeDescriptions;
}
}
|
gpl-2.0
|
Lythimus/lptv
|
apache-solr-3.6.0/solr/core/src/test/org/apache/solr/schema/PolyFieldTest.java
|
6827
|
package org.apache.solr.schema;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.core.SolrCore;
import org.apache.solr.common.SolrException;
import org.apache.solr.search.function.ValueSource;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test a whole slew of things related to PolyFields
*/
public class PolyFieldTest extends SolrTestCaseJ4 {
@BeforeClass
public static void beforeClass() throws Exception {
initCore("solrconfig.xml","schema.xml");
}
@Test
public void testSchemaBasics() throws Exception {
IndexSchema schema = h.getCore().getSchema();
SchemaField home = schema.getField("home");
assertNotNull(home);
assertTrue(home.isPolyField());
SchemaField[] dynFields = schema.getDynamicFieldPrototypes();
boolean seen = false;
for (SchemaField dynField : dynFields) {
if (dynField.getName().equals("*" + FieldType.POLY_FIELD_SEPARATOR + "double")) {
seen = true;
}
}
assertTrue("Didn't find the expected dynamic field", seen);
FieldType homeFT = schema.getFieldType("home");
assertEquals(home.getType(), homeFT);
FieldType xy = schema.getFieldTypeByName("xy");
assertNotNull(xy);
assertTrue(xy instanceof PointType);
assertTrue(xy.isPolyField());
home = schema.getFieldOrNull("home_0" + FieldType.POLY_FIELD_SEPARATOR + "double");
assertNotNull(home);
home = schema.getField("home");
assertNotNull(home);
home = schema.getField("homed");//sub field suffix
assertNotNull(home);
assertTrue(home.isPolyField());
}
@Test
public void testPointFieldType() throws Exception {
SolrCore core = h.getCore();
IndexSchema schema = core.getSchema();
SchemaField home = schema.getField("home");
assertNotNull(home);
assertTrue("home is not a poly field", home.isPolyField());
FieldType tmp = home.getType();
assertTrue(tmp instanceof PointType);
PointType pt = (PointType) tmp;
assertEquals(pt.getDimension(), 2);
double[] xy = new double[]{35.0, -79.34};
String point = xy[0] + "," + xy[1];
Fieldable[] fields = home.createFields(point, 2);
assertEquals(fields.length, 3);//should be 3, we have a stored field
//first two fields contain the values, third is just stored and contains the original
for (int i = 0; i < 3; i++) {
boolean hasValue = fields[1].tokenStreamValue() != null
|| fields[1].getBinaryValue() != null
|| fields[1].stringValue() != null;
assertTrue("Doesn't have a value: " + fields[1], hasValue);
}
/*assertTrue("first field " + fields[0].tokenStreamValue() + " is not 35.0", pt.getSubType().toExternal(fields[0]).equals(String.valueOf(xy[0])));
assertTrue("second field is not -79.34", pt.getSubType().toExternal(fields[1]).equals(String.valueOf(xy[1])));
assertTrue("third field is not '35.0,-79.34'", pt.getSubType().toExternal(fields[2]).equals(point));*/
home = schema.getField("home_ns");
assertNotNull(home);
fields = home.createFields(point, 2);
assertEquals(fields.length, 2);//should be 2, since we aren't storing
home = schema.getField("home_ns");
assertNotNull(home);
try {
fields = home.createFields("35.0,foo", 2);
assertTrue(false);
} catch (Exception e) {
//
}
//
SchemaField s1 = schema.getField("test_p");
SchemaField s2 = schema.getField("test_p");
ValueSource v1 = s1.getType().getValueSource(s1, null);
ValueSource v2 = s2.getType().getValueSource(s2, null);
assertEquals(v1, v2);
assertEquals(v1.hashCode(), v2.hashCode());
}
@Test
public void testSearching() throws Exception {
for (int i = 0; i < 50; i++) {
assertU(adoc("id", "" + i, "home", i + "," + (i * 100), "homed", (i * 1000) + "," + (i * 10000)));
}
assertU(commit());
assertQ(req("fl", "*,score", "q", "*:*"), "//*[@numFound='50']");
assertQ(req("fl", "*,score", "q", "home:1,100"),
"//*[@numFound='1']",
"//str[@name='home'][.='1,100']");
assertQ(req("fl", "*,score", "q", "homed:1000,10000"),
"//*[@numFound='1']",
"//str[@name='homed'][.='1000,10000']");
assertQ(req("fl", "*,score", "q",
"{!func}sqedist(home, vector(0, 0))"),
"\"//*[@numFound='50']\"");
assertQ(req("fl", "*,score", "q",
"{!func}dist(2, home, vector(0, 0))"),
"\"//*[@numFound='50']\"");
assertQ(req("fl", "*,score", "q",
"home:[10,10000 TO 30,30000]"),
"\"//*[@numFound='3']\"");
assertQ(req("fl", "*,score", "q",
"homed:[1,1000 TO 2000,35000]"),
"\"//*[@numFound='2']\"");
//bad
ignoreException("dimension");
assertQEx("Query should throw an exception due to incorrect dimensions", req("fl", "*,score", "q",
"homed:[1 TO 2000]"), SolrException.ErrorCode.BAD_REQUEST);
resetExceptionIgnores();
clearIndex();
}
@Test
public void testSearchDetails() throws Exception {
SolrCore core = h.getCore();
IndexSchema schema = core.getSchema();
double[] xy = new double[]{35.0, -79.34};
String point = xy[0] + "," + xy[1];
//How about some queries?
//don't need a parser for this path currently. This may change
assertU(adoc("id", "0", "home_ns", point));
assertU(commit());
SchemaField home = schema.getField("home_ns");
PointType pt = (PointType) home.getType();
assertEquals(pt.getDimension(), 2);
Query q = pt.getFieldQuery(null, home, point);
assertNotNull(q);
assertTrue(q instanceof BooleanQuery);
//should have two clauses, one for 35.0 and the other for -79.34
BooleanQuery bq = (BooleanQuery) q;
BooleanClause[] clauses = bq.getClauses();
assertEquals(clauses.length, 2);
clearIndex();
}
}
|
gpl-2.0
|
David-Desmaisons/MusicCollection
|
MusicCollectionWPF/MusicCollectionWPF/Windows/CustoMessageBox.xaml.cs
|
1292
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MusicCollectionWPF.ViewModelHelper;
using MusicCollectionWPF.ViewModel;
using MusicCollectionWPF.Infra;
namespace MusicCollectionWPF.Windows
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
[ViewModelBinding(typeof(InfoViewModel))]
public partial class CustoMessageBox : CustomWindow
{
public CustoMessageBox()
{
InitializeComponent();
}
public CustoMessageBox(string iMessage, string iTitle, bool iConfirmationnedded, string iMessageAdditional=null)
{
InfoViewModel ivm = new InfoViewModel()
{
Message = iMessage,
Title = iTitle,
ConfirmationNeeded = iConfirmationnedded,
MessageAdditional = iMessageAdditional,
IsOK = false,
Window = this
};
DataContext = ivm;
InitializeComponent();
}
}
}
|
gpl-2.0
|
DCLMonk/Pennyworth
|
Server/ClientPackets/DeviceDefPacket.cpp
|
1535
|
/**
* Pennyworth - A new smarthome protocol.
* Copyright (C) 2012 Dream-Crusher Labs LLC
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 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.
*/
/*
* DeviceDefPacket.cpp
*
* Created on: Jun 28, 2012
* Author: jmonk
*/
#include "DeviceDefPacket.h"
namespace dvs {
DeviceDefPacket::DeviceDefPacket(Device* device, User* user) : CPacket(DEVICE_DEF, user) {
this->device = device;
}
DeviceDefPacket::~DeviceDefPacket() {
}
void DeviceDefPacket::streamData(stringstream& data) {
data << ':';
data << device->getId();
data << ':';
data << device->getName();
data << ':';
data << device->getCName();
data << ':';
data << device->getRoom()->getId();
data << ':';
data << device->getIcon();
data << ':';
data << device->getX();
data << ':';
data << device->getY();
}
} /* namespace dvs */
|
gpl-2.0
|
georgejhunt/HaitiDictionary.activity
|
data/words/sitwonv~et.js
|
176
|
showWord(["n fr. "," Ti fwi piti, sitris, nan menm fanmi ak zorany; li si; yo fè limonad avèk li epi yo itilize l pou netwaye vyann tou. Sitwon vèt bon pou fè limonad."
])
|
gpl-2.0
|
RenatGilmanov/tau-usability-tool
|
src/main/net/taunova/usability/util/ThreadUtil.java
|
410
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.taunova.usability.util;
/**
*
* @author renat
*/
public class ThreadUtil {
public static final void sleep(int millis) {
try{
Thread.sleep(millis); //this will slow the capture rate to 0.1 seconds
}catch(Exception e) {
//...
}
}
}
|
gpl-2.0
|
JoelPub/wordpress-amazon
|
order/source/modules/reg/receiver.php
|
1545
|
<?php
/**
* 订阅就绑定FAKEID
*
* @author 19.3CM
* @QQ 81324093
*/
defined('IN_IA') or exit('Access Denied');
include_once IA_ROOT . '/source/modules/19.3cm.php';
class RegModuleReceiver extends WeModuleReceiver {
public function receive() {
global $_W;
//增加关注就插入最基础的FROMID和WEID 以及绑定微信号
if($this->message['type']=='subscribe'){
//高级权限号执行
$u=pdo_fetch("SELECT id,from_user,nickname,avatar FROM ".tablename('fans')." WHERE weid = '{$_W['weid']}' AND from_user='{$this->message['from']}' LIMIT 1");
if(empty($u['nickname'])||empty($u['avatar'])){
//增加判断用户昵称或者头像为空,才执行重取同步微信资料
$user=gj_getuserinfo($this->message['from']);
if(empty($u['from_user'])){
if(!empty($user['from_user'])){
pdo_insert('fans', $user);
}
}
else{
if(!empty($user['from_user'])){
unset($user['from_user']);
pdo_update('fans', $user, array('from_user' =>$this->message['from']));
}
}
//END
}
//end
}
/*
else{
if($this->message['type']!='unsubscribe'){
$u=pdo_fetch("SELECT id,from_user,nickname,avatar FROM ".tablename('fans')." WHERE weid = '{$_W['weid']}' AND from_user='{$this->message['from']}' LIMIT 1");
$user=gj_getuserinfo($this->message['from']);
if(empty($u['nickname'])||empty($u['avatar'])){
if(!empty($user['from_user'])){
pdo_insert('fans', $user);
}
}
}
}*/
}
}
|
gpl-2.0
|
bgarrels/freedomotic
|
plugins/devices/simulation/src/main/java/com/freedomotic/plugins/VariousSensors.java
|
5302
|
/**
*
* Copyright (c) 2009-2014 Freedomotic team http://freedomotic.com
*
* This file is part of Freedomotic
*
* 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, 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
* Freedomotic; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.freedomotic.plugins;
import com.freedomotic.api.EventTemplate;
import com.freedomotic.api.Protocol;
import com.freedomotic.events.ProtocolRead;
import com.freedomotic.exceptions.UnableToExecuteException;
import com.freedomotic.plugins.gui.VariousSensorsGui;
import com.freedomotic.reactions.Command;
import java.io.IOException;
/**
*
* @author Enrico
*/
public class VariousSensors extends Protocol {
private Boolean powered = false;
/**
*
*/
public VariousSensors() {
super("Sensors Simulator", "/simulation/sensors-simulator.xml");
setPollingWait(2000);
}
@Override
protected void onShowGui() {
bindGuiToPlugin(new VariousSensorsGui(this));
}
/**
*
*/
public void askSomething() {
final Command c = new Command();
c.setName("Ask something silly to user");
c.setDelay(0);
c.setExecuted(true);
c.setEditable(false);
c.setReceiver("app.actuators.frontend.javadesktop.in");
c.setProperty("question", "<html><h1>Do you like Freedomotic?</h1></html>");
c.setProperty("options", "Yes, it's good; No, it sucks; I don't know");
c.setReplyTimeout(10000); //10 seconds
new Thread(new Runnable() {
@Override
public void run() {
VariousSensorsGui guiHook = (VariousSensorsGui) gui;
Command reply = send(c);
if (reply != null) {
String userInput = reply.getProperty("result");
if (userInput != null) {
guiHook.updateDescription("The reply to the test question is " + userInput);
} else {
guiHook.updateDescription("The user has not responded to the question within the given time");
}
} else {
guiHook.updateDescription("Unreceived reply within given timeout (10 seconds)");
}
}
}).start();
}
public void executeNlpCommand(String text) {
final Command nlpCommand = new Command();
nlpCommand.setName("Recognize text with NLP");
nlpCommand.setReceiver("app.commands.interpreter.nlp");
nlpCommand.setDescription("A free-form text command to be interpreded by an NLP module");
nlpCommand.setProperty("text", text);
nlpCommand.setReplyTimeout(10000);
new Thread(new Runnable() {
@Override
public void run() {
VariousSensorsGui guiHook = (VariousSensorsGui) gui;
Command reply = send(nlpCommand);
if (reply != null) {
String executedCommand = reply.getProperty("result");
if (executedCommand != null) {
guiHook.updateDescription("Recognized command: " + executedCommand);
} else {
guiHook.updateDescription("No similar command exists");
}
} else {
guiHook.updateDescription("Unreceived reply within given timeout (10 seconds)");
}
}
}).start();
}
@Override
protected void onRun() {
//sends a fake sensor read event
ProtocolRead event = new ProtocolRead(this, "test", "test");
event.getPayload().addStatement("value",
powered.toString());
event.getPayload().addStatement("object.class", "Light");
event.getPayload().addStatement("object.name", "Created by VariousSensors");
//invert the value for the next round
notifyEvent(event);
if (powered) {
powered = false;
} else {
powered = true;
}
//wait two seconds before sending another event
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
@Override
protected void onCommand(Command c)
throws IOException, UnableToExecuteException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected boolean canExecute(Command c) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected void onEvent(EventTemplate event) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
gpl-2.0
|
trueg/virtuoso-opensource
|
binsrc/sesame/virtuoso_driver/VirtuosoExample3.java
|
4001
|
/*
* $Id$
*
* This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
* project.
*
* Copyright (C) 1998-2012 OpenLink Software
*
* This project 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; only version 2 of the License, dated June 1991.
*
* 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
*
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import org.openrdf.sesame.config.AccessDeniedException;
import org.openrdf.sesame.constants.RDFFormat;
import org.openrdf.sesame.query.MalformedQueryException;
import org.openrdf.sesame.query.QueryEvaluationException;
import org.openrdf.sesame.query.QueryResultsTable;
import org.openrdf.sesame.sail.NamespaceIterator;
import virtuoso.sesame.driver.*;
public class VirtuosoExample3
{
public static void main(String[] args)
{
// example query
try
{
VirtuosoAdminListener _report = new VirtuosoAdminListener();
VirtuosoRepository rep = new VirtuosoRepository("sesame", "jdbc:virtuoso://localhost:1111", "dba", "dba");
rep.clear(_report);
// TEST 1
File dataFile = new File("virtuoso_driver/data.nt");
System.out.println("TEST 1: Loading file " + dataFile.getAbsolutePath() + " ...");
rep.addData(dataFile, "http://localhost/", RDFFormat.NTRIPLES, false, _report);
String query = "SELECT ?s ?p ?o from <sesame> WHERE { ?s ?p ?o }";
QueryResultsTable result = rep.performTableQuery(null, query);
System.out.println("TEST 1: Passed = " + (result.getRowCount() > 0));
// TEST 2
System.out.println("TEST 2: Clearing repository ...");
rep.clear(_report);
query = "SELECT ?s ?p ?o from <sesame> WHERE { ?s ?p ?o }";
result = rep.performTableQuery(null, query);
System.out.println("TEST 2: Passed = " + (result.getRowCount() == 0));
// TEST 3
URL url = new URL("http://overdogg.com/rdf/requests/1"); //("http://demo.openlinksw.com/dataspace/person/demo#this");
System.out.println("TEST 3: Loading remote file: " + url.toString() + " ...");
rep.addData(url, "http://localhost/", RDFFormat.RDFXML, false, _report);
// execute query
query = "SELECT ?s ?p ?o from <sesame> WHERE { ?s ?p ?o }";
result = rep.performTableQuery(null, query);
System.out.println("TEST 3: Passed = " + (result.getRowCount() > 0));
// TEST 4
NamespaceIterator nss = rep.getNamespaces();
System.out.println("TEST 4: Passed = " + nss.hasNext());
}
catch (AccessDeniedException ade)
{
System.out.println("VirtuosoTest.main() Access denied.");
System.out.println(ade.getMessage());
}
catch (FileNotFoundException fnfe)
{
System.out.println("VirtuosoTest.main() File not found.");
System.out.println(fnfe.getMessage());
}
catch (IOException ioe)
{
System.out.println("VirtuosoTest.main() I/O error.");
System.out.println(ioe.getMessage());
}
catch (QueryEvaluationException qee)
{
System.out.println("VirtuosoTest.main() QueryEvaluationException.");
System.out.println(qee.getMessage());
}
catch (MalformedQueryException mqe)
{
System.out.println("VirtuosoTest.main() Malformed query - SimpleExample.");
System.out.println(mqe.getMessage());
mqe.printStackTrace();
}
catch (ClassCastException cce)
{
System.out.println("VirtuosoTest.main() ClassCastException.");
System.out.println(cce.getMessage());
cce.printStackTrace();
}
}
}
|
gpl-2.0
|
jaanusnurmoja/redjoomla
|
components/com_redevent/views/details/view.csv.php
|
3355
|
<?php
/**
* @version 1.0 $Id: view.html.php 1625 2009-11-18 16:54:27Z julien $
* @package Joomla
* @subpackage redEVENT
* @copyright redEVENT (C) 2008 redCOMPONENT.com / EventList (C) 2005 - 2008 Christoph Lukes
* @license GNU/GPL, see LICENSE.php
* redEVENT is based on EventList made by Christoph Lukes from schlu.net
* redEVENT can be downloaded from www.redcomponent.com
* redEVENT is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
* redEVENT 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 redEVENT; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.view');
/**
* CSV Details View class of the redEVENT component
*
* @package Joomla
* @subpackage redEVENT
* @since 2.0
*/
class RedeventViewDetails extends JView
{
/**
* Creates the output for the details view
*
* @since 2.0
*/
function display($tpl = null)
{
if ($this->getLayout() == 'exportattendees') {
return $this->_displayAttendees($tpl);
}
echo 'layout not found';
}
/**
* Creates the attendees output for the details view
*
* @since 2.0
*/
function _displayAttendees($tpl = null)
{
jimport('joomla.filesystem.file');
$model = $this->getModel();
if (!$this->get('ManageAttendees')) {
JError::raiseError(403, 'Not authorized');
}
$event = $this->get('Details');
$registers = $model->getRegisters(true, true);
$text = "";
if (count($registers))
{
$fields = array();
foreach ($registers[0]->fields AS $f) {
$fields[] = $f;
}
$text .= $this->writecsvrow($fields);
foreach((array) $registers as $r)
{
$data = array();
foreach ($r->answers as $val)
{
if (stristr($val, '~~~')) {
$val = str_replace('~~~', '\n', $val);
}
$data[] = $val;
}
$text .= $this->writecsvrow($data);
}
}
else {
//$text = "no attendees";
}
if (!redEVENTHelper::isValidDate($event->dates)) {
$event->dates = JText::_('COM_REDEVENT_OPEN_DATE');
}
$title = JFile::makeSafe($event->full_title .'_'. $event->dates .'_'. $event->venue .'.csv');
$doc =& JFactory::getDocument();
$doc->setMimeEncoding('text/csv');
header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Content-Disposition: attachment; filename="'.$title.'"');
header('Pragma: no-cache');
echo $text;
}
function writecsvrow($fields, $delimiter = ',', $enclosure = '"')
{
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ($fields as $field) {
$output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? (
$enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure
) : $field;
}
return join($delimiter, $output) . "\n";
}
}
|
gpl-2.0
|
wells369/Rubato
|
java/src/org/rubato/rubettes/denotex/Token.java
|
2674
|
/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
package org.rubato.rubettes.denotex;
/**
* Describes the input token stream.
*/
public class Token {
/**
* An integer that describes the kind of this token. This numbering
* system is determined by JavaCCParser, and a table of these numbers is
* stored in the file ...Constants.java.
*/
public int kind;
/**
* beginLine and beginColumn describe the position of the first character
* of this token; endLine and endColumn describe the position of the
* last character of this token.
*/
public int beginLine, beginColumn, endLine, endColumn;
/**
* The string image of the token.
*/
public String image;
/**
* A reference to the next regular (non-special) token from the input
* stream. If this is the last token from the input stream, or if the
* token manager has not read tokens beyond this one, this field is
* set to null. This is true only if this token is also a regular
* token. Otherwise, see below for a description of the contents of
* this field.
*/
public Token next;
/**
* This field is used to access special tokens that occur prior to this
* token, but after the immediately preceding regular (non-special) token.
* If there are no such special tokens, this field is set to null.
* When there are more than one such special token, this field refers
* to the last of these special tokens, which in turn refers to the next
* previous special token through its specialToken field, and so on
* until the first special token (whose specialToken field is null).
* The next fields of special tokens refer to other special tokens that
* immediately follow it (without an intervening regular token). If there
* is no such token, this field is null.
*/
public Token specialToken;
/**
* Returns the image.
*/
public String toString()
{
return image;
}
/**
* Returns a new Token object, by default. However, if you want, you
* can create and return subclass objects based on the value of ofKind.
* Simply add the cases to the switch for all those special cases.
* For example, if you have a subclass of Token called IDToken that
* you want to create if ofKind is ID, simlpy add something like :
*
* case MyParserConstants.ID : return new IDToken();
*
* to the following switch statement. Then you can cast matchedToken
* variable to the appropriate type and use it in your lexical actions.
*/
public static final Token newToken(int ofKind)
{
switch(ofKind)
{
default : return new Token();
}
}
}
|
gpl-2.0
|
etiko/thegossipfeed
|
sites/all/themes/tgf/views-view.tpl.php
|
1640
|
<?php
/**
* @file
* Main view template.
*
* Variables available:
* - $classes_array: An array of classes determined in
* template_preprocess_views_view(). Default classes are:
* .view
* .view-[css_name]
* .view-id-[view_name]
* .view-display-id-[display_name]
* .view-dom-id-[dom_id]
* - $classes: A string version of $classes_array for use in the class attribute
* - $css_name: A css-safe version of the view name.
* - $css_class: The user-specified classes names, if any
* - $header: The view header
* - $footer: The view footer
* - $rows: The results of the view query, if any
* - $empty: The empty text to display if the view is empty
* - $pager: The pager next/prev links to display, if any
* - $exposed: Exposed widget form/info to display
* - $feed_icon: Feed icon to display, if any
* - $more: A link to view more, if any
*
* @ingroup views_templates
*/
?>
<?php
print '<div class="'.$classes.'">';
print render($title_prefix);
if ($title){print $title;}
print render($title_suffix);
if ($header){print '<div class="view-header">'.$header.'</div>';}
if ($exposed){print '<div class="view-filters">'.$exposed.'</div>';}
if ($attachment_before){print '<div class="attachment attachment-before">'.$attachment_before.'</div>';}
if ($rows){print $rows;}
if ($pager){print $pager;}
if ($attachment_after){print '<div class="attachment attachment-after">'.$attachment_after.'</div>';}
if ($more){print $more;}
if ($footer){print '<div class="view-footer">'.$footer.'</div>';}
if ($feed_icon){print '<div class="feed-icon">'.$feed_icon.'</div>';}
print '</div>';
|
gpl-2.0
|
Riketta/Stronghold-Kingdoms
|
StrongholdKingdoms/Kingdoms/VillageLostReportPanelDerived.cs
|
1061
|
namespace Kingdoms
{
using CommonTypes;
using System;
internal class VillageLostReportPanelDerived : GenericReportPanelBasic
{
public override void setData(GetReport_ReturnType returnData)
{
base.setData(returnData);
base.lblMainText.Text = SK.Text("Reports_VillageLost", "Village Lost");
if (returnData.otherUser.Length == 0)
{
base.lblSubTitle.Text = SK.Text("Reports_VillageLost_inactivity", "Village Lost due to Inactivity");
}
else if (returnData.reportType == 0x80)
{
base.lblSubTitle.Text = SK.Text("Reports_VillageLost_abandoned", "Village Abandoned");
}
else
{
base.lblSubTitle.Text = SK.Text("Reports_VillageLost_attacked by", "Attacked By") + " : " + returnData.otherUser;
}
base.lblSecondaryText.Text = GameEngine.Instance.World.getVillageName(returnData.defendingVillage);
}
}
}
|
gpl-2.0
|
athiasjerome/XORCISM
|
SOURCES/XORCISMModel/OPERATORENUMERATION.cs
|
1661
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace XORCISMModel
{
using System;
using System.Collections.Generic;
public partial class OPERATORENUMERATION
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public OPERATORENUMERATION()
{
this.CPELOGICALTEST = new HashSet<CPELOGICALTEST>();
}
public int OperatorEnumerationID { get; set; }
public string OperatorValue { get; set; }
public string OperatorDescription { get; set; }
public Nullable<System.DateTimeOffset> CreatedDate { get; set; }
public Nullable<System.DateTimeOffset> timestamp { get; set; }
public Nullable<int> VocabularyID { get; set; }
public Nullable<bool> isEncrypted { get; set; }
public Nullable<System.DateTimeOffset> ValidFromDate { get; set; }
public Nullable<System.DateTimeOffset> ValidUntilDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CPELOGICALTEST> CPELOGICALTEST { get; set; }
public virtual VOCABULARY VOCABULARY { get; set; }
}
}
|
gpl-2.0
|
wpsmith/WP-API
|
tests/test-rest-terms-controller.php
|
25885
|
<?php
/**
* Unit tests covering WP_REST_Terms_Controller functionality.
*
* @package WordPress
* @subpackage JSON API
*/
class WP_Test_REST_Terms_Controller extends WP_Test_REST_Controller_Testcase {
public function setUp() {
parent::setUp();
$this->administrator = $this->factory->user->create( array(
'role' => 'administrator',
) );
$this->subscriber = $this->factory->user->create( array(
'role' => 'subscriber',
) );
}
public function test_register_routes() {
$routes = $this->server->get_routes();
$this->assertArrayHasKey( '/wp/v2/categories', $routes );
$this->assertArrayHasKey( '/wp/v2/categories/(?P<id>[\d]+)', $routes );
$this->assertArrayHasKey( '/wp/v2/tags', $routes );
$this->assertArrayHasKey( '/wp/v2/tags/(?P<id>[\d]+)', $routes );
}
public function test_context_param() {
// Collection
$request = new WP_REST_Request( 'OPTIONS', '/wp/v2/tags' );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] );
$this->assertEquals( array( 'view', 'embed' ), $data['endpoints'][0]['args']['context']['enum'] );
// Single
$tag1 = $this->factory->tag->create( array( 'name' => 'Season 5' ) );
$request = new WP_REST_Request( 'OPTIONS', '/wp/v2/tags/' . $tag1 );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] );
$this->assertEquals( array( 'view', 'embed' ), $data['endpoints'][0]['args']['context']['enum'] );
}
public function test_get_items() {
$request = new WP_REST_Request( 'GET', '/wp/v2/categories' );
$response = $this->server->dispatch( $request );
$this->check_get_taxonomy_terms_response( $response );
}
public function test_get_items_hide_empty_arg() {
$post_id = $this->factory->post->create();
$tag1 = $this->factory->tag->create( array( 'name' => 'Season 5' ) );
$tag2 = $this->factory->tag->create( array( 'name' => 'The Be Sharps' ) );
wp_set_object_terms( $post_id, array( $tag1, $tag2 ), 'post_tag' );
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'hide_empty', true );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 2, count( $data ) );
$this->assertEquals( 'Season 5', $data[0]['name'] );
$this->assertEquals( 'The Be Sharps', $data[1]['name'] );
}
public function test_get_items_parent_zero_arg() {
$parent1 = $this->factory->category->create( array( 'name' => 'Homer' ) );
$parent2 = $this->factory->category->create( array( 'name' => 'Marge' ) );
$child1 = $this->factory->category->create(
array(
'name' => 'Bart',
'parent' => $parent1,
)
);
$child2 = $this->factory->category->create(
array(
'name' => 'Lisa',
'parent' => $parent2,
)
);
$request = new WP_REST_Request( 'GET', '/wp/v2/categories' );
$request->set_param( 'parent', 0 );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$args = array(
'hide_empty' => false,
'parent' => 0,
);
$categories = get_terms( 'category', $args );
$this->assertEquals( count( $categories ), count( $data ) );
}
public function test_get_items_parent_zero_arg_string() {
$parent1 = $this->factory->category->create( array( 'name' => 'Homer' ) );
$parent2 = $this->factory->category->create( array( 'name' => 'Marge' ) );
$child1 = $this->factory->category->create(
array(
'name' => 'Bart',
'parent' => $parent1,
)
);
$child2 = $this->factory->category->create(
array(
'name' => 'Lisa',
'parent' => $parent2,
)
);
$request = new WP_REST_Request( 'GET', '/wp/v2/categories' );
$request->set_param( 'parent', '0' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$args = array(
'hide_empty' => false,
'parent' => 0,
);
$categories = get_terms( 'category', $args );
$this->assertEquals( count( $categories ), count( $data ) );
}
public function test_get_items_by_parent_non_found() {
$parent1 = $this->factory->category->create( array( 'name' => 'Homer' ) );
$request = new WP_REST_Request( 'GET', '/wp/v2/categories' );
$request->set_param( 'parent', $parent1 );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( array(), $data );
}
public function test_get_items_orderby_args() {
$tag1 = $this->factory->tag->create( array( 'name' => 'Apple' ) );
$tag2 = $this->factory->tag->create( array( 'name' => 'Banana' ) );
/*
* Tests:
* - orderby
* - order
* - per_page
*/
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'orderby', 'name' );
$request->set_param( 'order', 'desc' );
$request->set_param( 'per_page', 1 );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 1, count( $data ) );
$this->assertEquals( 'Banana', $data[0]['name'] );
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'orderby', 'name' );
$request->set_param( 'order', 'asc' );
$request->set_param( 'per_page', 2 );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 2, count( $data ) );
$this->assertEquals( 'Apple', $data[0]['name'] );
}
public function test_get_items_post_args() {
$post_id = $this->factory->post->create();
$tag1 = $this->factory->tag->create( array( 'name' => 'DC' ) );
$tag2 = $this->factory->tag->create( array( 'name' => 'Marvel' ) );
wp_set_object_terms( $post_id, array( $tag1, $tag2 ), 'post_tag' );
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'post', $post_id );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 2, count( $data ) );
$this->assertEquals( 'DC', $data[0]['name'] );
}
public function test_get_items_custom_tax_post_args() {
register_taxonomy( 'batman', 'post', array( 'show_in_rest' => true ) );
$controller = new WP_REST_Terms_Controller( 'batman' );
$controller->register_routes();
$term1 = $this->factory->term->create( array( 'name' => 'Cape', 'taxonomy' => 'batman' ) );
$term2 = $this->factory->term->create( array( 'name' => 'Mask', 'taxonomy' => 'batman' ) );
$post_id = $this->factory->post->create();
wp_set_object_terms( $post_id, array( $term1, $term2 ), 'batman' );
$request = new WP_REST_Request( 'GET', '/wp/v2/batman' );
$request->set_param( 'post', $post_id );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 2, count( $data ) );
$this->assertEquals( 'Cape', $data[0]['name'] );
}
public function test_get_items_search_args() {
$tag1 = $this->factory->tag->create( array( 'name' => 'Apple' ) );
$tag2 = $this->factory->tag->create( array( 'name' => 'Banana' ) );
/*
* Tests:
* - search
*/
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'search', 'App' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 1, count( $data ) );
$this->assertEquals( 'Apple', $data[0]['name'] );
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'search', 'Garbage' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 0, count( $data ) );
}
public function test_get_terms_parent_arg() {
$category1 = $this->factory->category->create( array( 'name' => 'Parent' ) );
$category2 = $this->factory->category->create( array( 'name' => 'Child', 'parent' => $category1 ) );
$request = new WP_REST_Request( 'GET', '/wp/v2/categories' );
$request->set_param( 'parent', $category1 );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$this->assertEquals( 1, count( $data ) );
$this->assertEquals( 'Child', $data[0]['name'] );
}
public function test_get_terms_private_taxonomy() {
register_taxonomy( 'robin', 'post', array( 'public' => false ) );
$term1 = $this->factory->term->create( array( 'name' => 'Cape', 'taxonomy' => 'robin' ) );
$term2 = $this->factory->term->create( array( 'name' => 'Mask', 'taxonomy' => 'robin' ) );
$request = new WP_REST_Request( 'GET', '/wp/v2/terms/robin' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_no_route', $response, 404 );
}
public function test_get_terms_invalid_taxonomy() {
$request = new WP_REST_Request( 'GET', '/wp/v2/terms/invalid-taxonomy' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_no_route', $response, 404 );
}
public function test_get_terms_pagination_headers() {
// Start of the index
for ( $i = 0; $i < 50; $i++ ) {
$this->factory->tag->create( array(
'name' => "Tag {$i}",
) );
}
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$response = $this->server->dispatch( $request );
$headers = $response->get_headers();
$this->assertEquals( 50, $headers['X-WP-Total'] );
$this->assertEquals( 5, $headers['X-WP-TotalPages'] );
$next_link = add_query_arg( array(
'page' => 2,
), rest_url( '/wp/v2/tags' ) );
$this->assertFalse( stripos( $headers['Link'], 'rel="prev"' ) );
$this->assertContains( '<' . $next_link . '>; rel="next"', $headers['Link'] );
// 3rd page
$this->factory->tag->create( array(
'name' => 'Tag 51',
) );
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'page', 3 );
$response = $this->server->dispatch( $request );
$headers = $response->get_headers();
$this->assertEquals( 51, $headers['X-WP-Total'] );
$this->assertEquals( 6, $headers['X-WP-TotalPages'] );
$prev_link = add_query_arg( array(
'page' => 2,
), rest_url( '/wp/v2/tags' ) );
$this->assertContains( '<' . $prev_link . '>; rel="prev"', $headers['Link'] );
$next_link = add_query_arg( array(
'page' => 4,
), rest_url( '/wp/v2/tags' ) );
$this->assertContains( '<' . $next_link . '>; rel="next"', $headers['Link'] );
// Last page
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'page', 6 );
$response = $this->server->dispatch( $request );
$headers = $response->get_headers();
$this->assertEquals( 51, $headers['X-WP-Total'] );
$this->assertEquals( 6, $headers['X-WP-TotalPages'] );
$prev_link = add_query_arg( array(
'page' => 5,
), rest_url( '/wp/v2/tags' ) );
$this->assertContains( '<' . $prev_link . '>; rel="prev"', $headers['Link'] );
$this->assertFalse( stripos( $headers['Link'], 'rel="next"' ) );
// Out of bounds
$request = new WP_REST_Request( 'GET', '/wp/v2/tags' );
$request->set_param( 'page', 8 );
$response = $this->server->dispatch( $request );
$headers = $response->get_headers();
$this->assertEquals( 51, $headers['X-WP-Total'] );
$this->assertEquals( 6, $headers['X-WP-TotalPages'] );
$prev_link = add_query_arg( array(
'page' => 6,
), rest_url( '/wp/v2/tags' ) );
$this->assertContains( '<' . $prev_link . '>; rel="prev"', $headers['Link'] );
$this->assertFalse( stripos( $headers['Link'], 'rel="next"' ) );
}
public function test_get_item() {
$request = new WP_REST_Request( 'GET', '/wp/v2/categories/1' );
$response = $this->server->dispatch( $request );
$this->check_get_taxonomy_term_response( $response );
}
public function test_get_term_invalid_taxonomy() {
$request = new WP_REST_Request( 'GET', '/wp/v2/terms/invalid-taxonomy/1' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_no_route', $response, 404 );
}
public function test_get_term_invalid_term() {
$request = new WP_REST_Request( 'GET', '/wp/v2/categories/' . REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_term_invalid', $response, 404 );
}
public function test_get_term_private_taxonomy() {
register_taxonomy( 'robin', 'post', array( 'public' => false ) );
$term1 = $this->factory->term->create( array( 'name' => 'Cape', 'taxonomy' => 'robin' ) );
$request = new WP_REST_Request( 'GET', '/wp/v2/terms/robin/' . $term1 );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_no_route', $response, 404 );
}
public function test_get_item_incorrect_taxonomy() {
register_taxonomy( 'robin', 'post' );
$term1 = $this->factory->term->create( array( 'name' => 'Cape', 'taxonomy' => 'robin' ) );
$request = new WP_REST_Request( 'GET', '/wp/v2/categories/' . $term1 );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_term_invalid', $response, 404 );
}
public function test_create_item() {
wp_set_current_user( $this->administrator );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories' );
$request->set_param( 'name', 'My Awesome Term' );
$request->set_param( 'description', 'This term is so awesome.' );
$request->set_param( 'slug', 'so-awesome' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 201, $response->get_status() );
$headers = $response->get_headers();
$data = $response->get_data();
$this->assertContains( '/wp/v2/categories/' . $data['id'], $headers['Location'] );
$this->assertEquals( 'My Awesome Term', $data['name'] );
$this->assertEquals( 'This term is so awesome.', $data['description'] );
$this->assertEquals( 'so-awesome', $data['slug'] );
}
public function test_create_item_invalid_taxonomy() {
wp_set_current_user( $this->administrator );
$request = new WP_REST_Request( 'POST', '/wp/v2/terms/invalid-taxonomy' );
$request->set_param( 'name', 'Invalid Taxonomy' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_no_route', $response, 404 );
}
public function test_create_item_incorrect_permissions() {
wp_set_current_user( $this->subscriber );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories' );
$request->set_param( 'name', 'Incorrect permissions' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_forbidden', $response, 403 );
}
public function test_create_item_missing_arguments() {
wp_set_current_user( $this->administrator );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_missing_callback_param', $response, 400 );
}
public function test_create_item_with_parent() {
wp_set_current_user( $this->administrator );
$parent = wp_insert_term( 'test-category', 'category' );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories' );
$request->set_param( 'name', 'My Awesome Term' );
$request->set_param( 'parent', $parent['term_id'] );
$response = $this->server->dispatch( $request );
$this->assertEquals( 201, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( $parent['term_id'], $data['parent'] );
}
public function test_create_item_invalid_parent() {
wp_set_current_user( $this->administrator );
$term = get_term_by( 'id', $this->factory->category->create(), 'category' );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories/' . $term->term_id );
$request->set_param( 'name', 'My Awesome Term' );
$request->set_param( 'parent', REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_term_invalid', $response, 400 );
}
public function test_create_item_parent_non_hierarchical_taxonomy() {
wp_set_current_user( $this->administrator );
$request = new WP_REST_Request( 'POST', '/wp/v2/tags' );
$request->set_param( 'name', 'My Awesome Term' );
$request->set_param( 'parent', REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_taxonomy_not_hierarchical', $response, 400 );
}
public function test_update_item() {
wp_set_current_user( $this->administrator );
$orig_args = array(
'name' => 'Original Name',
'description' => 'Original Description',
'slug' => 'original-slug',
);
$term = get_term_by( 'id', $this->factory->category->create( $orig_args ), 'category' );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories/' . $term->term_id );
$request->set_param( 'name', 'New Name' );
$request->set_param( 'description', 'New Description' );
$request->set_param( 'slug', 'new-slug' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 'New Name', $data['name'] );
$this->assertEquals( 'New Description', $data['description'] );
$this->assertEquals( 'new-slug', $data['slug'] );
}
public function test_update_item_invalid_taxonomy() {
wp_set_current_user( $this->administrator );
$request = new WP_REST_Request( 'POST', '/wp/v2/terms/invalid-taxonomy/' . REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$request->set_param( 'name', 'Invalid Taxonomy' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_no_route', $response, 404 );
}
public function test_update_item_invalid_term() {
wp_set_current_user( $this->administrator );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories/' . REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$request->set_param( 'name', 'Invalid Term' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_term_invalid', $response, 404 );
}
public function test_update_item_incorrect_permissions() {
wp_set_current_user( $this->subscriber );
$term = get_term_by( 'id', $this->factory->category->create(), 'category' );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories/' . $term->term_id );
$request->set_param( 'name', 'Incorrect permissions' );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_forbidden', $response, 403 );
}
public function test_update_item_parent() {
wp_set_current_user( $this->administrator );
$parent = get_term_by( 'id', $this->factory->category->create(), 'category' );
$term = get_term_by( 'id', $this->factory->category->create(), 'category' );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories/' . $term->term_taxonomy_id );
$request->set_param( 'parent', $parent->term_id );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( $parent->term_id, $data['parent'] );
}
public function test_update_item_invalid_parent() {
wp_set_current_user( $this->administrator );
$term = get_term_by( 'id', $this->factory->category->create(), 'category' );
$request = new WP_REST_Request( 'POST', '/wp/v2/categories/' . $term->term_id );
$request->set_param( 'parent', REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_term_invalid', $response, 400 );
}
public function test_update_item_parent_non_hierarchical_taxonomy() {
wp_set_current_user( $this->administrator );
$term = get_term_by( 'id', $this->factory->tag->create(), 'post_tag' );
$request = new WP_REST_Request( 'POST', '/wp/v2/tags/' . $term->term_taxonomy_id );
$request->set_param( 'parent', REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_taxonomy_not_hierarchical', $response, 400 );
}
public function test_delete_item() {
wp_set_current_user( $this->administrator );
$term = get_term_by( 'id', $this->factory->category->create( array( 'name' => 'Deleted Category' ) ), 'category' );
$request = new WP_REST_Request( 'DELETE', '/wp/v2/categories/' . $term->term_id );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$this->assertEquals( 'Deleted Category', $data['data']['name'] );
$this->assertTrue( $data['deleted'] );
}
public function test_delete_item_invalid_taxonomy() {
wp_set_current_user( $this->administrator );
$request = new WP_REST_Request( 'DELETE', '/wp/v2/terms/invalid-taxonomy/' . REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_no_route', $response, 404 );
}
public function test_delete_item_invalid_term() {
wp_set_current_user( $this->administrator );
$request = new WP_REST_Request( 'DELETE', '/wp/v2/categories/' . REST_TESTS_IMPOSSIBLY_HIGH_NUMBER );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_term_invalid', $response, 404 );
}
public function test_delete_item_incorrect_permissions() {
wp_set_current_user( $this->subscriber );
$term = get_term_by( 'id', $this->factory->category->create(), 'category' );
$request = new WP_REST_Request( 'DELETE', '/wp/v2/categories/' . $term->term_id );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'rest_forbidden', $response, 403 );
}
public function test_prepare_item() {
$term = get_term( 1, 'category' );
$request = new WP_REST_Request( 'GET', '/wp/v2/categories/1' );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$this->check_taxonomy_term( $term, $data, $response->get_links() );
}
public function test_prepare_taxonomy_term_child() {
$child = $this->factory->category->create( array(
'parent' => 1,
) );
$term = get_term( $child, 'category' );
$request = new WP_REST_Request( 'GET', '/wp/v2/categories/' . $child );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$this->check_taxonomy_term( $term, $data, $response->get_links() );
$this->assertEquals( 1, $data['parent'] );
$links = $response->get_links();
$this->assertEquals( rest_url( '/wp/v2/categories/1' ), $links['up'][0]['href'] );
}
public function test_get_item_schema() {
$request = new WP_REST_Request( 'OPTIONS', '/wp/v2/categories' );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$properties = $data['schema']['properties'];
$this->assertEquals( 8, count( $properties ) );
$this->assertArrayHasKey( 'id', $properties );
$this->assertArrayHasKey( 'count', $properties );
$this->assertArrayHasKey( 'description', $properties );
$this->assertArrayHasKey( 'link', $properties );
$this->assertArrayHasKey( 'name', $properties );
$this->assertArrayHasKey( 'parent', $properties );
$this->assertArrayHasKey( 'slug', $properties );
$this->assertArrayHasKey( 'taxonomy', $properties );
$this->assertEquals( array_keys( get_taxonomies() ), $properties['taxonomy']['enum'] );
}
public function test_get_item_schema_non_hierarchical() {
$request = new WP_REST_Request( 'OPTIONS', '/wp/v2/tags' );
$response = $this->server->dispatch( $request );
$data = $response->get_data();
$properties = $data['schema']['properties'];
$this->assertArrayHasKey( 'id', $properties );
$this->assertFalse( isset( $properties['parent'] ) );
}
public function tearDown() {
_unregister_taxonomy( 'batman' );
_unregister_taxonomy( 'robin' );
parent::tearDown();
}
protected function check_get_taxonomy_terms_response( $response ) {
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$args = array(
'hide_empty' => false,
);
$categories = get_terms( 'category', $args );
$this->assertEquals( count( $categories ), count( $data ) );
$this->assertEquals( $categories[0]->term_id, $data[0]['id'] );
$this->assertEquals( $categories[0]->name, $data[0]['name'] );
$this->assertEquals( $categories[0]->slug, $data[0]['slug'] );
$this->assertEquals( $categories[0]->taxonomy, $data[0]['taxonomy'] );
$this->assertEquals( $categories[0]->description, $data[0]['description'] );
$this->assertEquals( $categories[0]->count, $data[0]['count'] );
}
protected function check_taxonomy_term( $term, $data, $links ) {
$this->assertEquals( $term->term_id, $data['id'] );
$this->assertEquals( $term->name, $data['name'] );
$this->assertEquals( $term->slug, $data['slug'] );
$this->assertEquals( $term->description, $data['description'] );
$this->assertEquals( get_term_link( $term ), $data['link'] );
$this->assertEquals( $term->count, $data['count'] );
$taxonomy = get_taxonomy( $term->taxonomy );
if ( $taxonomy->hierarchical ) {
$this->assertEquals( $term->parent, $data['parent'] );
} else {
$this->assertFalse( isset( $term->parent ) );
}
$this->assertArrayHasKey( 'self', $links );
$this->assertArrayHasKey( 'collection', $links );
$this->assertContains( 'wp/v2/taxonomies/' . $term->taxonomy, $links['about'][0]['href'] );
}
protected function check_get_taxonomy_term_response( $response ) {
$this->assertEquals( 200, $response->get_status() );
$data = $response->get_data();
$category = get_term( 1, 'category' );
$this->check_taxonomy_term( $category, $data, $response->get_links() );
}
}
|
gpl-2.0
|
botswana-harvard/edc-calendar
|
edc_calendar/models/update_or_create_event_model_mixin.py
|
2108
|
from django.apps import apps as django_apps
from django.db import models
from .event import Event
class UpdatesOrCreatesCalenderEventModelError(Exception):
pass
class UpdatesOrCreatesCalenderEventModelMixin(models.Model):
"""A model mixin that creates or updates a calendar event
on post_save signal.
"""
def create_or_update_calendar_event(self):
"""Creates or Updates the event model with attributes
from this instance.
Called from the signal
"""
if not getattr(self, self.identifier_field) and not getattr(self, self.title_field):
raise UpdatesOrCreatesCalenderEventModelError(
f'Cannot update or create Calender Event. '
f'Field value for \'{self.identifier_field}\' is None.')
event_value = getattr(self, self.identifier_field)
title_value = getattr(self, self.title_field)
if getattr(self, self.second_title_field):
title_value += str(getattr(self, self.second_title_field))
try:
Event.objects.get(**{
self.identifier_field: event_value,
'title': title_value})
except Event.DoesNotExist:
Event.objects.create(
**{self.identifier_field: event_value, 'title': title_value},
**self.event_options)
@property
def identifier_field(self):
"""Returns the field attr on YOUR model that will update
`identifier_field`.
"""
return 'subject_identifier'
@property
def title_field(self):
"""Returns the field attr on YOUR model that will update
`title`.
"""
return 'visit_code'
@property
def second_title_field(self):
"""Returns the field attr on YOUR model that will update
`title`.
"""
return 'visit_code_sequence'
@property
def event_options(self):
"""Returns the dict of the following attrs
`description` `start_time` `end_time`.
"""
return {}
class Meta:
abstract = True
|
gpl-2.0
|
marcomnc/magento2bloming
|
app/code/local/MpsSistemi/Gui/Helper/Blomming.php
|
1908
|
<?php
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* @category
* @package
* @copyright Copyright (c) 2013 Mps Sistemi (http://www.mps-sistemi.it)
* @author MPS Sistemi S.a.s - Marco Mancinelli <marco.mancinelli@mps-sistemi.it>
*
*/
class MpsSistemi_Gui_Helper_Blomming extends MpsSistemi_Gui_Helper_Data {
/**
* Normalizzo il filtro prodottiper blomming
* @param array $filter
*/
public function NomalizeProductFilter($filter) {
$fCat = '';
if (isset($filter['filter']['category'])) {
$fCat = implode(',', $filter['filter']['category']);
}
$filter['filter']['category'] = $fCat;
return $filter;
}
public function ValidateProductFilter($filter) {
$validate = "";
if (($filter['filter']['type'] === 0) ||
($filter['filter']['type'] != Mage_Catalog_Model_Product_Type::TYPE_SIMPLE &&
$filter['filter']['type'] != Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)) {
$validate .= $this->__('Product Type not allowed. Only Simple or Configurable ');
}
return $validate;
}
}
|
gpl-2.0
|
stweil/TYPO3.CMS
|
typo3/sysext/impexp/Classes/Utility/ImportExportUtility.php
|
2685
|
<?php
declare(strict_types=1);
/*
* 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!
*/
namespace TYPO3\CMS\Impexp\Utility;
use Psr\EventDispatcher\EventDispatcherInterface;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Impexp\Event\BeforeImportEvent;
use TYPO3\CMS\Impexp\Import;
/**
* Utility for import / export
* Can be used for API access for simple importing of files.
*
* @internal This class is not considered part of the public TYPO3 API.
*/
class ImportExportUtility
{
protected ?Import $import = null;
protected EventDispatcherInterface $eventDispatcher;
public function __construct(EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
public function getImport(): ?Import
{
return $this->import;
}
/**
* Import a T3D file directly
*
* @param string $file The full absolute path to the file
* @param int $pid The pid under which the t3d file should be imported
* @throws \ErrorException
* @return int ID of first created page
*/
public function importT3DFile(string $file, int $pid): int
{
$this->import = GeneralUtility::makeInstance(Import::class);
$this->import->setPid($pid);
$this->eventDispatcher->dispatch(new BeforeImportEvent($this->import));
try {
$this->import->loadFile($file, true);
$this->import->importData();
} catch (\Exception $e) {
$logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
$logger->warning(
$e->getMessage() . PHP_EOL . implode(PHP_EOL, $this->import->getErrorLog())
);
}
// Get id of first created page:
$importResponse = 0;
$importMapId = $this->import->getImportMapId();
if (isset($importMapId['pages'])) {
$newPages = $importMapId['pages'];
$importResponse = (int)reset($newPages);
}
// Check for errors during the import process:
if ($this->import->hasErrors()) {
if (!$importResponse) {
throw new \ErrorException('No page records imported', 1377625537);
}
}
return $importResponse;
}
}
|
gpl-2.0
|
saintcode/cenotexplore
|
src/wordpress/wp-content/plugins/travelpayouts/app/includes/common/TPCurrencyUtils.php
|
6569
|
<?php
/**
* Created by PhpStorm.
* User: freeman
* Date: 18.04.16
* Time: 17:43
*/
namespace app\includes\common;
use \app\includes\TPPlugin;
class TPCurrencyUtils
{
const TP_CURRENCY_RUB = 'RUB';
const TP_CURRENCY_USD = 'USD';
const TP_CURRENCY_EUR = 'EUR';
const TP_CURRENCY_BRL = 'BRL';
const TP_CURRENCY_CAD = 'CAD';
const TP_CURRENCY_CHF = 'CHF';
const TP_CURRENCY_HKD = 'HKD';
const TP_CURRENCY_IDR = 'IDR';
const TP_CURRENCY_INR = 'INR';
const TP_CURRENCY_NZD = 'NZD';
const TP_CURRENCY_PHP = 'PHP';
const TP_CURRENCY_PLN = 'PLN';
const TP_CURRENCY_SGD = 'SGD';
const TP_CURRENCY_THB = 'THB';
const TP_CURRENCY_GBP = 'GBP';
const TP_CURRENCY_ZAR = 'ZAR';
const TP_CURRENCY_UAH = 'UAH';
const TP_CURRENCY_KZT = 'KZT';
const TP_CURRENCY_AUD = 'AUD';
const TP_CURRENCY_TRY = 'TRY';
const TP_CURRENCY_ILS = 'ILS';
const TP_CURRENCY_ARS = 'ARS';
const TP_CURRENCY_COP = 'COP';
const TP_CURRENCY_PEN = 'PEN';
const TP_CURRENCY_CLP = 'CLP';
const TP_CURRENCY_AED = 'AED';
const TP_CURRENCY_SAR = 'SAR';
const TP_CURRENCY_SEK = 'SEK';
const TP_CURRENCY_HUF = 'HUF';
const TP_CURRENCY_KGS = 'KGS';
const TP_CURRENCY_MXN = 'MXN';
const TP_CURRENCY_AMD = 'AMD';
const TP_CURRENCY_XOF = 'XOF';
const TP_CURRENCY_VND = 'VND';
const TP_CURRENCY_BGN = 'BGN';
const TP_CURRENCY_GEL = 'GEL';
const TP_CURRENCY_RON = 'RON';
const TP_CURRENCY_DKK = 'DKK';
const TP_CURRENCY_BDT = 'BDT';
const TP_CURRENCY_KRW = 'KRW';
const TP_CURRENCY_RSD = 'RSD';
const TP_CURRENCY_AZN = 'AZN';
const TP_CURRENCY_BYN = 'BYN';
const TP_CURRENCY_CNY = 'CNY';
const TP_CURRENCY_EGP = 'EGP';
const TP_CURRENCY_JPY = 'JPY';
const TP_CURRENCY_MYR = 'MYR';
const TP_CURRENCY_NOK = 'NOK';
const TP_CURRENCY_PKR = 'PKR';
const TP_CURRENCY_BHD = 'BHD';
const TP_CURRENCY_CZK = 'CZK';
const TP_CURRENCY_IQD = 'IQD';
const TP_CURRENCY_ISK = 'ISK';
const TP_CURRENCY_JOD = 'JOD';
const TP_CURRENCY_KWD = 'KWD';
const TP_CURRENCY_LKR = 'LKR';
const TP_CURRENCY_LYD = 'LYD';
const TP_CURRENCY_MUR = 'MUR';
const TP_CURRENCY_NGN = 'NGN';
const TP_CURRENCY_NPR = 'NPR';
const TP_CURRENCY_OMR = 'OMR';
const TP_CURRENCY_QAR = 'QAR';
const TP_CURRENCY_TJS = 'TJS';
/**
* @return mixed
*/
public static function getCurrencyAll(){
$currency = array();
$currency = array(
//self::TP_CURRENCY_RUB,
//self::TP_CURRENCY_USD,
//self::TP_CURRENCY_EUR,
self::TP_CURRENCY_BRL,
self::TP_CURRENCY_CAD,
self::TP_CURRENCY_CHF,
self::TP_CURRENCY_HKD,
self::TP_CURRENCY_IDR,
self::TP_CURRENCY_INR,
self::TP_CURRENCY_NZD,
self::TP_CURRENCY_PHP,
self::TP_CURRENCY_PLN,
self::TP_CURRENCY_SGD,
self::TP_CURRENCY_THB,
self::TP_CURRENCY_GBP,
self::TP_CURRENCY_ZAR,
self::TP_CURRENCY_UAH,
self::TP_CURRENCY_KZT,
self::TP_CURRENCY_AUD,
self::TP_CURRENCY_TRY,
self::TP_CURRENCY_ILS,
self::TP_CURRENCY_ARS,
self::TP_CURRENCY_COP,
self::TP_CURRENCY_PEN,
self::TP_CURRENCY_CLP,
self::TP_CURRENCY_AED,
self::TP_CURRENCY_SAR,
self::TP_CURRENCY_SEK,
self::TP_CURRENCY_HUF,
self::TP_CURRENCY_KGS,
self::TP_CURRENCY_MXN,
self::TP_CURRENCY_AMD,
self::TP_CURRENCY_XOF,
self::TP_CURRENCY_VND,
self::TP_CURRENCY_BGN,
self::TP_CURRENCY_GEL,
self::TP_CURRENCY_RON,
self::TP_CURRENCY_DKK,
self::TP_CURRENCY_BDT,
self::TP_CURRENCY_KRW,
self::TP_CURRENCY_RSD,
self::TP_CURRENCY_AZN,
self::TP_CURRENCY_BYN,
self::TP_CURRENCY_CNY,
self::TP_CURRENCY_EGP,
self::TP_CURRENCY_JPY,
self::TP_CURRENCY_MYR,
self::TP_CURRENCY_NOK,
self::TP_CURRENCY_PKR,
self::TP_CURRENCY_BHD,
self::TP_CURRENCY_CZK,
self::TP_CURRENCY_IQD,
self::TP_CURRENCY_ISK,
self::TP_CURRENCY_JOD,
self::TP_CURRENCY_KWD,
self::TP_CURRENCY_LKR,
self::TP_CURRENCY_LYD,
self::TP_CURRENCY_MUR,
self::TP_CURRENCY_NGN,
self::TP_CURRENCY_NPR,
self::TP_CURRENCY_OMR,
self::TP_CURRENCY_QAR,
self::TP_CURRENCY_TJS,
);
sort($currency);
array_unshift($currency, self::TP_CURRENCY_RUB, self::TP_CURRENCY_USD, self::TP_CURRENCY_EUR);
//error_log(print_r($currency, true));
//error_log(count($currency));
return $currency;
}
public static function getDefaultCurrency(){
$currency = self::TP_CURRENCY_USD;
global $locale;
switch($locale) {
case "ru_RU":
$currency = self::TP_CURRENCY_RUB;
break;
case "en_US":
$currency = self::TP_CURRENCY_USD;
break;
default:
$currency = self::TP_CURRENCY_RUB;
break;
}
return $currency;
}
/**
* @return string
*/
public static function getCurrency(){
$currency = '';
if (!empty(TPPlugin::$options['local']['currency'])){
$currency = TPPlugin::$options['local']['currency'];
} else {
$currency = self::getDefaultCurrency();
}
return $currency;
}
public static function currencyValid(){
if ( ! TPPlugin::$options['local']['currency'] ||
! in_array( TPPlugin::$options['local']['currency'], self::getCurrencyAll() ) ) {
TPPlugin::$options['local']['currency'] = self::getDefaultCurrency();
update_option( TPOPlUGIN_OPTION_NAME, TPPlugin::$options);
}
}
public static function isCurrency($currency){
if (! $currency || ! in_array( $currency, self::getCurrencyAll() ))
return false;
return true;
}
}
|
gpl-2.0
|
lejingw/ice-java
|
python/IceStorm/clock/Publisher.py
|
2684
|
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
#
# **********************************************************************
import sys, traceback, time, Ice, IceStorm, getopt
Ice.loadSlice('Clock.ice')
import Demo
class Publisher(Ice.Application):
def usage(self):
print("Usage: " + self.appName() + " [--datagram|--twoway|--oneway] [topic]")
def run(self, args):
try:
opts, args = getopt.getopt(args[1:], '', ['datagram', 'twoway', 'oneway'])
except getopt.GetoptError:
self.usage()
return 1
datagram = False
twoway = False
optsSet = 0
topicName = "time"
for o, a in opts:
if o == "--datagram":
datagram = True
optsSet = optsSet + 1
elif o == "--twoway":
twoway = True
optsSet = optsSet + 1
elif o == "--oneway":
optsSet = optsSet + 1
if optsSet > 1:
self.usage()
return 1
if len(args) > 0:
topicName = args[0]
manager = IceStorm.TopicManagerPrx.checkedCast(self.communicator().propertyToProxy('TopicManager.Proxy'))
if not manager:
print(args[0] + ": invalid proxy")
return 1
#
# Retrieve the topic.
#
try:
topic = manager.retrieve(topicName)
except IceStorm.NoSuchTopic:
try:
topic = manager.create(topicName)
except IceStorm.TopicExists:
print(self.appName() + ": temporary error. try again")
return 1
#
# Get the topic's publisher object, and create a Clock proxy with
# the mode specified as an argument of this application.
#
publisher = topic.getPublisher();
if datagram:
publisher = publisher.ice_datagram();
elif twoway:
# Do nothing.
pass
else: # if(oneway)
publisher = publisher.ice_oneway();
clock = Demo.ClockPrx.uncheckedCast(publisher)
print("publishing tick events. Press ^C to terminate the application.")
try:
while 1:
clock.tick(time.strftime("%m/%d/%Y %H:%M:%S"))
time.sleep(1)
except IOError:
# Ignore
pass
except Ice.CommunicatorDestroyedException:
# Ignore
pass
return 0
app = Publisher()
sys.exit(app.main(sys.argv, "config.pub"))
|
gpl-2.0
|
adrianjonmiller/Anacap-Tech
|
wp-content/plugins/sticky-custom-post-types/sticky-custom-post-types.php
|
4502
|
<?php
/*
Plugin Name: Sticky Custom Post Types
Plugin URI: http://superann.com/sticky-custom-post-types/
Description: Enables support for sticky custom post types. Set options in Settings → Reading.
Version: 1.2.3
Author: Ann Oyama
Author URI: http://superann.com
License: GPL2
Copyright 2011 Ann Oyama (email : wordpress [at] superann.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
add_action( 'admin_init', 'super_sticky_add_meta_box' );
add_action( 'admin_init', 'super_sticky_admin_init', 20 );
add_action( 'pre_get_posts', 'super_sticky_posts_filter' );
function super_sticky_description() {
echo '<p>' . __( 'Enable support for sticky custom post types.' ) . '</p>';
}
function super_sticky_set_post_types() {
$post_types = get_post_types( array( '_builtin' => false, 'public' => true ), 'names' );
if ( ! empty( $post_types ) ) {
$checked_post_types = super_sticky_post_types();
foreach ( $post_types as $post_type ) { ?>
<div><input type="checkbox" id="<?php echo esc_attr( 'post_type_' . $post_type ); ?>" name="sticky_custom_post_types[]" value="<?php echo esc_attr( $post_type ); ?>" <?php checked( in_array( $post_type, $checked_post_types ) ); ?> /> <label for="<?php echo esc_attr( 'post_type_' . $post_type ); ?>"><?php echo esc_html( $post_type ); ?></label></div><?php
}
} else {
echo '<p>' . __( 'No public custom post types found.' ) . '</p>';
}
}
function super_sticky_filter( $query_type ) {
$filters = (array) get_option( 'sticky_custom_post_types_filters', array() );
return in_array( $query_type, $filters );
}
function super_sticky_set_filters() { ?>
<span><input type="checkbox" id="sticky_custom_post_types_filters_home" name="sticky_custom_post_types_filters[]" value="home" <?php checked( super_sticky_filter( 'home' ) ); ?> /> <label for="sticky_custom_post_types_filters_home">home</label></span><?php
}
function super_sticky_admin_init() {
register_setting( 'reading', 'sticky_custom_post_types' );
register_setting( 'reading', 'sticky_custom_post_types_filters' );
add_settings_section( 'super_sticky_options', __( 'Sticky Custom Post Types' ), 'super_sticky_description', 'reading' );
add_settings_field( 'sticky_custom_post_types', __( 'Show "Stick this..." checkbox on' ), 'super_sticky_set_post_types', 'reading', 'super_sticky_options' );
add_settings_field( 'sticky_custom_post_types_filters', __( 'Display selected post type(s) on' ), 'super_sticky_set_filters', 'reading', 'super_sticky_options' );
}
function super_sticky_post_types() {
return (array) get_option( 'sticky_custom_post_types', array() );
}
function super_sticky_meta() { ?>
<input id="super-sticky" name="sticky" type="checkbox" value="sticky" <?php checked( is_sticky() ); ?> /> <label for="super-sticky" class="selectit"><?php _e( 'Stick this to the front page' ) ?></label><?php
}
function super_sticky_add_meta_box() {
if( ! current_user_can( 'edit_others_posts' ) )
return;
foreach( super_sticky_post_types() as $post_type )
add_meta_box( 'super_sticky_meta', __( 'Sticky' ), 'super_sticky_meta', $post_type, 'side', 'high' );
}
function super_sticky_posts_filter( $query ) {
if ( $query->is_main_query() && $query->is_home() && ! $query->get( 'suppress_filters' ) && super_sticky_filter( 'home' ) ) {
$super_sticky_post_types = super_sticky_post_types();
if ( ! empty( $super_sticky_post_types ) ) {
$post_types = array();
$query_post_type = $query->get( 'post_type' );
if ( empty( $query_post_type ) ) {
$post_types[] = 'post';
} elseif ( is_string( $query_post_type ) ) {
$post_types[] = $query_post_type;
} elseif ( is_array( $query_post_type ) ) {
$post_types = $query_post_type;
} else {
return; // Unexpected value
}
$post_types = array_merge( $post_types, $super_sticky_post_types );
$query->set( 'post_type', $post_types );
}
}
}
?>
|
gpl-2.0
|
agustincl/scq2015m
|
forms/modules/Application/src/Application/Forms/UserForm.php
|
2533
|
<?php
return array(
'id'=>array(
'type'=>'hidden',
'filters'=> array('Stringtrim', 'StripTags', 'Escape'),
'validators' => array ('required'=>true)
),
'name'=>array(
'label'=>'Nombre',
'type'=>'text',
'filters'=> array('Stringtrim', 'StripTags', 'Escape'),
'validators' => array ('lenghtMax'=>200,
'lenghtMin'=>1,
'required'=>true
)
),
'email'=>array(
'label'=>'Email',
'type'=>'email',
'filters'=> array('Stringtrim', 'StripTags', 'Escape'),
'validators' => array ('lenghtMax'=>200,
'lenghtMin'=>1,
'required'=>true,
'email'=>true
)
),
'password'=>array(
'label'=>'Contraseña',
'type'=>'password',
'filters'=> array('Stringtrim', 'StripTags', 'Escape'),
'validators' => array ('lenghtMax'=>200,
'lenghtMin'=>8,
'required'=>true
)
),
'birthdate'=>array(
'label'=>'Fecha de nacimiento',
'type'=>'date',
'validators' => array ('date'=>true)
),
'description'=>array(
'label'=>'Descripcion',
'type'=>'textarea',
'filters'=> array('Stringtrim', 'Escape')
),
'gender'=>array(
'label'=>'Sexo',
'type'=>'radio',
'options'=>array('Mujer'=>'mujer',
'Hombre' =>'hombre',
'Otro'=>'otro'
),
'validators'=>array('inArray'=>true,
'required'=>true
)
),
'transport'=>array(
'label'=>'Tipo de transporte',
'type'=>'checkbox',
'options'=>array('Coche'=>'coche',
'Bicicleta' =>'bicycle',
'Moto'=>'motorcycle'
),
'validators'=>array('inArray'=>true)
),
'city'=>array(
'label'=>'Ciudad',
'type'=>'select',
'options'=>array('Santiago de Compostela'=>'scq',
'Vigo' =>'vigo',
'A Coruña'=>'aco'
),
'validators'=>array('inArray'=>true)
),
'code'=>array(
'label'=>'Programas en?',
'type'=>'selectmultiple',
'options'=>array('PHP'=>'php',
'Java' =>'java',
'C++'=>'c++',
'Otros'=>'otros',
),
'validators'=>array('inArray'=>true)
),
'submit'=>array(
'label'=>'Enviar',
'type'=>'submit'
),
);
|
gpl-2.0
|
deewilcox/soul-serenades
|
wp-content/plugins/woocommerce-tm-extra-product-options/include/tm-functions.php
|
2022
|
<?php
// Direct access security
if (!defined('TM_EPO_PLUGIN_SECURITY')){
die();
}
if (!function_exists('tm_woocommerce_check')){
function tm_woocommerce_check(){
$active_plugins = (array) get_option( 'active_plugins', array() );
if ( is_multisite() ){
$active_plugins = array_merge( $active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
}
return in_array( 'woocommerce/woocommerce.php', $active_plugins ) || array_key_exists( 'woocommerce/woocommerce.php', $active_plugins );
}
}
if (!function_exists('tm_woocommerce_subscriptions_check')){
function tm_woocommerce_subscriptions_check(){
$active_plugins = (array) get_option( 'active_plugins', array() );
if ( is_multisite() ){
$active_plugins = array_merge( $active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
}
return in_array( 'woocommerce-subscriptions/woocommerce-subscriptions.php', $active_plugins ) || array_key_exists( 'woocommerce-subscriptions/woocommerce-subscriptions.php', $active_plugins );
}
}
/* Check for require json function for PHP 4 & 5.1 */
if (!function_exists('json_decode')) {
include_once ('json/JSON.php');
function json_encode($data) { $json = new Services_JSON(); return( $json->encode($data) ); }
function json_decode($data) { $json = new Services_JSON(); return( $json->decode($data) ); }
}
/* Check for require json function for PHP 4 & 5.1 */
if (!function_exists('tm_get_roles')) {
function tm_get_roles(){
$result = array();
$result["@everyone"] = __('Everyone',TM_EPO_TRANSLATION);
$result["@loggedin"] = __('Logged in users',TM_EPO_TRANSLATION);
global $wp_roles;
if (empty($wp_roles)){
$all_roles = new WP_Roles();
}else{
$all_roles=$wp_roles;
}
$roles = $all_roles->roles;
if ($roles) {
foreach ($roles as $role => $details) {
$name = translate_user_role($details['name']);
$result[$role] = $name;
}
}
return $result;
}
}
?>
|
gpl-2.0
|
pierres/archlinux-mediawiki
|
extensions/TitleBlacklist/includes/api/ApiQueryTitleBlacklist.php
|
3434
|
<?php
/**
* TitleBlacklist extension API
*
* Copyright © 2011 Wikimedia Foundation and Ian Baker <ian@wikimedia.org>
* Based on code by Victor Vasiliev, Bryan Tong Minh, Roan Kattouw, and Alex Z.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
/**
* Query module check a title against the blacklist
*
* @ingroup API
* @ingroup Extensions
*/
class ApiQueryTitleBlacklist extends ApiBase {
public function __construct( $query, $moduleName ) {
parent::__construct( $query, $moduleName, 'tb' );
}
public function execute() {
$params = $this->extractRequestParams();
$action = $params['action'];
$override = !$params['nooverride'];
// createtalk and createpage are useless as they're treated exactly like create
if ( $action === 'createpage' || $action === 'createtalk' ) {
$action = 'create';
}
$title = Title::newFromText( $params['title'] );
if ( !$title ) {
$this->dieWithError(
[ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ]
);
}
$blacklisted = TitleBlacklist::singleton()->userCannot(
$title, $this->getUser(), $action, $override
);
if ( $blacklisted instanceof TitleBlacklistEntry ) {
// this title is blacklisted.
$result = [
htmlspecialchars( $blacklisted->getRaw() ),
htmlspecialchars( $params['title'] ),
];
$res = $this->getResult();
$res->addValue( 'titleblacklist', 'result', 'blacklisted' );
// there aren't any messages for create(talk|page), using edit for those instead
$message = $blacklisted->getErrorMessage( $action !== 'create' ? $action : 'edit' );
$res->addValue( 'titleblacklist', 'reason', wfMessage( $message, $result )->text() );
$res->addValue( 'titleblacklist', 'message', $message );
$res->addValue( 'titleblacklist', 'line', htmlspecialchars( $blacklisted->getRaw() ) );
} else {
// not blacklisted
$this->getResult()->addValue( 'titleblacklist', 'result', 'ok' );
}
}
public function getAllowedParams() {
return [
'title' => [
ApiBase::PARAM_REQUIRED => true,
],
'action' => [
ApiBase::PARAM_DFLT => 'edit',
ApiBase::PARAM_ISMULTI => false,
ApiBase::PARAM_TYPE => [
// createtalk and createpage are useless as they're treated exactly like create
'create', 'edit', 'upload', 'createtalk', 'createpage', 'move', 'new-account'
],
],
'nooverride' => [
ApiBase::PARAM_DFLT => false,
]
];
}
/**
* @see ApiBase::getExamplesMessages()
* @return string[]
*/
protected function getExamplesMessages() {
return [
'action=titleblacklist&tbtitle=Foo'
=> 'apihelp-titleblacklist-example-1',
'action=titleblacklist&tbtitle=Bar&tbaction=edit'
=> 'apihelp-titleblacklist-example-2',
];
}
}
|
gpl-2.0
|
ziyunhx/document-management
|
Code/Model/Model/WorkFlow.cs
|
1237
|
namespace Model
{
public class WorkFlow
{
private string _ID;
private string _Name;
private string _URL;
private string _State;
private string _Remark;
public string ID
{
get
{
return this._ID;
}
set
{
this._ID = value;
}
}
public string Name
{
get
{
return this._Name;
}
set
{
this._Name = value;
}
}
public string URL
{
get
{
return this._URL;
}
set
{
this._URL = value;
}
}
public string State
{
get
{
return this._State;
}
set
{
this._State = value;
}
}
public string Remark
{
get
{
return this._Remark;
}
set
{
this._Remark = value;
}
}
}
}
|
gpl-2.0
|
AplayER/baigoSSO
|
core/lang/zh_CN/common.php
|
7205
|
<?php
/*-----------------------------------------------------------------
!!!!警告!!!!
以下为系统文件,请勿修改
-----------------------------------------------------------------*/
//不能非法包含或直接执行
if(!defined("IN_BAIGO")) {
exit("Access Denied");
}
/*-------------------------通用-------------------------*/
return array(
/*------站点------*/
"site" => array(
"name" => "baigo SSO",
),
/*------页面标题------*/
"page" => array(
"admin" => "管理后台",
"adminLogin" => "管理后台登录",
"alert" => "提示信息",
"edit" => "编辑",
"add" => "创建",
"detail" => "详情",
"show" => "查看",
"order" => "优先级",
"profile" => "管理员个人信息",
"pass" => "修改密码",
"appBelong" => "授权用户",
"upgrade" => "baigo SSO 升级程序",
"upgradeDbtable" => "升级数据库",
"upgradeOver" => "完成升级",
"install" => "baigo SSO 安装程序",
"installExt" => "服务器环境检查",
"installDbconfig" => "数据库设置",
"installDbtable" => "创建数据表",
"installBase" => "基本设置",
"installReg" => "注册设置",
"installAdmin" => "创建管理员",
"installAuto" => "SSO 自动部署",
"installOver" => "完成安装",
),
/*------链接文字------*/
"href" => array(
"all" => "全部",
"agree" => "同意",
"logout" => "退出",
"back" => "返回",
"add" => "创建",
"edit" => "编辑",
"order" => "优先级",
"draft" => "草稿",
"recycle" => "回收站",
"help" => "帮助",
"appBelong" => "授权用户",
"passModi" => "修改密码",
"show" => "查看",
"noticeTest" => "通知接口测试",
"pageFirst" => "首页",
"pagePrevList" => "上十页",
"pagePrev" => "上一页",
"pageNext" => "下一页",
"pageNextList" => "下十页",
"pageLast" => "尾页",
),
/*------说明文字------*/
"label" => array(
"id" => "ID",
"add" => "创建",
"all" => "全部",
"seccode" => "验证码",
"key" => "关键词",
"type" => "类型",
"alert" => "返回代码",
"hits" => "点击数",
"count" => "统计",
"noname" => "未命名",
"unknown" => "未知",
"custom" => "自定义",
"modOnly" => "(需要修改时输入)", //需要修改时输入
"status" => "状态",
"box" => "保存为",
"allow" => "权限",
"note" => "备注",
"title" => "标题",
"pic" => "图片",
"content" => "内容",
"draft" => "草稿",
"recycle" => "回收站",
"check" => "选中",
"preview" => "预览",
"target" => "目标",
"result" => "结果",
"sync" => "同步通知",
"operator" => "操作者",
"on" => "开",
"off" => "关",
"apiUrl" => "API 接口 URL",
"upgrade" => "正在进行升级安装",
"to" => "至",
"complete" => "升级安装无法创建管理员,点完成完成安装",
"belongUser" => "已授权用户",
"selectUser" => "待授权用户",
"appName" => "应用名称",
"appId" => "APP ID",
"appKey" => "APP KEY",
"appKeyNote" => "如果 APP KEY 泄露,可以通过重置更换,原 APP KEY 将作废。",
"appNotice" => "通知接口 URL",
"ipAllow" => "允许通信 IP",
"ipBad" => "禁止通信 IP",
"ipNote" => "每行一个 IP,可使用通配符 <strong>*</strong> (如 192.168.1.*)",
"profileAllow" => "个人权限",
"profileInfo" => "禁止修改个人信息",
"profilePass" => "禁止修改密码",
"dbHost" => "数据库服务器",
"dbPort" => "服务器端口",
"dbName" => "数据库名称",
"dbUser" => "数据库用户名",
"dbPass" => "数据库密码",
"dbCharset" => "数据库字符编码",
"dbTable" => "数据表名前缀",
"dbDebug" => "数据库调试模式",
"user" => "用户",
"admin" => "管理员",
"username" => "用户名", //用户名
"password" => "密码", //密码
"passOld" => "旧密码", //密码
"passNew" => "新密码", //密码
"passConfirm" => "确认密码", //密码
"upgradeDbtable" => "即将升级数据库",
"upgradeOver" => "还差最后一步,完成升级",
"installOver" => "还差最后一步,完成安装",
"installDbtable" => "即将创建数据表",
"installAuto" => "即将执行自动部署第二步",
"nick" => "昵称",
"email" => "E-mail 地址",
"timeAdd" => "创建",
"timeLogin" => "最后登录",
),
/*------选择项------*/
"option" => array(
"allStatus" => "所有状态",
"allType" => "所有类型",
"allYear" => "所有年份",
"allMonth" => "所有月份",
"please" => "请选择",
"batch" => "批量操作",
"del" => "永久删除",
"normal" => "正常",
"revert" => "放回原处",
"draft" => "存为草稿",
"recycle" => "放入回收站",
),
/*------按钮------*/
"btn" => array(
"ok" => "确定",
"submit" => "提交",
"del" => "永久删除",
"complete" => "完成",
"search" => "搜索",
"filter" => "筛选",
"recycle" => "移至回收站",
"empty" => "清空回收站",
"login" => "登录",
"skip" => "跳过",
"save" => "保存",
"close" => "关闭",
"jump" => "跳转至",
"over" => "完成",
"auth" => "授权",
"deauth" => "取消授权",
"stepNext" => "下一步",
"resetKey" => "重置 APP KEY",
),
/*------确认框------*/
"confirm" => array(
"del" => "确认永久删除吗?此操作不可恢复!",
"empty" => "确认清空回收站吗?此操作不可恢复!",
"deauth" => "取消授权将使此应用失去对这些用户的编辑权限,确认取消吗?",
"resetKey" => "确认重置吗?此操作不可恢复!",
),
"text" => array(
"extErr" => "服务器环境检查未通过,请检查上述扩展库是否已经正确安装。",
"extOk" => "服务器环境检查通过,可以继续安装。",
),
/*------图片说明------*/
"alt" => array(
"seccode" => "看不清",
),
);
|
gpl-2.0
|
abhishekmurthy/Calligra
|
kexi/widget/tableview/kexidatetableedit.cpp
|
8011
|
/* This file is part of the KDE project
Copyright (C) 2002 Lucijan Busch <lucijan@gmx.at>
Copyright (C) 2003 Daniel Molkentin <molkentin@kde.org>
Copyright (C) 2003-2004,2006 Jarosław Staniek <staniek@kde.org>
This program 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 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kexidatetableedit.h"
#include <QApplication>
#include <QPainter>
#include <QVariant>
#include <QRect>
#include <QPalette>
#include <QColor>
#include <QFontMetrics>
#include <QDateTime>
#include <QCursor>
#include <QPoint>
#include <QLayout>
#include <QToolButton>
#include <QClipboard>
#include <kdebug.h>
#include <klocale.h>
#include <kglobal.h>
#include <kdatepicker.h>
#include <kdatetable.h>
#include <klineedit.h>
#include <kmenu.h>
#include <kdatewidget.h>
#include <kexiutils/utils.h>
KexiDateTableEdit::KexiDateTableEdit(KexiTableViewColumn &column, QWidget *parent)
: KexiInputTableEdit(column, parent)
{
setObjectName("KexiDateTableEdit");
//! @todo add QValidator so date like "2006-59-67" cannot be even entered
kDebug() << m_formatter.inputMask();
m_lineedit->setInputMask(m_formatter.inputMask());
}
KexiDateTableEdit::~KexiDateTableEdit()
{
}
void KexiDateTableEdit::setValueInInternalEditor(const QVariant &value)
{
if (value.isValid() && value.toDate().isValid())
m_lineedit->setText(m_formatter.toString(value.toDate()));
else
m_lineedit->setText(QString());
}
void KexiDateTableEdit::setValueInternal(const QVariant& add_, bool removeOld)
{
if (removeOld) {
//new date entering... just fill the line edit
//! @todo cut string if too long..
QString add(add_.toString());
m_lineedit->setText(add);
m_lineedit->setCursorPosition(add.length());
return;
}
setValueInInternalEditor(KexiDataItemInterface::originalValue());
m_lineedit->setCursorPosition(0); //ok?
}
void KexiDateTableEdit::setupContents(QPainter *p, bool focused, const QVariant& val,
QString &txt, int &align, int &x, int &y_offset, int &w, int &h)
{
Q_UNUSED(p);
Q_UNUSED(focused);
Q_UNUSED(x);
Q_UNUSED(w);
Q_UNUSED(h);
#ifdef Q_WS_WIN
y_offset = -1;
#else
y_offset = 0;
#endif
if (val.toDate().isValid())
txt = m_formatter.toString(val.toDate());
// txt = val.toDate().toString(Qt::LocalDate);
align |= Qt::AlignLeft;
}
bool KexiDateTableEdit::valueIsNull()
{
// if (m_lineedit->text().replace(m_formatter.separator(),"").trimmed().isEmpty())
if (m_formatter.isEmpty(m_lineedit->text())) //empty date is null
return true;
return dateValue().isNull();
}
bool KexiDateTableEdit::valueIsEmpty()
{
return valueIsNull();//js OK? TODO (nonsense?)
}
QDate KexiDateTableEdit::dateValue() const
{
return m_formatter.fromString(m_lineedit->text());
}
QVariant KexiDateTableEdit::value()
{
return m_formatter.stringToVariant(m_lineedit->text());
}
bool KexiDateTableEdit::valueIsValid()
{
if (m_formatter.isEmpty(m_lineedit->text())) //empty date is valid
return true;
return m_formatter.fromString(m_lineedit->text()).isValid();
}
bool KexiDateTableEdit::valueChanged()
{
//kDebug() << m_origValue.toString() << " ? " << m_lineedit->text();
return KexiDataItemInterface::originalValue() != m_lineedit->text();
}
void KexiDateTableEdit::handleCopyAction(const QVariant& value, const QVariant& visibleValue)
{
Q_UNUSED(visibleValue);
if (!value.isNull() && value.toDate().isValid())
qApp->clipboard()->setText(m_formatter.toString(value.toDate()));
else
qApp->clipboard()->setText(QString());
}
void KexiDateTableEdit::handleAction(const QString& actionName)
{
const bool alreadyVisible = m_lineedit->isVisible();
if (actionName == "edit_paste") {
const QVariant newValue(m_formatter.fromString(qApp->clipboard()->text()));
if (!alreadyVisible) { //paste as the entire text if the cell was not in edit mode
emit editRequested();
m_lineedit->clear();
}
setValueInInternalEditor(newValue);
} else
KexiInputTableEdit::handleAction(actionName);
}
/*
void
KexiDateTableEdit::slotDateChanged(QDate date)
{
m_edit->setDate(date);
repaint();
}
void
KexiDateTableEdit::slotShowDatePicker()
{
QDate date = m_edit->date();
m_datePicker->setDate(date);
m_datePicker->setFocus();
m_datePicker->show();
m_datePicker->setFocus();
}
//! @internal helper
void KexiDateTableEdit::moveToFirstSection()
{
if (!m_dte_date_obj)
return;
#ifdef QDateTimeEditor_HACK
if (m_dte_date)
m_dte_date->setFocusSection(0);
#else
#ifdef Q_WS_WIN //tmp
QKeyEvent ke_left(QEvent::KeyPress, Qt::Key_Left, 0, 0);
for (int i=0; i<8; i++)
QApplication::sendEvent( m_dte_date_obj, &ke_left );
#endif
#endif
}
bool KexiDateTableEdit::eventFilter( QObject *o, QEvent *e )
{
if (o==m_datePicker) {
kDebug() << e->type();
switch (e->type()) {
case QEvent::Hide:
m_datePickerPopupMenu->hide();
break;
case QEvent::KeyPress:
case QEvent::KeyRelease: {
kDebug() << "ok!";
QKeyEvent *ke = (QKeyEvent *)e;
if (ke->key()==Qt::Key_Enter || ke->key()==Qt::Key_Return) {
//accepting picker
acceptDate();
return true;
}
else if (ke->key()==Qt::Key_Escape) {
//canceling picker
m_datePickerPopupMenu->hide();
kDebug() << "reject";
return true;
}
else m_datePickerPopupMenu->setFocus();
break;
}
default:
break;
}
}
#ifdef Q_WS_WIN //tmp
else if (e->type()==QEvent::FocusIn && o->parent() && o->parent()->parent()==m_edit
&& m_setNumberOnFocus >= 0 && m_dte_date_obj)
{
// there was a number character passed as 'add' parameter in init():
moveToFirstSection();
QKeyEvent ke(QEvent::KeyPress, int(Qt::Key_0)+m_setNumberOnFocus,
'0'+m_setNumberOnFocus, 0, QString::number(m_setNumberOnFocus));
QApplication::sendEvent( m_dte_date_obj, &ke );
m_setNumberOnFocus = -1;
}
#endif
#ifdef QDateTimeEditor_HACK
else if (e->type()==QEvent::KeyPress && m_dte_date) {
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
if ((ke->key()==Qt::Key_Right && !m_sentEvent && cursorAtEnd())
|| (ke->key()==Qt::Key_Left && !m_sentEvent && cursorAtStart()))
{
//the editor should send this key event:
m_sentEvent = true; //avoid recursion
QApplication::sendEvent( this, ke );
m_sentEvent = false;
ke->ignore();
return true;
}
}
#endif
return false;
}
void KexiDateTableEdit::acceptDate()
{
m_edit->setDate(m_datePicker->date());
m_datePickerPopupMenu->hide();
kDebug() << "accept";
}
bool KexiDateTableEdit::cursorAtStart()
{
#ifdef QDateTimeEditor_HACK
return m_dte_date && m_edit->hasFocus() && m_dte_date->focusSection()==0;
#else
return false;
#endif
}
bool KexiDateTableEdit::cursorAtEnd()
{
#ifdef QDateTimeEditor_HACK
return m_dte_date && m_edit->hasFocus()
&& m_dte_date->focusSection()==int(m_dte_date->sectionCount()-1);
#else
return false;
#endif
}
void KexiDateTableEdit::clear()
{
m_edit->setDate(QDate());
}*/
KEXI_CELLEDITOR_FACTORY_ITEM_IMPL(KexiDateEditorFactoryItem, KexiDateTableEdit)
#include "kexidatetableedit.moc"
|
gpl-2.0
|
szb231053450/tourism
|
src/main/webapp/resources/base/js/handsontable-pro-1.7.0/src/plugins/ganttChart/ganttChartDataFeed.js
|
9610
|
import {objectEach, deepClone} from 'handsontable/helpers/object';
import {arrayEach} from 'handsontable/helpers/array';
import {DateCalculator} from './dateCalculator';
/**
* This class handles the data-related calculations for the GanttChart plugin.
*
* @plugin GanttChart
*/
class GanttChartDataFeed {
constructor(chartInstance, data, startDateColumn, endDateColumn, additionalData, asyncUpdates) {
this.data = data;
this.chartInstance = chartInstance;
this.chartPlugin = this.chartInstance.getPlugin('ganttChart');
this.hotSource = null;
this.sourceHooks = {};
this.ongoingAsync = false;
this.applyData(data, startDateColumn, endDateColumn, additionalData, asyncUpdates || false);
}
/**
* Parse data accordingly to it's type (HOT instance / data object).
*
* @param {Object} data The source Handsontable instance or a data object.
* @param {Number} startDateColumn Index of the column containing the start dates.
* @param {Number} endDateColumn Index of the column containing the end dates.
* @param {Object} additionalData Object containing column and label information about additional data passed to the Gantt Plugin.
* @param {Boolean} asyncUpdates If set to true, the source instance updates will be applied asynchronously.
*/
applyData(data, startDateColumn, endDateColumn, additionalData, asyncUpdates) {
if (Object.prototype.toString.call(data) === '[object Array]') {
this.loadData(data);
// if data is a Handsontable instance (probably not the best way to recognize it)
} else if (data.guid) {
this.bindWithHotInstance(data, startDateColumn, endDateColumn, additionalData, asyncUpdates);
}
}
/**
* Make another Handsontable instance be a live feed for the gantt chart.
*
* @param {Object} instance The source Handsontable instance.
* @param {Number} startDateColumn Index of the column containing the start dates.
* @param {Number} endDateColumn Index of the column containing the end dates.
* @param {Object} additionalData Object containing column and label information about additional data passed to the
* Gantt Plugin. See the example for more details.
* @param {Boolean} asyncUpdates If set to true, the source instance updates will be applied asynchronously.
*
* @example
* ```js
* hot.getPlugin('ganttChart').bindWithHotInstance(sourceInstance, 4, 5, {
* vendor: 0, // data labeled 'vendor' is stored in the first sourceInstance column.
* format: 1, // data labeled 'format' is stored in the second sourceInstance column.
* market: 2 // data labeled 'market' is stored in the third sourceInstance column.
* });
* ```
*/
bindWithHotInstance(instance, startDateColumn, endDateColumn, additionalData, asyncUpdates) {
this.hotSource = {
instance: instance,
startColumn: startDateColumn,
endColumn: endDateColumn,
additionalData: additionalData,
asyncUpdates: asyncUpdates
};
this.addSourceHotHooks();
this.asyncCall(this.updateFromSource);
}
/**
* Run the provided function asynchronously.
*
* @param {Function} func
*/
asyncCall(func) {
if (!this.hotSource.asyncUpdates) {
func.call(this);
return;
}
this.asyncStart();
setTimeout(() => {
func.call(this);
this.asyncEnd();
}, 0);
}
asyncStart() {
this.ongoingAsync = true;
}
asyncEnd() {
this.ongoingAsync = false;
}
/**
* Add hooks to the source Handsontable instance.
*
* @private
*/
addSourceHotHooks() {
this.sourceHooks = {
afterLoadData: (firstRun) => this.onAfterSourceLoadData(firstRun),
afterChange: (changes, source) => this.onAfterSourceChange(changes, source),
afterColumnSort: (column, order) => this.onAfterColumnSort(column, order)
};
this.hotSource.instance.addHook('afterLoadData', this.sourceHooks.afterLoadData);
this.hotSource.instance.addHook('afterChange', this.sourceHooks.afterChange);
this.hotSource.instance.addHook('afterColumnSort', this.sourceHooks.afterColumnSort);
}
/**
* Remove hooks from the source Handsontable instance.
*
* @private
* @param {Object} hotSource The source Handsontable instance object.
*/
removeSourceHotHooks(hotSource) {
if (this.sourceHooks.afterLoadData) {
hotSource.instance.removeHook('afterLoadData', this.sourceHooks.afterLoadData);
}
if (this.sourceHooks.afterChange) {
hotSource.instance.removeHook('afterChange', this.sourceHooks.afterChange);
}
if (this.sourceHooks.afterColumnSort) {
hotSource.instance.removeHook('afterColumnSort', this.sourceHooks.afterColumnSort);
}
}
/**
* Get data from the source Handsontable instance.
*
* @param {Number} [row] Source Handsontable instance row.
* @returns {Array}
*/
getDataFromSource(row) {
let additionalObjectData = {};
let hotSource = this.hotSource;
let sourceHotRows;
let rangeBarData = [];
if (row === void 0) {
sourceHotRows = hotSource.instance.getData(0, 0, hotSource.instance.countRows() - 1, hotSource.instance.countCols() - 1);
} else {
sourceHotRows = [];
sourceHotRows[row] = hotSource.instance.getDataAtRow(row);
}
for (let i = row || 0, dataLength = sourceHotRows.length; i < (row ? row + 1 : dataLength); i++) {
additionalObjectData = {};
let currentRow = sourceHotRows[i];
if (currentRow[hotSource.startColumn] === null || currentRow[hotSource.startColumn] === '') {
continue;
}
objectEach(hotSource.additionalData, (prop, j) => {
additionalObjectData[j] = currentRow[prop];
});
rangeBarData.push([
i, currentRow[hotSource.startColumn],
currentRow[hotSource.endColumn], additionalObjectData, i]);
}
return rangeBarData;
}
/**
* Update the Gantt Chart-enabled Handsontable instance with the data from the source Handsontable instance.
*
* @param {Number} [row] Index of the row which needs updating.
*/
updateFromSource(row) {
let dataFromSource = this.getDataFromSource(row);
if (!row && isNaN(row)) {
this.chartPlugin.clearRangeBars();
this.chartPlugin.clearRangeList();
}
arrayEach(dataFromSource, (bar) => {
bar = this.trimRangeIfNeeded(bar);
this.chartPlugin.addRangeBar.apply(this.chartPlugin, bar);
});
}
/**
* Load chart data to the Handsontable instance.
*
* @param {Array} data Array of objects containing the range data.
*
* @example
* ```js
* [
* {
* additionalData: {vendor: 'Vendor One', format: 'Posters', market: 'New York, NY'},
* startDate: '1/5/2015',
* endDate: '1/20/2015'
* },
* {
* additionalData: {vendor: 'Vendor Two', format: 'Malls', market: 'Los Angeles, CA'},
* startDate: '1/11/2015',
* endDate: '1/29/2015'
* }
* ]
* ```
*/
loadData(data) {
arrayEach(data, (bar, i) => {
bar = this.trimRangeIfNeeded(bar);
this.chartPlugin.addRangeBar(i, bar.startDate, bar.endDate, bar.additionalData);
});
}
/**
* Trim the dates in the provided range bar, if they exceed the currently processed year.
*
* @param {Array} bar Range bar data.
* @returns {Array}
*/
trimRangeIfNeeded(bar) {
let startDate = new Date(bar[1]);
let endDate = new Date(bar[2]);
if (typeof startDate === 'string' || typeof endDate === 'string') {
return false;
}
let startYear = startDate.getFullYear();
let endYear = endDate.getFullYear();
if (startYear < this.chartPlugin.currentYear && endYear >= this.chartPlugin.currentYear) {
bar[1] = '01/01/' + this.chartPlugin.currentYear;
}
if (endYear > this.chartPlugin.currentYear && startYear <= this.chartPlugin.currentYear) {
bar[2] = '12/31/' + this.chartPlugin.currentYear;
}
return bar;
}
/**
* afterChange hook callback for the source Handsontable instance.
*
* @private
* @param {Array} changes List of changes.
* @param {String} source Change source.
*/
onAfterSourceChange(changes, source) {
this.asyncCall(() => {
if (!changes) {
return;
}
let changesByRows = {};
for (let i = 0, changesLength = changes.length; i < changesLength; i++) {
let currentChange = changes[i];
let row = parseInt(currentChange[0], 10);
let col = parseInt(currentChange[1], 10);
if (!changesByRows[row]) {
changesByRows[row] = {};
}
changesByRows[row][col] = [currentChange[2], currentChange[3]];
}
objectEach(changesByRows, (prop, i) => {
i = parseInt(i, 10);
if (this.chartPlugin.getRangeBarCoordinates(i)) {
this.chartPlugin.removeRangeBarByColumn(i, this.chartPlugin.rangeList[i][1]);
}
this.updateFromSource(i);
});
});
}
/**
* afterLoadData hook callback for the source Handsontable instance.
*
* @private
* @param firstRun
*/
onAfterSourceLoadData(firstRun) {
this.asyncCall((firstRun) => {
this.chartPlugin.removeAllRangeBars();
this.updateFromSource();
});
}
/**
* afterColumnSort hook callback for the source Handsontable instance.
*
* @private
* @param {Number} column Sorted column.
* @param order
*/
onAfterColumnSort(column, order) {
this.asyncCall(() => {
this.chartPlugin.removeAllRangeBars();
this.updateFromSource();
});
}
}
export {GanttChartDataFeed};
|
gpl-2.0
|
dangdinhtu2014/nukeviet_slider
|
modules/slider/admin/alias.php
|
1039
|
<?php
/**
* @Project NUKEVIET 4.x
* @Author DANGDINHTU (dlinhvan@gmail.com)
* @Copyright (C) 2013 Webdep24.com - dangdinhtu.com. All rights reserved
* @License GNU/GPL version 2 or any later version
* @Createdate Wed, 21 Jan 2015 14:00:59 GMT
*/
if( ! defined( 'NV_IS_FILE_ADMIN' ) ) die( 'Stop!!!' );
$name = $nv_Request->get_title( 'name', 'post', '' );
$alias = change_alias( $name );
$id = $nv_Request->get_int( 'id', 'post', 0 );
$mod = $nv_Request->get_string( 'mod', 'post', '' );
if( $mod == 'photo' )
{
$tab = TABLE_SLIDER_NAME . '_photo';
$stmt = $db->prepare( 'SELECT COUNT(*) FROM ' . $tab . ' WHERE photo_id !=' . $id . ' AND alias= :alias' );
$stmt->bindParam( ':alias', $alias, PDO::PARAM_STR );
$stmt->execute();
$nb = $stmt->fetchColumn();
if( ! empty( $nb ) )
{
$nb = $db->query( 'SELECT MAX(album_id) FROM ' . $tab )->fetchColumn();
$alias .= '-' . ( intval( $nb ) + 1 );
}
}
include NV_ROOTDIR . '/includes/header.php';
echo strtolower( $alias );
include NV_ROOTDIR . '/includes/footer.php';
|
gpl-2.0
|
mecirt/7k2
|
src/olightn.cpp
|
9174
|
/*
* Seven Kingdoms 2: The Fryhtan War
*
* Copyright 1999 Enlight Software Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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, see <http://www.gnu.org/licenses/>.
*
*/
// Filename : OLIGHTN.CPP
// Description : Lightning class
// Ownership : Gilbert
#include <math.h>
#include <ovgabuf.h>
#include <omisc.h>
#include <olightn.h>
#include <oworldmt.h>
#include <color.h>
#include <omagic.h>
#include <ovga.h>
//------------ Define constant ----------//
#define PI 3.141592654
#define CORELIGHTNCOLOR (VGA_GRAY+15)
#define INLIGHTNCOLOR (VGA_GRAY+13)
#define OUTLIGHTNCOLOR (VGA_GRAY+10)
//--------- Define static class vars --------//
int Lightning::bound_x1; // = ZOOM_X1+4;
int Lightning::bound_y1; // = ZOOM_Y1-4;
int Lightning::bound_x2; // = ZOOM_X2-4;
int Lightning::bound_y2; // = ZOOM_Y2-4;
//---------- Declare static functions ----------//
static double sqr(double x);
//-------- Begin of static function Lightning::dist ----------//
double Lightning::dist(double dx, double dy)
{
return sqrt( dx*dx + dy*dy);
}
//-------- End of static function Lightning::dist ----------//
//-------- Begin of static function Lightning::set_clip ----------//
void Lightning::set_clip(int x1, int y1, int x2, int y2)
{
bound_x1 = x1;
bound_x2 = x2;
bound_y1 = y1;
bound_y2 = y2;
}
//-------- End of static function Lightning::set_clip ----------//
//-------- Begin of function Lightning::~Lightning ----------//
Lightning::~Lightning()
{
}
//-------- End of function Lightning::~Lightning ----------//
//-------- Begin of function Lightning::rand_seed ----------//
unsigned Lightning::rand_seed()
{
#define MULTIPLIER 0x015a4e35L
#define INCREMENT 1
seed = MULTIPLIER * seed + INCREMENT;
return seed;
}
//-------- End of function Lightning::rand_seed ----------//
//-------- Begin of function Lightning::init ----------//
void Lightning::init(double fromX, double fromY, double toX, double toY,
char energy)
{
x = fromX;
y = fromY;
destx = toX;
desty = toY;
energy_level = energy;
v = 16.0;
expect_steps = (int)( dist(desty-y, destx-x) / v * 1.2);
if( expect_steps < 2 )
expect_steps = 2;
steps = 0;
a0 = a = 8.0;
r0 = r = 8.0 * a;
wide = PI / 4;
seed = (unsigned)(fromX + fromY + toX + toY) | 1;
(void) rand_seed();
}
//-------- End of function Lightning::init ----------//
//-------- Begin of function Lightning::goal ----------//
// return TRUE if the point is very near destination
int Lightning::goal()
{
return( dist(destx-x, desty-y) < v );
}
//-------- End of function Lightning::goal ----------//
//-------- Begin of function Lightning::update_parameter ----------//
void Lightning::update_parameter()
{
double progress = (double) steps / expect_steps;
if( progress > 1)
progress = 1;
// a = a0; // constant
r = r0 * (1-progress);
wide = 0.25 * ( 1 + progress ) * PI;
}
//-------- End of function Lightning::update_parameter ----------//
//-------- Begin of function Lightning::move_particle ----------//
void Lightning::move_particle()
{
// determine attraction
double attractionDist = dist(destx-x, desty-y);
if( attractionDist < v)
return;
double aX = a * (destx-x) / attractionDist;
double aY = a * (desty-y) / attractionDist;
// determine random component
double attractionAngle = atan2( desty-y, destx-x);
double randomAngle = ((rand_seed() & 255)/128.0-1.0)*wide+ attractionAngle;
double rX = r * cos(randomAngle);
double rY = r * sin(randomAngle);
// total
double tX = aX + rX;
double tY = aY + rY;
double distt = dist(tX, tY);
// move x and y, along tX, tY but the magnitude is v
if( distt > 0)
{
x += v * tX / distt;
y += v * tY / distt;
}
steps ++;
update_parameter();
}
//-------- End of function Lightning::move_particle ----------//
//-------- Begin of function Lightning::draw_step ----------//
void Lightning::draw_step(VgaBuf *vgabuf)
{
int prex, prey;
if(!goal() )
{
prex = (int) x;
prey = (int) y;
move_particle();
// BUGHERE: ignore if clipped, currently
if( energy_level > 4)
{
if( prex >= bound_x1+2 && (int)x >= bound_x1+2 &&
prex <= bound_x2-2 && (int)x <= bound_x2-2 &&
prey >= bound_y1+2 && (int)y >= bound_y1+2 &&
prey <= bound_y2-2 && (int)y <= bound_y2-2 )
{
/* vgabuf->line(prex+2, prey, (int) x+2, (int) y, OUTLIGHTNCOLOR);
vgabuf->line(prex, prey+2, (int) x, (int) y+2, OUTLIGHTNCOLOR);
vgabuf->line(prex-2, prey, (int) x-2, (int) y, OUTLIGHTNCOLOR);
vgabuf->line(prex, prey-2, (int) x, (int) y-2, OUTLIGHTNCOLOR);
vgabuf->line(prex+1, prey, (int) x+1, (int) y, INLIGHTNCOLOR);
vgabuf->line(prex, prey+1, (int) x, (int) y+1, INLIGHTNCOLOR);
vgabuf->line(prex-1, prey, (int) x-1, (int) y, INLIGHTNCOLOR);
vgabuf->line(prex, prey-1, (int) x, (int) y-1, INLIGHTNCOLOR);
vgabuf->line(prex, prey, (int) x, (int) y, CORELIGHTNCOLOR);*/
magic.draw_light_beam(&vga_back, prex, prey, x, y, 10, 4,
0, 80, 255, 255, 255, 255, 0);
magic.draw_circle2(&vga_back, x, y, 25, 0, 0, 0, 80, 255, 0);
magic.draw_circle2(&vga_back, x, y, 8, 0, 0, 255, 255, 255, 0);
}
}
else if( energy_level > 2)
{
if( prex >= bound_x1+1 && (int)x >= bound_x1+1 &&
prex <= bound_x2-1 && (int)x <= bound_x2-1 &&
prey >= bound_y1+1 && (int)y >= bound_y1+1 &&
prey <= bound_y2-1 && (int)y <= bound_y2-1 )
{
/* vgabuf->line(prex+1, prey, (int) x+1, (int) y, OUTLIGHTNCOLOR);
vgabuf->line(prex, prey+1, (int) x, (int) y+1, OUTLIGHTNCOLOR);
vgabuf->line(prex, prey, (int) x, (int) y, INLIGHTNCOLOR);*/
magic.draw_light_beam(&vga_back, prex, prey, x, y, 8, 2,
0, 80, 255, 255, 255, 255, 0);
}
}
else
{
if( prex >= bound_x1 && (int)x >= bound_x1 &&
prex <= bound_x2 && (int)x <= bound_x2 &&
prey >= bound_y1 && (int)y >= bound_y1 &&
prey <= bound_y2 && (int)y <= bound_y2 )
{
// vgabuf->line(prex, prey, (int) x, (int) y, OUTLIGHTNCOLOR);
magic.draw_light_beam(&vga_back, prex, prey, x, y, 3, 1,
0, 80, 255, 255, 255, 255, 0);
}
}
}
}
//-------- End of function Lightning::draw_step ----------//
//-------- Begin of function Lightning::draw_whole ----------//
void Lightning::draw_whole(VgaBuf *vgabuf)
{
int prex, prey;
while(!goal() )
{
prex = (int) x;
prey = (int) y;
move_particle();
// ignore clipping, currently
if( energy_level > 4)
{
if( prex >= bound_x1+2 && (int)x >= bound_x1+2 &&
prex <= bound_x2-2 && (int)x <= bound_x2-2 &&
prey >= bound_y1+2 && (int)y >= bound_y1+2 &&
prey <= bound_y2-2 && (int)y <= bound_y2-2 )
{
vgabuf->line(prex+2, prey, (int) x+2, (int) y, OUTLIGHTNCOLOR);
vgabuf->line(prex, prey+2, (int) x, (int) y+2, OUTLIGHTNCOLOR);
vgabuf->line(prex-2, prey, (int) x-2, (int) y, OUTLIGHTNCOLOR);
vgabuf->line(prex, prey-2, (int) x, (int) y-2, OUTLIGHTNCOLOR);
vgabuf->line(prex+1, prey, (int) x+1, (int) y, INLIGHTNCOLOR);
vgabuf->line(prex, prey+1, (int) x, (int) y+1, INLIGHTNCOLOR);
vgabuf->line(prex-1, prey, (int) x-1, (int) y, INLIGHTNCOLOR);
vgabuf->line(prex, prey-1, (int) x, (int) y-1, INLIGHTNCOLOR);
vgabuf->line(prex, prey, (int) x, (int) y, CORELIGHTNCOLOR);
}
}
else if( energy_level > 2)
{
if( prex >= bound_x1+1 && (int)x >= bound_x1+1 &&
prex <= bound_x2-1 && (int)x <= bound_x2-1 &&
prey >= bound_y1+1 && (int)y >= bound_y1+1 &&
prey <= bound_y2-1 && (int)y <= bound_y2-1 )
{
vgabuf->line(prex+1, prey, (int) x+1, (int) y, OUTLIGHTNCOLOR);
vgabuf->line(prex, prey+1, (int) x, (int) y+1, OUTLIGHTNCOLOR);
vgabuf->line(prex, prey, (int) x, (int) y, INLIGHTNCOLOR);
}
}
else
{
if( prex >= bound_x1 && (int)x >= bound_x1 &&
prex <= bound_x2 && (int)x <= bound_x2 &&
prey >= bound_y1 && (int)y >= bound_y1 &&
prey <= bound_y2 && (int)y <= bound_y2 )
{
vgabuf->line(prex, prey, (int) x, (int) y, OUTLIGHTNCOLOR);
}
}
}
}
//-------- End of function Lightning::draw_whole ----------//
//-------- Begin of function Lightning::progress ----------//
double Lightning::progress()
{
if(goal())
return 1;
else
return (double) steps / expect_steps;
}
//-------- End of function Lightning::progress ----------//
//-------- Begin of function Lightning::draw_section ----------//
void Lightning::draw_section(VgaBuf *vgabuf, double portion)
{
while( progress() < ( portion< 1.0 ? portion : 1.0 ) )
draw_step(vgabuf);
}
//-------- End of function Lightning::draw_section ----------//
//-------- Begin of static function sqr ----------//
static double sqr(double x)
{
return x*x;
}
//-------- End of static function sqr ----------//
|
gpl-2.0
|
tommythorn/yari
|
shared/cacao-related/phoneme_feature/cldc/src/javaapi/share/com/sun/cldc/io/ResourceInputStream.java
|
7651
|
/*
*
*
* Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program 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.
*
* 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 version 2 for more details (a copy is
* included at /legal/license.txt).
*
* 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 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.cldc.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
/**
* Input stream class for accessing resource files in classpath.
*/
public class ResourceInputStream extends InputStream {
private Object fileDecoder;
private Object savedDecoder; // used for mark/reset functionality
/**
* Fixes the resource name to be conformant with the CLDC 1.0
* specification. We are not allowed to use "../" to get outside
* of the .jar file.
*
* @param name the name of the resource in classpath to access.
* @return the fixed string.
* @exception IOException if the resource name points to a
* classfile, as determined by the resource name's
* extension.
*/
private static String fixResourceName(String name) throws IOException {
Vector dirVector = new Vector();
int startIdx = 0;
int endIdx = 0;
String curDir;
while ((endIdx = name.indexOf('/', startIdx)) != -1) {
if (endIdx == startIdx) {
// We have a leading '/' or two consecutive '/'s
startIdx++;
continue;
}
curDir = name.substring(startIdx, endIdx);
startIdx = endIdx + 1;
if (curDir.equals(".")) {
// Ignore a single '.' directory
continue;
}
if (curDir.equals("..")) {
// Go up a level
try {
dirVector.removeElementAt(dirVector.size()-1);
} catch (ArrayIndexOutOfBoundsException aioobe) {
// "/../resource" Not allowed!
throw new IOException();
}
continue;
}
dirVector.addElement(curDir);
}
// save directory structure
StringBuffer dirName = new StringBuffer();
int nelements = dirVector.size();
for (int i = 0; i < nelements; ++i) {
dirName.append((String)dirVector.elementAt(i));
dirName.append("/");
}
// save filename
if (startIdx < name.length()) {
String filename = name.substring(startIdx);
// Throw IOE if the resource ends with ".class", but, not
// if the entire name is ".class"
if ((filename.endsWith(".class")) &&
(! ".class".equals(filename))) {
throw new IOException();
}
dirName.append(name.substring(startIdx));
}
return dirName.toString();
}
/**
* Construct a resource input stream for accessing objects in the jar file.
*
* @param name the name of the resource in classpath to access. The
* name must not have a leading '/'.
* @exception IOException if an I/O error occurs.
*/
public ResourceInputStream(String name) throws IOException {
String fixedName = fixResourceName(name);
fileDecoder = open(fixedName);
if (fileDecoder == null) {
throw new IOException();
}
}
/**
* Reads the next byte of data from the input stream.
*
* @return the next byte of data, or <code>-1</code> if the end
* of the stream is reached.
* @exception IOException if an I/O error occurs.
*/
public int read() throws IOException {
// Fix for CR 6303054
if (fileDecoder == null) {
throw new IOException();
}
return readByte(fileDecoder);
}
/**
* Gets the number of bytes remaining to be read.
*
* @return the number of bytes remaining in the resource.
* @exception IOException if an I/O error occurs.
*/
public int available() throws IOException {
if (fileDecoder == null) {
throw new IOException();
}
return bytesRemain(fileDecoder);
}
/**
* Reads bytes into a byte array.
*
* @param b the buffer to read into.
* @param off offset to start at in the buffer.
* @param len number of bytes to read.
* @return the number of bytes read, or <code>-1</code> if the end
* of the stream is reached.
* @exception IOException if an I/O error occurs.
*/
public int read(byte b[], int off, int len) throws IOException {
// Fix for CR 6303054
if (fileDecoder == null) {
throw new IOException();
}
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
return readBytes(fileDecoder, b, off, len);
}
public void close() throws IOException {
fileDecoder = null;
}
/**
* Remembers current position in ResourceInputStream so that
* subsequent call to <code>reset</code> will rewind the stream
* to the saved position.
*
* @param readlimit affects nothing
* @see java.io.InputStream#reset()
*/
public void mark(int readlimit) {
if (fileDecoder != null) {
savedDecoder = clone(fileDecoder);
}
}
/**
* Repositions this stream to the position at the time the
* <code>mark</code> method was last called on this input stream.
*
* @exception IOException if this stream has not been marked
* @see java.io.InputStream#mark(int)
*/
public void reset() throws IOException {
if (fileDecoder == null || savedDecoder == null) {
throw new IOException();
}
fileDecoder = clone(savedDecoder);
}
/**
* Indicates that this ResourceInputStream supports mark/reset
* functionality
*
* @return true
*/
public boolean markSupported() {
return true;
}
// OS-specific interface to underlying file system.
private static native Object open(String name);
private static native int bytesRemain(Object fileDecoder);
private static native int readByte(Object fileDecoder);
private static native int readBytes(Object fileDecoder,
byte b[], int off, int len);
/*
* Copies all fields from one FileDecoder object to another -
* used remember or restore current ResourceInputStream state.
*/
private static native Object clone(Object source);
}
|
gpl-2.0
|
Droces/casabio
|
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/ASF/FileLength.php
|
694
|
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\ASF;
use PHPExiftool\Driver\AbstractTag;
class FileLength extends AbstractTag
{
protected $Id = 16;
protected $Name = 'FileLength';
protected $FullName = 'ASF::FileProperties';
protected $GroupName = 'ASF';
protected $g0 = 'ASF';
protected $g1 = 'ASF';
protected $g2 = 'Video';
protected $Type = 'int64u';
protected $Writable = false;
protected $Description = 'File Length';
}
|
gpl-2.0
|
darkloveir/Skyfire-6.1.2-version
|
src/server/game/Quests/QuestDef.cpp
|
10621
|
/*
* Copyright (C) 2011-2014 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "QuestDef.h"
#include "Player.h"
#include "World.h"
#include "ObjectMgr.h"
Quest::Quest(Field* questRecord)
{
Id = questRecord[0].GetUInt32();
Method = questRecord[1].GetUInt8();
Level = questRecord[2].GetInt16();
MinLevel = uint32(questRecord[3].GetInt16());
MaxLevel = uint32(questRecord[4].GetInt16());
ZoneOrSort = questRecord[5].GetInt16();
Type = questRecord[6].GetUInt16();
SuggestedPlayers = questRecord[7].GetUInt8();
LimitTime = questRecord[8].GetUInt32();
RequiredClasses = questRecord[9].GetUInt16();
RequiredRaces = questRecord[10].GetUInt32();
RequiredSkillId = questRecord[11].GetUInt16();
RequiredSkillPoints = questRecord[12].GetUInt16();
RequiredMinRepFaction = questRecord[13].GetUInt16();
RequiredMaxRepFaction = questRecord[14].GetUInt16();
RequiredMinRepValue = questRecord[15].GetInt32();
RequiredMaxRepValue = questRecord[16].GetInt32();
PrevQuestId = questRecord[17].GetInt32();
NextQuestId = questRecord[18].GetInt32();
ExclusiveGroup = questRecord[19].GetInt32();
NextQuestIdChain = questRecord[20].GetUInt32();
RewardXPId = questRecord[21].GetUInt8();
RewardMoney = questRecord[22].GetInt32();
RewardMoneyMaxLevel = questRecord[23].GetUInt32();
RewardSpell = questRecord[24].GetUInt32();
RewardSpellCast = questRecord[25].GetInt32();
RewardHonor = questRecord[26].GetUInt32();
RewardHonorMultiplier = questRecord[27].GetFloat();
RewardMailTemplateId = questRecord[28].GetUInt32();
RewardMailDelay = questRecord[29].GetUInt32();
SourceItemId = questRecord[30].GetUInt32();
SourceSpellid = questRecord[31].GetUInt32();
Flags = questRecord[32].GetUInt32();
Flags2 = questRecord[33].GetUInt32();
SpecialFlags = questRecord[34].GetUInt8();
MinimapTargetMark = questRecord[35].GetUInt8();
RewardTitleId = questRecord[36].GetUInt8();
RewardTalents = questRecord[37].GetUInt8();
RewardArenaPoints = questRecord[38].GetUInt16();
RewardSkillId = questRecord[39].GetUInt16();
RewardSkillPoints = questRecord[40].GetUInt8();
RewardReputationMask = questRecord[41].GetUInt8();
QuestGiverPortrait = questRecord[42].GetUInt32();
QuestTurnInPortrait = questRecord[43].GetUInt32();
RewardPackageItemId = questRecord[44].GetUInt32();
for (int i = 0; i < QUEST_REWARDS_COUNT; ++i)
RewardItemId[i] = questRecord[45 + i].GetUInt32();
for (int i = 0; i < QUEST_REWARDS_COUNT; ++i)
RewardItemIdCount[i] = questRecord[49 + i].GetUInt16();
for (int i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
RewardChoiceItemId[i] = questRecord[53 + i].GetUInt32();
for (int i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
RewardChoiceItemCount[i] = questRecord[59 + i].GetUInt16();
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
RewardFactionId[i] = questRecord[65 + i].GetUInt16();
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
RewardFactionValueId[i] = questRecord[70 + i].GetInt32();
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
RewardFactionValueIdOverride[i] = questRecord[75 + i].GetInt32();
PointMapId = questRecord[80].GetUInt16();
PointX = questRecord[81].GetFloat();
PointY = questRecord[82].GetFloat();
PointOption = questRecord[83].GetUInt32();
Title = questRecord[84].GetString();
Objectives = questRecord[85].GetString();
Details = questRecord[86].GetString();
EndText = questRecord[87].GetString();
CompletedText = questRecord[88].GetString();
OfferRewardText = questRecord[89].GetString();
RequestItemsText = questRecord[90].GetString();
for (int i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
RequiredSourceItemId[i] = questRecord[91 + i].GetUInt32();
for (int i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
RequiredSourceItemCount[i] = questRecord[95 + i].GetUInt16();
for (int i = 0; i < QUEST_REWARD_CURRENCY_COUNT; ++i)
RewardCurrencyId[i] = questRecord[99 + i].GetUInt16();
for (int i = 0; i < QUEST_REWARD_CURRENCY_COUNT; ++i)
RewardCurrencyCount[i] = questRecord[103 + i].GetUInt8();
QuestGiverTextWindow = questRecord[107].GetString();
QuestGiverTargetName = questRecord[108].GetString();
QuestTurnTextWindow = questRecord[109].GetString();
QuestTurnTargetName = questRecord[110].GetString();
SoundAccept = questRecord[111].GetUInt16();
SoundTurnIn = questRecord[112].GetUInt16();
for (int i = 0; i < QUEST_EMOTE_COUNT; ++i)
DetailsEmote[i] = questRecord[113 + i].GetUInt16();
for (int i = 0; i < QUEST_EMOTE_COUNT; ++i)
DetailsEmoteDelay[i] = questRecord[117 + i].GetUInt32();
EmoteOnIncomplete = questRecord[121].GetUInt16();
EmoteOnComplete = questRecord[122].GetUInt16();
for (int i = 0; i < QUEST_EMOTE_COUNT; ++i)
OfferRewardEmote[i] = questRecord[123 + i].GetInt16();
for (int i = 0; i < QUEST_EMOTE_COUNT; ++i)
OfferRewardEmoteDelay[i] = questRecord[127 + i].GetInt32();
// int32 WDBVerified = questRecord[131].GetInt32();
if (SpecialFlags & QUEST_SPECIAL_FLAGS_AUTO_ACCEPT)
Flags |= QUEST_FLAGS_AUTO_ACCEPT;
_rewItemsCount = 0;
_rewChoiceItemsCount = 0;
_rewCurrencyCount = 0;
for (int i = 0; i < QUEST_REWARDS_COUNT; ++i)
if (RewardItemId[i])
++_rewItemsCount;
for (int i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
if (RewardChoiceItemId[i])
++_rewChoiceItemsCount;
for (int i = 0; i < QUEST_REWARD_CURRENCY_COUNT; ++i)
if (RewardCurrencyId[i])
++_rewCurrencyCount;
m_questObjecitveTypeCount.assign(QUEST_OBJECTIVE_TYPE_END, 0);
}
uint32 Quest::XPValue(Player* player) const
{
if (player)
{
int32 quest_level = (Level == -1 ? player->getLevel() : Level);
const QuestXPEntry* xpentry = sQuestXPStore.LookupEntry(quest_level);
if (!xpentry)
return 0;
int32 diffFactor = 2 * (quest_level - player->getLevel()) + 20;
if (diffFactor < 1)
diffFactor = 1;
else if (diffFactor > 10)
diffFactor = 10;
uint32 xp = diffFactor * xpentry->Exp[RewardXPId] / 10;
if (xp <= 100)
xp = 5 * ((xp + 2) / 5);
else if (xp <= 500)
xp = 10 * ((xp + 5) / 10);
else if (xp <= 1000)
xp = 25 * ((xp + 12) / 25);
else
xp = 50 * ((xp + 25) / 50);
return xp;
}
return 0;
}
int32 Quest::GetRewMoney() const
{
return int32(RewardMoney * sWorld->getRate(RATE_DROP_MONEY));
}
uint32 Quest::GetRewMoneyMaxLevel() const
{
if (HasFlag(QUEST_FLAGS_NO_MONEY_FROM_XP))
return 0;
return RewardMoneyMaxLevel;
}
bool Quest::IsAutoAccept() const
{
return sWorld->getBoolConfig(CONFIG_QUEST_IGNORE_AUTO_ACCEPT) ? false : (Flags & QUEST_FLAGS_AUTO_ACCEPT);
}
bool Quest::IsAutoComplete() const
{
return sWorld->getBoolConfig(CONFIG_QUEST_IGNORE_AUTO_COMPLETE) ? false : (Method == 0 || HasFlag(QUEST_FLAGS_AUTOCOMPLETE));
}
bool Quest::IsRaidQuest(Difficulty difficulty) const
{
switch (Type)
{
case QUEST_TYPE_RAID:
return true;
case QUEST_TYPE_RAID_10:
return !(difficulty & RAID_DIFFICULTY_MASK_25MAN);
case QUEST_TYPE_RAID_25:
return difficulty & RAID_DIFFICULTY_MASK_25MAN;
default:
break;
}
return false;
}
bool Quest::IsAllowedInRaid(Difficulty difficulty) const
{
if (IsRaidQuest(difficulty))
return true;
return sWorld->getBoolConfig(CONFIG_QUEST_IGNORE_RAID);
}
uint32 Quest::CalculateHonorGain(uint8 level) const
{
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL;
uint32 honor = 0;
/*if (GetRewHonorAddition() > 0 || GetRewHonorMultiplier() > 0.0f)
{
// values stored from 0.. for 1...
TeamContributionPointsEntry const* tc = sTeamContributionPointsStore.LookupEntry(level);
if (!tc)
return 0;
honor = uint32(tc->value * GetRewHonorMultiplier() * 0.1f);
honor += GetRewHonorAddition();
}*/
return honor;
}
// Note: These next two functions will need to be changed/extended once QuestPackageItem.db2 is implemented
bool Quest::IsRewChoiceItemValid(uint32 itemId) const
{
for (uint8 i = 0; i < QUEST_REWARD_CHOICES_COUNT; i++)
if (RewardChoiceItemId[i] == itemId)
return true;
return false;
}
uint32 Quest::GetRewChoiceItemCount(uint32 itemId) const
{
for (uint8 i = 0; i < QUEST_REWARD_CHOICES_COUNT; i++)
if (RewardChoiceItemId[i] == itemId)
return RewardChoiceItemCount[i];
return 0;
}
QuestObjective const* Quest::GetQuestObjective(uint32 objectiveId) const
{
for (QuestObjectiveSet::const_iterator citr = m_questObjectives.begin(); citr != m_questObjectives.end(); citr++)
if ((*citr)->Id == objectiveId)
return *citr;
return NULL;
}
QuestObjective const* Quest::GetQuestObjectiveXIndex(uint8 index) const
{
for (QuestObjectiveSet::const_iterator citr = m_questObjectives.begin(); citr != m_questObjectives.end(); citr++)
if ((*citr)->Index == index)
return *citr;
return NULL;
}
QuestObjective const* Quest::GetQuestObjectiveXObjectId(uint32 objectId) const
{
for (QuestObjectiveSet::const_iterator citr = m_questObjectives.begin(); citr != m_questObjectives.end(); citr++)
if ((*citr)->ObjectId == objectId)
return *citr;
return NULL;
}
uint8 Quest::GetQuestObjectiveCountType(uint8 type) const
{
if (type >= QUEST_OBJECTIVE_TYPE_END)
return 0;
return m_questObjecitveTypeCount[type];
}
|
gpl-2.0
|
Neo2003/mame4all-pi-adv
|
src/vidhrdw/mermaid.cpp
|
4559
|
/***************************************************************************
vidhrdw.c
Functions to emulate the video hardware of the machine.
***************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
unsigned char* mermaid_background_videoram;
unsigned char* mermaid_foreground_videoram;
unsigned char* mermaid_foreground_colorram;
unsigned char* mermaid_background_scrollram;
unsigned char* mermaid_foreground_scrollram;
static struct rectangle spritevisiblearea =
{
0*8, 26*8-1,
2*8, 30*8-1
};
/***************************************************************************
Convert the color PROMs into a more useable format.
I'm not sure about the resistor value, I'm using the Galaxian ones.
***************************************************************************/
void mermaid_vh_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom)
{
#define TOTAL_COLORS(gfxn) (Machine->gfx[gfxn]->total_colors * Machine->gfx[gfxn]->color_granularity)
#define COLOR(gfxn,offs) (colortable[Machine->drv->gfxdecodeinfo[gfxn].color_codes_start + offs])
int i;
/* first, the char acter/sprite palette */
for (i = 0;i < TOTAL_COLORS(0); i++)
{
int bit0,bit1,bit2;
/* red component */
bit0 = (*color_prom >> 0) & 0x01;
bit1 = (*color_prom >> 1) & 0x01;
bit2 = (*color_prom >> 2) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* green component */
bit0 = (*color_prom >> 3) & 0x01;
bit1 = (*color_prom >> 4) & 0x01;
bit2 = (*color_prom >> 5) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
/* blue component */
bit0 = 0;
bit1 = (*color_prom >> 6) & 0x01;
bit2 = (*color_prom >> 7) & 0x01;
*(palette++) = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
color_prom++;
}
/* blue background */
*(palette++) = 0;
*(palette++) = 0;
*(palette++) = 0xff;
/* set up background palette */
COLOR(2,0) = 32;
COLOR(2,1) = 33;
COLOR(2,2) = 64;
COLOR(2,3) = 33;
}
/***************************************************************************
Draw the game screen in the given osd_bitmap.
Do NOT call osd_update_display() from this function, it will be called by
the main emulation engine.
***************************************************************************/
void mermaid_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh)
{
int offs;
/* for every character in the backround RAM, check if it has been modified */
/* since last time and update it accordingly. */
for (offs = 0; offs < videoram_size; offs ++)
{
int code,sx,sy;
sy = 8 * (offs / 32);
sx = 8 * (offs % 32);
code = mermaid_background_videoram[offs];
drawgfx(tmpbitmap,Machine->gfx[2],
code,
(sx >= 26*8) ? 0 : 1,
0,0,
sx,sy,
0,TRANSPARENCY_NONE,0);
}
/* copy the temporary bitmap to the screen */
{
int i, scroll[32];
for (i = 0;i < 32;i++)
{
scroll[i] = -mermaid_background_scrollram[i];
}
copyscrollbitmap(bitmap,tmpbitmap,0,0,32,scroll,&Machine->visible_area,TRANSPARENCY_NONE,0);
}
/* draw the front layer. They are characters, but draw them as sprites */
for (offs = 0; offs < videoram_size; offs ++)
{
int code,sx,sy;
sy = 8 * (offs / 32);
sx = (offs % 32);
sy = (sy - mermaid_foreground_scrollram[sx]) & 0xff;
code = mermaid_foreground_videoram[offs] | ((mermaid_foreground_colorram[offs] & 0x30) << 4);
drawgfx(bitmap,Machine->gfx[0],
code,
mermaid_foreground_colorram[offs] & 0x0f,
0,0,
8*sx,sy,
&Machine->visible_area,TRANSPARENCY_PEN,0);
}
/* draw the sprites */
for (offs = spriteram_size - 4;offs >= 0;offs -= 4)
{
UINT8 flipx,flipy,sx,sy,code,bank = 0;
sx = spriteram[offs + 3] + 1;
sy = 240 - spriteram[offs + 1];
flipx = spriteram[offs + 0] & 0x40;
flipy = spriteram[offs + 0] & 0x80;
/* this doesn't look correct. Oh really? Maybe there is a PROM. */
switch (spriteram[offs + 2] & 0xf0)
{
case 0x00: bank = 2; break;
case 0x10: bank = 1; break;
case 0x20: bank = 2; break;
case 0x30: bank = 3; break;
case 0x50: bank = 1; break;
case 0x60: bank = 2; break;
case 0x80: bank = 0; break;
case 0x90: bank = 3; break;
case 0xa0: bank = 2; break;
case 0xb0: bank = 3; break;
}
code = (spriteram[offs + 0] & 0x3f) | (bank << 6);
drawgfx(bitmap,Machine->gfx[1],
code,
spriteram[offs + 2] & 0x0f,
flipx, flipy,
sx, sy,
&spritevisiblearea,TRANSPARENCY_PEN,0);
}
}
|
gpl-2.0
|
Kinokoh/hotspotmap
|
web/js/markerclusterer.min.js
|
8303
|
function d(a){return function(b){this[a]=b}}function f(a){return function(){return this[a]}}var k;
function l(a,b,c){this.extend(l,google.maps.OverlayView);this.b=a;this.a=[];this.f=[];this.da=[53,56,66,78,90];this.j=[];this.A=!1;c=c||{};this.g=c.gridSize||60;this.l=c.minimumClusterSize||2;this.K=c.maxZoom||null;this.j=c.styles||[];this.Y=c.imagePath||this.R;this.X=c.imageExtension||this.Q;this.P=!0;void 0!=c.zoomOnClick&&(this.P=c.zoomOnClick);this.r=!1;void 0!=c.averageCenter&&(this.r=c.averageCenter);m(this);this.setMap(a);this.L=this.b.getZoom();var e=this;google.maps.event.addListener(this.b,
"zoom_changed",function(){var a=e.b.getZoom(),b=e.b.minZoom||0,c=Math.min(e.b.maxZoom||100,e.b.mapTypes[e.b.getMapTypeId()].maxZoom),a=Math.min(Math.max(a,b),c);e.L!=a&&(e.L=a,e.m())});google.maps.event.addListener(this.b,"idle",function(){e.i()});b&&(b.length||Object.keys(b).length)&&this.C(b,!1)}k=l.prototype;k.R="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m";k.Q="png";
k.extend=function(a,b){return function(a){for(var b in a.prototype)this.prototype[b]=a.prototype[b];return this}.apply(a,[b])};k.onAdd=function(){this.A||(this.A=!0,p(this))};k.draw=function(){};function m(a){if(!a.j.length)for(var b=0,c;c=a.da[b];b++)a.j.push({url:a.Y+(b+1)+"."+a.X,height:c,width:c})}k.T=function(){for(var a=this.o(),b=new google.maps.LatLngBounds,c=0,e;e=a[c];c++)b.extend(e.getPosition());this.b.fitBounds(b)};k.w=f("j");k.o=f("a");k.W=function(){return this.a.length};k.ca=d("K");
k.J=f("K");k.G=function(a,b){for(var c=0,e=a.length,g=e;0!==g;)g=parseInt(g/10,10),c++;c=Math.min(c,b);return{text:e,index:c}};k.aa=d("G");k.H=f("G");k.C=function(a,b){if(a.length)for(var c=0,e;e=a[c];c++)s(this,e);else if(Object.keys(a).length)for(e in a)s(this,a[e]);b||this.i()};function s(a,b){b.s=!1;b.draggable&&google.maps.event.addListener(b,"dragend",function(){b.s=!1;a.M()});a.a.push(b)}k.q=function(a,b){s(this,a);b||this.i()};
function t(a,b){var c=-1;if(a.a.indexOf)c=a.a.indexOf(b);else for(var e=0,g;g=a.a[e];e++)if(g==b){c=e;break}if(-1==c)return!1;b.setMap(null);a.a.splice(c,1);return!0}k.Z=function(a,b){var c=t(this,a);return!b&&c?(this.m(),this.i(),!0):!1};k.$=function(a,b){for(var c=!1,e=0,g;g=a[e];e++)g=t(this,g),c=c||g;if(!b&&c)return this.m(),this.i(),!0};k.V=function(){return this.f.length};k.getMap=f("b");k.setMap=d("b");k.I=f("g");k.ba=d("g");
k.v=function(a){var b=this.getProjection(),c=new google.maps.LatLng(a.getNorthEast().lat(),a.getNorthEast().lng()),e=new google.maps.LatLng(a.getSouthWest().lat(),a.getSouthWest().lng()),c=b.fromLatLngToDivPixel(c);c.x+=this.g;c.y-=this.g;e=b.fromLatLngToDivPixel(e);e.x-=this.g;e.y+=this.g;c=b.fromDivPixelToLatLng(c);b=b.fromDivPixelToLatLng(e);a.extend(c);a.extend(b);return a};k.S=function(){this.m(!0);this.a=[]};
k.m=function(a){for(var b=0,c;c=this.f[b];b++)c.remove();for(b=0;c=this.a[b];b++)c.s=!1,a&&c.setMap(null);this.f=[]};k.M=function(){var a=this.f.slice();this.f.length=0;this.m();this.i();window.setTimeout(function(){for(var b=0,c;c=a[b];b++)c.remove()},0)};k.i=function(){p(this)};
function p(a){if(a.A)for(var b=new google.maps.LatLngBounds(a.b.getBounds().getSouthWest(),a.b.getBounds().getNorthEast()),b=a.v(b),c=0,e;e=a.a[c];c++)if(!e.s&&b.contains(e.getPosition())){for(var g=a,u=4E4,q=null,x=0,n=void 0;n=g.f[x];x++){var h=n.getCenter();if(h){var r=e.getPosition();if(h&&r)var y=(r.lat()-h.lat())*Math.PI/180,z=(r.lng()-h.lng())*Math.PI/180,h=Math.sin(y/2)*Math.sin(y/2)+Math.cos(h.lat()*Math.PI/180)*Math.cos(r.lat()*Math.PI/180)*Math.sin(z/2)*Math.sin(z/2),h=12742*Math.atan2(Math.sqrt(h),
Math.sqrt(1-h));else h=0;h<u&&(u=h,q=n)}}q&&q.F.contains(e.getPosition())?q.q(e):(n=new v(g),n.q(e),g.f.push(n))}}function v(a){this.k=a;this.b=a.getMap();this.g=a.I();this.l=a.l;this.r=a.r;this.d=null;this.a=[];this.F=null;this.n=new w(this,a.w())}k=v.prototype;
k.q=function(a){var b;a:if(this.a.indexOf)b=-1!=this.a.indexOf(a);else{b=0;for(var c;c=this.a[b];b++)if(c==a){b=!0;break a}b=!1}if(b)return!1;this.d?this.r&&(c=this.a.length+1,b=(this.d.lat()*(c-1)+a.getPosition().lat())/c,c=(this.d.lng()*(c-1)+a.getPosition().lng())/c,this.d=new google.maps.LatLng(b,c),A(this)):(this.d=a.getPosition(),A(this));a.s=!0;this.a.push(a);b=this.a.length;b<this.l&&a.getMap()!=this.b&&a.setMap(this.b);if(b==this.l)for(c=0;c<b;c++)this.a[c].setMap(null);b>=this.l&&a.setMap(null);
a=this.b.getZoom();if((b=this.k.J())&&a>b)for(a=0;b=this.a[a];a++)b.setMap(this.b);else this.a.length<this.l?B(this.n):(b=this.k.H()(this.a,this.k.w().length),this.n.setCenter(this.d),a=this.n,a.B=b,a.c&&(a.c.innerHTML=b.text),b=Math.max(0,a.B.index-1),b=Math.min(a.j.length-1,b),b=a.j[b],a.ea=b.url,a.h=b.height,a.p=b.width,a.N=b.textColor,a.e=b.anchor,a.O=b.textSize,a.D=b.backgroundPosition,this.n.show());return!0};
k.getBounds=function(){for(var a=new google.maps.LatLngBounds(this.d,this.d),b=this.o(),c=0,e;e=b[c];c++)a.extend(e.getPosition());return a};k.remove=function(){this.n.remove();this.a.length=0;delete this.a};k.U=function(){return this.a.length};k.o=f("a");k.getCenter=f("d");function A(a){var b=new google.maps.LatLngBounds(a.d,a.d);a.F=a.k.v(b)}k.getMap=f("b");
function w(a,b){a.k.extend(w,google.maps.OverlayView);this.j=b;this.u=a;this.d=null;this.b=a.getMap();this.B=this.c=null;this.t=!1;this.setMap(this.b)}k=w.prototype;
k.onAdd=function(){this.c=document.createElement("DIV");if(this.t){var a=C(this,this.d);this.c.style.cssText=D(this,a);this.c.innerHTML=this.B.text}this.getPanes().overlayMouseTarget.appendChild(this.c);var b=this;google.maps.event.addDomListener(this.c,"click",function(){var a=b.u.k;google.maps.event.trigger(a,"clusterclick",b.u);a.P&&b.b.fitBounds(b.u.getBounds())})};function C(a,b){var c=a.getProjection().fromLatLngToDivPixel(b);c.x-=parseInt(a.p/2,10);c.y-=parseInt(a.h/2,10);return c}
k.draw=function(){if(this.t){var a=C(this,this.d);this.c.style.top=a.y+"px";this.c.style.left=a.x+"px"}};function B(a){a.c&&(a.c.style.display="none");a.t=!1}k.show=function(){if(this.c){var a=C(this,this.d);this.c.style.cssText=D(this,a);this.c.style.display=""}this.t=!0};k.remove=function(){this.setMap(null)};k.onRemove=function(){this.c&&this.c.parentNode&&(B(this),this.c.parentNode.removeChild(this.c),this.c=null)};k.setCenter=d("d");
function D(a,b){var c=[];c.push("background-image:url("+a.ea+");");c.push("background-position:"+(a.D?a.D:"0 0")+";");"object"===typeof a.e?("number"===typeof a.e[0]&&0<a.e[0]&&a.e[0]<a.h?c.push("height:"+(a.h-a.e[0])+"px; padding-top:"+a.e[0]+"px;"):c.push("height:"+a.h+"px; line-height:"+a.h+"px;"),"number"===typeof a.e[1]&&0<a.e[1]&&a.e[1]<a.p?c.push("width:"+(a.p-a.e[1])+"px; padding-left:"+a.e[1]+"px;"):c.push("width:"+a.p+"px; text-align:center;")):c.push("height:"+a.h+"px; line-height:"+a.h+
"px; width:"+a.p+"px; text-align:center;");c.push("cursor:pointer; top:"+b.y+"px; left:"+b.x+"px; color:"+(a.N?a.N:"black")+"; position:absolute; font-size:"+(a.O?a.O:11)+"px; font-family:Arial,sans-serif; font-weight:bold");return c.join("")}window.MarkerClusterer=l;l.prototype.addMarker=l.prototype.q;l.prototype.addMarkers=l.prototype.C;l.prototype.clearMarkers=l.prototype.S;l.prototype.fitMapToMarkers=l.prototype.T;l.prototype.getCalculator=l.prototype.H;l.prototype.getGridSize=l.prototype.I;
l.prototype.getExtendedBounds=l.prototype.v;l.prototype.getMap=l.prototype.getMap;l.prototype.getMarkers=l.prototype.o;l.prototype.getMaxZoom=l.prototype.J;l.prototype.getStyles=l.prototype.w;l.prototype.getTotalClusters=l.prototype.V;l.prototype.getTotalMarkers=l.prototype.W;l.prototype.redraw=l.prototype.i;l.prototype.removeMarker=l.prototype.Z;l.prototype.removeMarkers=l.prototype.$;l.prototype.resetViewport=l.prototype.m;l.prototype.repaint=l.prototype.M;l.prototype.setCalculator=l.prototype.aa;
l.prototype.setGridSize=l.prototype.ba;l.prototype.setMaxZoom=l.prototype.ca;l.prototype.onAdd=l.prototype.onAdd;l.prototype.draw=l.prototype.draw;v.prototype.getCenter=v.prototype.getCenter;v.prototype.getSize=v.prototype.U;v.prototype.getMarkers=v.prototype.o;w.prototype.onAdd=w.prototype.onAdd;w.prototype.draw=w.prototype.draw;w.prototype.onRemove=w.prototype.onRemove;Object.keys=Object.keys||function(a){var b=[],c;for(c in a)a.hasOwnProperty(c)&&b.push(c);return b};
|
gpl-2.0
|
kunj1988/Magento2
|
app/code/Magento/Reports/Controller/Adminhtml/Report/Sales/ExportCouponsExcel.php
|
811
|
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Reports\Controller\Adminhtml\Report\Sales;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
class ExportCouponsExcel extends \Magento\Reports\Controller\Adminhtml\Report\Sales
{
/**
* Export coupons report grid to Excel XML format
*
* @return ResponseInterface
*/
public function execute()
{
$fileName = 'coupons.xml';
$grid = $this->_view->getLayout()->createBlock(\Magento\Reports\Block\Adminhtml\Sales\Coupons\Grid::class);
$this->_initReportAction($grid);
return $this->_fileFactory->create($fileName, $grid->getExcelFile($fileName), DirectoryList::VAR_DIR);
}
}
|
gpl-2.0
|
sani-coop/tinjaca
|
doc/informe1/_graphviz/bpmn_pgv.py
|
4453
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
BPMN PGV generates BPMN diagrams from graphviz using pygraphviz. This is an early alpha, usable but lacks many features
and configuration flexibility.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__author__ = 'mapologo'
import pygraphviz as pgv
from textwrap import fill
IMAGE_PATH = "../_static/"
LABEL_TEMPLATE = """<<TABLE border="0" cellborder="0">
<TR><TD align="left"><IMG SRC="{}"/></TD></TR>
<TR><TD>{}</TD></TR>
</TABLE>>"""
TITLE_TEMPLATE = "<<B>{}</B>>"
GATE_TEMPLATE = """<<TABLE border="0" cellborder="0" cellpadding="0">
<TR><TD><IMG SRC="{}"/></TD></TR>
</TABLE>>"""
ACTIV_ICON = {"human": IMAGE_PATH + "person.png",
"message": IMAGE_PATH + "envelope.png"}
EV_STYLE = {"start": "filled", "end": "filled, bold"}
TEXT_WIDTH = 25
def add_event(G, node, xlabel, ev_type):
"""
Add an event node to G with label xlabel and event type ev_type.
:param G: a pygraphviz AGraph.
:param node: a string or string convertable.
:param xlabel: a string used as identifier.
:param ev_type: a string used as EV_STYLE key.
:return: None
"""
G.add_node(node, label="", xlabel=fill(xlabel, TEXT_WIDTH), shape="circle", width="0.6",
style=EV_STYLE[ev_type], fillcolor="white:grey", fontsize="10")
def add_activity(G, node, label, act_type):
"""
Add an activity node to G with label and activity type act_type.
:param G: a pygraphviz AGraph.
:param node: a string or string convertable.
:param label: a string used as identifier.
:param act_type: a string used as ACTIV_ICON key.
:return: None
"""
label = fill(label, TEXT_WIDTH)
label = label.replace('\n', '<br/>')
label = LABEL_TEMPLATE.format(ACTIV_ICON[act_type], label)
G.add_node(node, label=label, shape="box", style="rounded,filled", fillcolor="white:grey")
GATE_ICON = {"exclusive": IMAGE_PATH + "cross.png",
"complex": IMAGE_PATH + "asterisk.png"}
def add_gateway(G, node, xlabel, gate_type):
"""
Add a gateway node to G with xlabel and gate type gate_type.
:param G: a pygraphviz AGraph.
:param node: a string or string convertable.
:param xlabel: a string used as identifier.
:param gate_type: a string used as GATE_ICON key.
:return:
"""
G.add_node(node, label=GATE_TEMPLATE.format(GATE_ICON[gate_type]), xlabel=xlabel, shape="diamond",
style="filled", fillcolor="white:grey", fontsize="10", width="1", height="1", fixedsize="true")
ADD_ELEM = {"start": add_event,
"end": add_event,
"human": add_activity,
"message": add_activity,
"exclusive": add_gateway,
"complex": add_gateway}
def add_edges(G, edge_list):
"""
Add edges to G given by edge_list
:param G:
:param edge_list: A dict of dicts of dicts. A dict of origin nodes which has a dict of destination nodes which has
a dict of attributes.
:return: updated G
"""
for orig, dests in edge_list.items():
for dest, attrs in dests.items():
G.add_edge(orig, dest)
if attrs:
E = G.get_edge(orig, dest)
for (k, v) in attrs.items():
E.attr[k] = v
return(G)
def add_cluster(G, name, label, cluster_nodes, cluster_edges):
"""
Add a cluster subgraph to G with name "cluster_" + name and label. Comprehends a cluster_nodes bunch of nodes
connected internally with cluster_edges.
:param G: a pygraphviz AGraph.
:param name: a string or string convertable.
:param label: a string used as identifier, will be converted to "cluster_" + name.
:param cluster_nodes: A list of str.
:param cluster_edges: A dict of dicts of dicts. A dict of origin nodes which has a dict of destination nodes which
has a dict of attributes.
:return:
"""
name = "cluster_" + name
nodes = cluster_nodes.keys()
G.add_subgraph(nodes, name)
S = G.get_subgraph(name)
S.graph_attr.update(label=TITLE_TEMPLATE.format(label), labeljust="l")
for node, (label, node_type) in cluster_nodes.items():
ADD_ELEM[node_type](S, node, label, node_type)
add_edges(S, cluster_edges)
return(S)
|
gpl-2.0
|
oat-sa/extension-tao-itemqti
|
model/qti/attribute/PowerForm.php
|
1334
|
<?php
/*
* 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; under version 2
* of the License (non-upgradable).
*
* 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.
*
* Copyright (c) 2013 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
*
*
*/
namespace oat\taoQtiItem\model\qti\attribute;
use oat\taoQtiItem\model\qti\attribute\PowerForm;
use oat\taoQtiItem\model\qti\attribute\Attribute;
/**
* The PowerForm attribute
*
* @access public
* @author Sam, <sam@taotesting.com>
* @package taoQTI
*/
class PowerForm extends Attribute
{
protected static $name = 'powerForm';
protected static $type = 'oat\\taoQtiItem\\model\\qti\\datatype\\QtiBoolean';
protected static $defaultValue = null;
protected static $required = false;
}
|
gpl-2.0
|
ghorbanzade/ghorcom
|
src/view/teaching-github.php
|
171
|
<?php
if (isset($course)) {
echo "<h3>".$course->get_name()." <small>".$course->get_semester()."</small></h3>";
echo "<h4>Course Repository</h4>";
echo "<hr></hr>";
}
|
gpl-2.0
|
azadmanesh/sl-tracer
|
truffle/com.oracle.truffle.object.basic/src/com/oracle/truffle/object/basic/BasicLocations.java
|
24511
|
/*
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. 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.
*
* 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.object.basic;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.object.BooleanLocation;
import com.oracle.truffle.api.object.DoubleLocation;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.object.FinalLocationException;
import com.oracle.truffle.api.object.IncompatibleLocationException;
import com.oracle.truffle.api.object.IntLocation;
import com.oracle.truffle.api.object.Location;
import com.oracle.truffle.api.object.LongLocation;
import com.oracle.truffle.api.object.ObjectLocation;
import com.oracle.truffle.api.object.Property;
import com.oracle.truffle.api.object.Shape;
import com.oracle.truffle.object.LocationImpl;
import com.oracle.truffle.object.LocationImpl.InternalLongLocation;
import java.lang.invoke.MethodHandle;
/**
* Property location.
*
* @see Shape
* @see Property
* @see DynamicObject
*/
public abstract class BasicLocations {
static final int LONG_SIZE = 1;
static final int OBJECT_SIZE = 1;
public abstract static class ArrayLocation extends LocationImpl {
protected final int index;
protected final Location arrayLocation;
public ArrayLocation(int index, Location arrayLocation) {
this.index = index;
this.arrayLocation = arrayLocation;
}
protected final Object getArray(DynamicObject store, boolean condition) {
// non-null cast
return arrayLocation.get(store, condition);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + index;
return result;
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
ArrayLocation other = (ArrayLocation) obj;
if (index != other.index) {
return false;
}
return true;
}
public final int getIndex() {
return index;
}
@Override
public String getWhereString() {
return "[" + index + "]";
}
}
public abstract static class FieldLocation extends LocationImpl {
private final int index;
public FieldLocation(int index) {
this.index = index;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + index;
return result;
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
FieldLocation other = (FieldLocation) obj;
if (index != other.index) {
return false;
}
return true;
}
public final int getIndex() {
return index;
}
@Override
public String getWhereString() {
return "@" + index;
}
}
public abstract static class MethodHandleFieldLocation extends FieldLocation {
protected final MethodHandle getter;
protected final MethodHandle setter;
public MethodHandleFieldLocation(int index, MethodHandle getter, MethodHandle setter) {
super(index);
this.getter = getter;
this.setter = setter;
}
}
public static class ObjectArrayLocation extends ArrayLocation implements ObjectLocation {
public ObjectArrayLocation(int index, Location arrayLocation) {
super(index, arrayLocation);
}
@Override
public Object get(DynamicObject store, boolean condition) {
return ((Object[]) getArray(store, condition))[index];
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
((Object[]) getArray(store, false))[index] = value;
}
@Override
public boolean canStore(Object value) {
return true;
}
public Class<? extends Object> getType() {
return Object.class;
}
public final boolean isNonNull() {
return false;
}
@Override
public int objectArrayCount() {
return OBJECT_SIZE;
}
@Override
public final void accept(LocationVisitor locationVisitor) {
locationVisitor.visitObjectArray(index, OBJECT_SIZE);
}
}
public static class ObjectFieldLocation extends MethodHandleFieldLocation implements ObjectLocation {
public ObjectFieldLocation(int index, MethodHandle getter, MethodHandle setter) {
super(index, getter, setter);
}
@Override
public Object get(DynamicObject store, boolean condition) {
try {
return getter.invokeExact(store);
} catch (Throwable e) {
CompilerDirectives.transferToInterpreter();
throw new IllegalStateException(e);
}
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
try {
setter.invokeExact(store, value);
} catch (Throwable e) {
CompilerDirectives.transferToInterpreter();
throw new IllegalStateException(e);
}
}
@Override
public boolean canStore(Object value) {
return true;
}
public Class<? extends Object> getType() {
return Object.class;
}
public boolean isNonNull() {
return false;
}
@Override
public int objectFieldCount() {
return OBJECT_SIZE;
}
@Override
public final void accept(LocationVisitor locationVisitor) {
locationVisitor.visitObjectField(getIndex(), OBJECT_SIZE);
}
}
public abstract static class SimpleObjectFieldLocation extends FieldLocation implements ObjectLocation {
public SimpleObjectFieldLocation(int index) {
super(index);
}
@Override
public abstract Object get(DynamicObject store, boolean condition);
@Override
public abstract void setInternal(DynamicObject store, Object value);
@Override
public boolean canStore(Object value) {
return true;
}
public Class<? extends Object> getType() {
return Object.class;
}
public boolean isNonNull() {
return false;
}
@Override
public int objectFieldCount() {
return OBJECT_SIZE;
}
@Override
public final void accept(LocationVisitor locationVisitor) {
locationVisitor.visitObjectField(getIndex(), OBJECT_SIZE);
}
}
public static class LongArrayLocation extends ArrayLocation implements InternalLongLocation {
protected final boolean allowInt;
public LongArrayLocation(int index, Location arrayLocation, boolean allowInt) {
super(index, arrayLocation);
this.allowInt = allowInt;
}
public LongArrayLocation(int index, Location arrayLocation) {
this(index, arrayLocation, false);
}
@Override
public final Object get(DynamicObject store, boolean condition) {
return getLong(store, condition);
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
if (canStore(value)) {
setLongInternal(store, ((Number) value).longValue());
} else {
throw incompatibleLocation();
}
}
@Override
public long getLong(DynamicObject store, boolean condition) {
return ((long[]) getArray(store, condition))[index];
}
public final void setLongInternal(DynamicObject store, long value) {
((long[]) getArray(store, false))[index] = value;
}
@Override
public void setLong(DynamicObject store, long value, Shape shape) throws FinalLocationException {
setLongInternal(store, value);
}
@Override
public final void setLong(DynamicObject store, long value, Shape oldShape, Shape newShape) {
store.setShapeAndGrow(oldShape, newShape);
setLongInternal(store, value);
}
@Override
public final void setLong(DynamicObject store, long value) throws FinalLocationException {
setLong(store, value, null);
}
public final long getLong(DynamicObject store, Shape shape) {
return getLong(store, checkShape(store, shape));
}
@Override
public final boolean canStore(Object value) {
return value instanceof Long || (allowInt && value instanceof Integer);
}
public final Class<Long> getType() {
return long.class;
}
@Override
public int primitiveArrayCount() {
return LONG_SIZE;
}
@Override
public final void accept(LocationVisitor locationVisitor) {
locationVisitor.visitPrimitiveArray(getIndex(), LONG_SIZE);
}
}
public static class LongFieldLocation extends MethodHandleFieldLocation implements InternalLongLocation {
public LongFieldLocation(int index, MethodHandle getter, MethodHandle setter) {
super(index, getter, setter);
}
public static LongLocation create(InternalLongLocation longLocation, boolean allowInt) {
if ((!allowInt && (longLocation instanceof LongLocationDecorator)) || (longLocation instanceof LongLocationDecorator && ((LongLocationDecorator) longLocation).allowInt == allowInt)) {
return longLocation;
} else {
return new LongLocationDecorator(longLocation, allowInt);
}
}
@Override
public final Object get(DynamicObject store, boolean condition) {
return getLong(store, condition);
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
if (canStore(value)) {
setLongInternal(store, (long) value);
} else {
throw incompatibleLocation();
}
}
@Override
public final boolean canStore(Object value) {
return value instanceof Long;
}
@Override
public final void setLong(DynamicObject store, long value, Shape oldShape, Shape newShape) {
store.setShapeAndGrow(oldShape, newShape);
setLongInternal(store, value);
}
public long getLong(DynamicObject store, boolean condition) {
try {
return (long) getter.invokeExact(store);
} catch (Throwable e) {
CompilerDirectives.transferToInterpreter();
throw new IllegalStateException(e);
}
}
public void setLong(DynamicObject store, long value, Shape shape) {
setLongInternal(store, value);
}
public final void setLong(DynamicObject store, long value) throws FinalLocationException {
setLong(store, value, null);
}
public final void setLongInternal(DynamicObject store, long value) {
try {
setter.invokeExact(store, value);
} catch (Throwable e) {
CompilerDirectives.transferToInterpreter();
throw new IllegalStateException(e);
}
}
public final long getLong(DynamicObject store, Shape shape) {
return getLong(store, checkShape(store, shape));
}
@Override
public final int primitiveFieldCount() {
return LONG_SIZE;
}
public final Class<Long> getType() {
return long.class;
}
@Override
public final void accept(LocationVisitor locationVisitor) {
locationVisitor.visitPrimitiveField(getIndex(), LONG_SIZE);
}
}
public static class LongLocationDecorator extends PrimitiveLocationDecorator implements InternalLongLocation {
protected final boolean allowInt;
public LongLocationDecorator(InternalLongLocation longLocation, boolean allowInt) {
super(longLocation);
this.allowInt = allowInt;
}
@Override
public final Object get(DynamicObject store, boolean condition) {
return getLong(store, condition);
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
if (canStore(value)) {
setLongInternal(store, ((Number) value).longValue());
} else {
throw incompatibleLocation();
}
}
@Override
public final boolean canStore(Object value) {
return value instanceof Long || (allowInt && value instanceof Integer);
}
@Override
public final void setLong(DynamicObject store, long value, Shape oldShape, Shape newShape) {
store.setShapeAndGrow(oldShape, newShape);
setLongInternal(store, value);
}
public Class<Long> getType() {
return long.class;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj) && this.allowInt == ((LongLocationDecorator) obj).allowInt;
}
}
public abstract static class SimpleLongFieldLocation extends FieldLocation implements InternalLongLocation {
public SimpleLongFieldLocation(int index) {
super(index);
}
@Override
public final Object get(DynamicObject store, boolean condition) {
return getLong(store, condition);
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
if (canStore(value)) {
setLongInternal(store, ((Number) value).longValue());
} else {
throw incompatibleLocation();
}
}
@Override
public final boolean canStore(Object value) {
return value instanceof Long;
}
@Override
public final void setLong(DynamicObject store, long value, Shape oldShape, Shape newShape) {
store.setShapeAndGrow(oldShape, newShape);
setLongInternal(store, value);
}
public abstract long getLong(DynamicObject store, boolean condition);
public final long getLong(DynamicObject store, Shape shape) {
return getLong(store, checkShape(store, shape));
}
public final void setLong(DynamicObject store, long value) {
setLong(store, value, null);
}
public void setLong(DynamicObject store, long value, Shape shape) {
setLongInternal(store, value);
}
public abstract void setLongInternal(DynamicObject store, long value);
@Override
public final int primitiveFieldCount() {
return LONG_SIZE;
}
public final Class<Long> getType() {
return long.class;
}
@Override
public final void accept(LocationVisitor locationVisitor) {
locationVisitor.visitPrimitiveField(getIndex(), LONG_SIZE);
}
}
public abstract static class PrimitiveLocationDecorator extends LocationImpl {
private final InternalLongLocation longLocation;
public PrimitiveLocationDecorator(InternalLongLocation longLocation) {
this.longLocation = longLocation;
}
public final long getLong(DynamicObject store, Shape shape) {
return longLocation.getLong(store, shape);
}
public final long getLong(DynamicObject store, boolean condition) {
return longLocation.getLong(store, condition);
}
public final void setLong(DynamicObject store, long value, Shape shape) throws FinalLocationException {
longLocation.setLong(store, value, shape);
}
public final void setLong(DynamicObject store, long value) throws FinalLocationException {
longLocation.setLong(store, value);
}
public final void setLongInternal(DynamicObject store, long value) {
longLocation.setLongInternal(store, value);
}
public final InternalLongLocation getInternalLocation() {
return longLocation;
}
@Override
public final int primitiveFieldCount() {
return ((LocationImpl) longLocation).primitiveFieldCount();
}
@Override
public final int primitiveArrayCount() {
return ((LocationImpl) longLocation).primitiveArrayCount();
}
@Override
public final void accept(LocationVisitor locationVisitor) {
((LocationImpl) longLocation).accept(locationVisitor);
}
@Override
public String getWhereString() {
return longLocation.getWhereString();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj) && this.longLocation.equals(((PrimitiveLocationDecorator) obj).longLocation);
}
@Override
public int hashCode() {
return longLocation.hashCode();
}
}
public static class IntLocationDecorator extends PrimitiveLocationDecorator implements IntLocation {
public IntLocationDecorator(InternalLongLocation longLocation) {
super(longLocation);
}
@Override
public final Object get(DynamicObject store, boolean condition) {
return getInt(store, condition);
}
public int getInt(DynamicObject store, boolean condition) {
return (int) getLong(store, condition);
}
public void setInt(DynamicObject store, int value, Shape shape) throws FinalLocationException {
setLong(store, value, shape);
}
@Override
public final void setInt(DynamicObject store, int value) throws FinalLocationException {
setInt(store, value, null);
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
if (canStore(value)) {
setLongInternal(store, (int) value);
} else {
throw incompatibleLocation();
}
}
public final int getInt(DynamicObject store, Shape shape) {
return getInt(store, checkShape(store, shape));
}
@Override
public final boolean canStore(Object value) {
return value instanceof Integer;
}
@Override
public final void setInt(DynamicObject store, int value, Shape oldShape, Shape newShape) {
store.setShapeAndGrow(oldShape, newShape);
setLongInternal(store, value);
}
public Class<Integer> getType() {
return int.class;
}
}
public static class DoubleLocationDecorator extends PrimitiveLocationDecorator implements DoubleLocation {
private final boolean allowInt;
public DoubleLocationDecorator(InternalLongLocation longLocation, boolean allowInt) {
super(longLocation);
this.allowInt = allowInt;
}
@Override
public final Object get(DynamicObject store, boolean condition) {
return getDouble(store, condition);
}
public double getDouble(DynamicObject store, boolean condition) {
return Double.longBitsToDouble(getLong(store, condition));
}
public void setDouble(DynamicObject store, double value, Shape shape) {
setLongInternal(store, Double.doubleToRawLongBits(value));
}
public void setDouble(DynamicObject store, double value) {
setDouble(store, value, null);
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
if (canStore(value)) {
setDouble(store, ((Number) value).doubleValue(), null);
} else {
throw incompatibleLocation();
}
}
public final double getDouble(DynamicObject store, Shape shape) {
return getDouble(store, checkShape(store, shape));
}
@Override
public final boolean canStore(Object value) {
return value instanceof Double || (allowInt && value instanceof Integer);
}
@Override
public final void setDouble(DynamicObject store, double value, Shape oldShape, Shape newShape) {
store.setShapeAndGrow(oldShape, newShape);
setDouble(store, value, newShape);
}
public Class<Double> getType() {
return double.class;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj) && this.allowInt == ((DoubleLocationDecorator) obj).allowInt;
}
}
public static class BooleanLocationDecorator extends PrimitiveLocationDecorator implements BooleanLocation {
public BooleanLocationDecorator(InternalLongLocation longLocation) {
super(longLocation);
}
@Override
public final Object get(DynamicObject store, boolean condition) {
return getBoolean(store, condition);
}
public boolean getBoolean(DynamicObject store, boolean condition) {
return getLong(store, condition) != 0;
}
public void setBoolean(DynamicObject store, boolean value, Shape shape) {
setLongInternal(store, value ? 1 : 0);
}
public void setBoolean(DynamicObject store, boolean value) {
setBoolean(store, value, null);
}
@Override
public final void setInternal(DynamicObject store, Object value) throws IncompatibleLocationException {
if (canStore(value)) {
setBoolean(store, (boolean) value, null);
} else {
throw incompatibleLocation();
}
}
public final boolean getBoolean(DynamicObject store, Shape shape) {
return getBoolean(store, checkShape(store, shape));
}
@Override
public final boolean canStore(Object value) {
return value instanceof Boolean;
}
@Override
public final void setBoolean(DynamicObject store, boolean value, Shape oldShape, Shape newShape) {
store.setShapeAndGrow(oldShape, newShape);
setBoolean(store, value, newShape);
}
public Class<Boolean> getType() {
return boolean.class;
}
}
}
|
gpl-2.0
|
latentPrion/zambesii
|
core/kernel/common/memoryTrib/vaddrSpaceStream.cpp
|
1462
|
#include <debug.h>
#include <__kclasses/debugPipe.h>
#include <kernel/common/process.h>
#include <kernel/common/memoryTrib/vaddrSpaceStream.h>
error_t VaddrSpaceStream::initialize(void)
{
error_t ret;
ret = vaddrSpace.initialize(parent->addrSpaceBinding);
if (ret != ERROR_SUCCESS) { return ret; };
ret = pageCache.initialize();
if (ret != ERROR_SUCCESS) { return ret; };
return vSwamp.initialize();
}
error_t VaddrSpaceStream::bind(void)
{
return ERROR_SUCCESS;
}
void VaddrSpaceStream::cut(void)
{
}
void VaddrSpaceStream::dump(void)
{
printf(NOTICE"VaddrSpaceStream %x: Level0: v: %p, p: %P\n",
id, vaddrSpace.level0Accessor.rsrc,
&vaddrSpace.level0Paddr);
printf(NOTICE"vaddrSpace object: v %p, p %P\n",
vaddrSpace.level0Accessor.rsrc, &vaddrSpace.level0Paddr);
vSwamp.dump();
}
void *VaddrSpaceStream::getPages(uarch_t nPages)
{
void *ret = 0;
// First try to allocate from the page cache.
if (pageCache.pop(nPages, &ret) == ERROR_SUCCESS) {
return ret;
};
/* Cache allocation attempt failed. Get free pages from the swamp. If that
* fails then it means the process simply has no more virtual memory.
**/
return vSwamp.getPages(nPages);
}
void VaddrSpaceStream::releasePages(void *vaddr, uarch_t nPages)
{
// First try to free to the page cache.
if (pageCache.push(nPages, vaddr) == ERROR_SUCCESS) {
return;
};
// Cache free failed. Cache is full. Free to the swamp.
vSwamp.releasePages(vaddr, nPages);
}
|
gpl-2.0
|
vconrado/gtest-example
|
src/test/Multiply_Test.cpp
|
379
|
#include <limits.h>
#include "gtest/gtest.h"
#include "Multiply.hpp"
class MultiplyTest : public ::testing::Test {
protected:
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(MultiplyTest,twoValues){
const int x = 4;
const int y = 5;
Multiply multiply;
EXPECT_EQ(20,multiply.twoValues(x,y));
EXPECT_EQ(6,multiply.twoValues(2,3));
}
|
gpl-2.0
|
Team-OfferManager/ebay-jaxb-bindings
|
src/main/java/de/idealo/offers/imports/offermanager/ebay/api/binding/jaxb/trading/GetMyeBaySellingRequestType.java
|
8800
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2014.11.06 um 02:47:13 AM CET
//
package de.idealo.offers.imports.offermanager.ebay.api.binding.jaxb.trading;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Returns items from the Selling section of the user's My eBay account,
* including items that the user is currently selling (the Active list),
* items that have bids, sold items, and unsold items.
*
*
* <p>Java-Klasse für GetMyeBaySellingRequestType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="GetMyeBaySellingRequestType">
* <complexContent>
* <extension base="{urn:ebay:apis:eBLBaseComponents}AbstractRequestType">
* <sequence>
* <element name="ScheduledList" type="{urn:ebay:apis:eBLBaseComponents}ItemListCustomizationType" minOccurs="0"/>
* <element name="ActiveList" type="{urn:ebay:apis:eBLBaseComponents}ItemListCustomizationType" minOccurs="0"/>
* <element name="SoldList" type="{urn:ebay:apis:eBLBaseComponents}ItemListCustomizationType" minOccurs="0"/>
* <element name="UnsoldList" type="{urn:ebay:apis:eBLBaseComponents}ItemListCustomizationType" minOccurs="0"/>
* <element name="BidList" type="{urn:ebay:apis:eBLBaseComponents}ItemListCustomizationType" minOccurs="0"/>
* <element name="DeletedFromSoldList" type="{urn:ebay:apis:eBLBaseComponents}ItemListCustomizationType" minOccurs="0"/>
* <element name="DeletedFromUnsoldList" type="{urn:ebay:apis:eBLBaseComponents}ItemListCustomizationType" minOccurs="0"/>
* <element name="SellingSummary" type="{urn:ebay:apis:eBLBaseComponents}ItemListCustomizationType" minOccurs="0"/>
* <element name="HideVariations" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GetMyeBaySellingRequestType", propOrder = {
"scheduledList",
"activeList",
"soldList",
"unsoldList",
"bidList",
"deletedFromSoldList",
"deletedFromUnsoldList",
"sellingSummary",
"hideVariations"
})
public class GetMyeBaySellingRequestType
extends AbstractRequestType
{
@XmlElement(name = "ScheduledList")
protected ItemListCustomizationType scheduledList;
@XmlElement(name = "ActiveList")
protected ItemListCustomizationType activeList;
@XmlElement(name = "SoldList")
protected ItemListCustomizationType soldList;
@XmlElement(name = "UnsoldList")
protected ItemListCustomizationType unsoldList;
@XmlElement(name = "BidList")
protected ItemListCustomizationType bidList;
@XmlElement(name = "DeletedFromSoldList")
protected ItemListCustomizationType deletedFromSoldList;
@XmlElement(name = "DeletedFromUnsoldList")
protected ItemListCustomizationType deletedFromUnsoldList;
@XmlElement(name = "SellingSummary")
protected ItemListCustomizationType sellingSummary;
@XmlElement(name = "HideVariations")
protected Boolean hideVariations;
/**
* Ruft den Wert der scheduledList-Eigenschaft ab.
*
* @return
* possible object is
* {@link ItemListCustomizationType }
*
*/
public ItemListCustomizationType getScheduledList() {
return scheduledList;
}
/**
* Legt den Wert der scheduledList-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ItemListCustomizationType }
*
*/
public void setScheduledList(ItemListCustomizationType value) {
this.scheduledList = value;
}
/**
* Ruft den Wert der activeList-Eigenschaft ab.
*
* @return
* possible object is
* {@link ItemListCustomizationType }
*
*/
public ItemListCustomizationType getActiveList() {
return activeList;
}
/**
* Legt den Wert der activeList-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ItemListCustomizationType }
*
*/
public void setActiveList(ItemListCustomizationType value) {
this.activeList = value;
}
/**
* Ruft den Wert der soldList-Eigenschaft ab.
*
* @return
* possible object is
* {@link ItemListCustomizationType }
*
*/
public ItemListCustomizationType getSoldList() {
return soldList;
}
/**
* Legt den Wert der soldList-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ItemListCustomizationType }
*
*/
public void setSoldList(ItemListCustomizationType value) {
this.soldList = value;
}
/**
* Ruft den Wert der unsoldList-Eigenschaft ab.
*
* @return
* possible object is
* {@link ItemListCustomizationType }
*
*/
public ItemListCustomizationType getUnsoldList() {
return unsoldList;
}
/**
* Legt den Wert der unsoldList-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ItemListCustomizationType }
*
*/
public void setUnsoldList(ItemListCustomizationType value) {
this.unsoldList = value;
}
/**
* Ruft den Wert der bidList-Eigenschaft ab.
*
* @return
* possible object is
* {@link ItemListCustomizationType }
*
*/
public ItemListCustomizationType getBidList() {
return bidList;
}
/**
* Legt den Wert der bidList-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ItemListCustomizationType }
*
*/
public void setBidList(ItemListCustomizationType value) {
this.bidList = value;
}
/**
* Ruft den Wert der deletedFromSoldList-Eigenschaft ab.
*
* @return
* possible object is
* {@link ItemListCustomizationType }
*
*/
public ItemListCustomizationType getDeletedFromSoldList() {
return deletedFromSoldList;
}
/**
* Legt den Wert der deletedFromSoldList-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ItemListCustomizationType }
*
*/
public void setDeletedFromSoldList(ItemListCustomizationType value) {
this.deletedFromSoldList = value;
}
/**
* Ruft den Wert der deletedFromUnsoldList-Eigenschaft ab.
*
* @return
* possible object is
* {@link ItemListCustomizationType }
*
*/
public ItemListCustomizationType getDeletedFromUnsoldList() {
return deletedFromUnsoldList;
}
/**
* Legt den Wert der deletedFromUnsoldList-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ItemListCustomizationType }
*
*/
public void setDeletedFromUnsoldList(ItemListCustomizationType value) {
this.deletedFromUnsoldList = value;
}
/**
* Ruft den Wert der sellingSummary-Eigenschaft ab.
*
* @return
* possible object is
* {@link ItemListCustomizationType }
*
*/
public ItemListCustomizationType getSellingSummary() {
return sellingSummary;
}
/**
* Legt den Wert der sellingSummary-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ItemListCustomizationType }
*
*/
public void setSellingSummary(ItemListCustomizationType value) {
this.sellingSummary = value;
}
/**
* Ruft den Wert der hideVariations-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean getHideVariations() {
return hideVariations;
}
/**
* Legt den Wert der hideVariations-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setHideVariations(Boolean value) {
this.hideVariations = value;
}
}
|
gpl-2.0
|
jrmrjnck/okular-tabbed
|
part.cpp
|
93172
|
/***************************************************************************
* Copyright (C) 2002 by Wilco Greven <greven@kde.org> *
* Copyright (C) 2002 by Chris Cheney <ccheney@cheney.cx> *
* Copyright (C) 2002 by Malcolm Hunter <malcolm.hunter@gmx.co.uk> *
* Copyright (C) 2003-2004 by Christophe Devriese *
* <Christophe.Devriese@student.kuleuven.ac.be> *
* Copyright (C) 2003 by Daniel Molkentin <molkentin@kde.org> *
* Copyright (C) 2003 by Andy Goossens <andygoossens@telenet.be> *
* Copyright (C) 2003 by Dirk Mueller <mueller@kde.org> *
* Copyright (C) 2003 by Laurent Montel <montel@kde.org> *
* Copyright (C) 2004 by Dominique Devriese <devriese@kde.org> *
* Copyright (C) 2004 by Christoph Cullmann <crossfire@babylon2k.de> *
* Copyright (C) 2004 by Henrique Pinto <stampede@coltec.ufmg.br> *
* Copyright (C) 2004 by Waldo Bastian <bastian@kde.org> *
* Copyright (C) 2004-2008 by Albert Astals Cid <aacid@kde.org> *
* Copyright (C) 2004 by Antti Markus <antti.markus@starman.ee> *
* *
* 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. *
***************************************************************************/
#include "part.h"
// qt/kde includes
#include <qapplication.h>
#include <qfile.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qtimer.h>
#include <QtGui/QPrinter>
#include <QtGui/QPrintDialog>
#include <QScrollBar>
#include <kvbox.h>
#include <kaboutapplicationdialog.h>
#include <kaction.h>
#include <kactioncollection.h>
#include <kdirwatch.h>
#include <kstandardaction.h>
#include <kpluginfactory.h>
#include <kfiledialog.h>
#include <kinputdialog.h>
#include <kmessagebox.h>
#include <knuminput.h>
#include <kio/netaccess.h>
#include <kmenu.h>
#include <kxmlguiclient.h>
#include <kxmlguifactory.h>
#include <kservicetypetrader.h>
#include <kstandarddirs.h>
#include <kstandardshortcut.h>
#include <ktemporaryfile.h>
#include <ktoggleaction.h>
#include <ktogglefullscreenaction.h>
#include <kio/job.h>
#include <kicon.h>
#include <kfilterdev.h>
#include <kfilterbase.h>
#if 0
#include <knewstuff2/engine.h>
#endif
#include <kdeprintdialog.h>
#include <kprintpreview.h>
#include <kbookmarkmenu.h>
// local includes
#include "aboutdata.h"
#include "extensions.h"
#include "ui/pageview.h"
#include "ui/toc.h"
#include "ui/searchwidget.h"
#include "ui/thumbnaillist.h"
#include "ui/side_reviews.h"
#include "ui/minibar.h"
#include "ui/embeddedfilesdialog.h"
#include "ui/propertiesdialog.h"
#include "ui/presentationwidget.h"
#include "ui/pagesizelabel.h"
#include "ui/bookmarklist.h"
#include "ui/findbar.h"
#include "ui/sidebar.h"
#include "ui/fileprinterpreview.h"
#include "ui/guiutils.h"
#include "conf/preferencesdialog.h"
#include "settings.h"
#include "core/action.h"
#include "core/annotations.h"
#include "core/bookmarkmanager.h"
#include "core/document.h"
#include "core/document_p.h"
#include "core/generator.h"
#include "core/page.h"
#include "core/fileprinter.h"
#include <cstdio>
#include <memory>
class FileKeeper
{
public:
FileKeeper()
: m_handle( NULL )
{
}
~FileKeeper()
{
}
void open( const QString & path )
{
if ( !m_handle )
m_handle = std::fopen( QFile::encodeName( path ), "r" );
}
void close()
{
if ( m_handle )
{
int ret = std::fclose( m_handle );
Q_UNUSED( ret )
m_handle = NULL;
}
}
KTemporaryFile* copyToTemporary() const
{
if ( !m_handle )
return 0;
KTemporaryFile * retFile = new KTemporaryFile;
retFile->open();
std::rewind( m_handle );
int c = -1;
do
{
c = std::fgetc( m_handle );
if ( c == EOF )
break;
if ( !retFile->putChar( (char)c ) )
break;
} while ( !feof( m_handle ) );
retFile->flush();
return retFile;
}
private:
std::FILE * m_handle;
};
Okular::PartFactory::PartFactory()
: KPluginFactory(okularAboutData( "okular", I18N_NOOP( "Okular" ) ))
{
}
Okular::PartFactory::~PartFactory()
{
}
QObject *Okular::PartFactory::create(const char *iface, QWidget *parentWidget, QObject *parent, const QVariantList &args, const QString &keyword)
{
Q_UNUSED ( keyword );
Okular::Part *object = new Okular::Part( parentWidget, parent, args, componentData() );
object->setReadWrite( QLatin1String(iface) == QLatin1String("KParts::ReadWritePart") );
return object;
}
K_EXPORT_PLUGIN( Okular::PartFactory() )
static QAction* actionForExportFormat( const Okular::ExportFormat& format, QObject *parent = 0 )
{
QAction *act = new QAction( format.description(), parent );
if ( !format.icon().isNull() )
{
act->setIcon( format.icon() );
}
return act;
}
static QString compressedMimeFor( const QString& mime_to_check )
{
// The compressedMimeMap is here in case you have a very old shared mime database
// that doesn't have inheritance info for things like gzeps, etc
// Otherwise the "is()" calls below are just good enough
static QHash< QString, QString > compressedMimeMap;
static bool supportBzip = false;
static bool supportXz = false;
const QString app_gzip( QString::fromLatin1( "application/x-gzip" ) );
const QString app_bzip( QString::fromLatin1( "application/x-bzip" ) );
const QString app_xz( QString::fromLatin1( "application/x-xz" ) );
if ( compressedMimeMap.isEmpty() )
{
std::auto_ptr< KFilterBase > f;
compressedMimeMap[ QString::fromLatin1( "image/x-gzeps" ) ] = app_gzip;
// check we can read bzip2-compressed files
f.reset( KFilterBase::findFilterByMimeType( app_bzip ) );
if ( f.get() )
{
supportBzip = true;
compressedMimeMap[ QString::fromLatin1( "application/x-bzpdf" ) ] = app_bzip;
compressedMimeMap[ QString::fromLatin1( "application/x-bzpostscript" ) ] = app_bzip;
compressedMimeMap[ QString::fromLatin1( "application/x-bzdvi" ) ] = app_bzip;
compressedMimeMap[ QString::fromLatin1( "image/x-bzeps" ) ] = app_bzip;
}
// check we can read XZ-compressed files
f.reset( KFilterBase::findFilterByMimeType( app_xz ) );
if ( f.get() )
{
supportXz = true;
}
}
QHash< QString, QString >::const_iterator it = compressedMimeMap.constFind( mime_to_check );
if ( it != compressedMimeMap.constEnd() )
return it.value();
KMimeType::Ptr mime = KMimeType::mimeType( mime_to_check );
if ( mime )
{
if ( mime->is( app_gzip ) )
return app_gzip;
else if ( supportBzip && mime->is( app_bzip ) )
return app_bzip;
else if ( supportXz && mime->is( app_xz ) )
return app_xz;
}
return QString();
}
static Okular::EmbedMode detectEmbedMode( QWidget *parentWidget, QObject *parent, const QVariantList &args )
{
Q_UNUSED( parentWidget );
if ( parent
&& ( parent->objectName() == QLatin1String( "okular::Shell" )
|| parent->objectName() == QLatin1String( "okular/okular__Shell" ) ) )
return Okular::NativeShellMode;
if ( parent
&& ( QByteArray( "KHTMLPart" ) == parent->metaObject()->className() ) )
return Okular::KHTMLPartMode;
Q_FOREACH ( const QVariant &arg, args )
{
if ( arg.type() == QVariant::String )
{
if ( arg.toString() == QLatin1String( "Print/Preview" ) )
{
return Okular::PrintPreviewMode;
}
else if ( arg.toString() == QLatin1String( "ViewerWidget" ) )
{
return Okular::ViewerWidgetMode;
}
}
}
return Okular::UnknownEmbedMode;
}
static QString detectConfigFileName( const QVariantList &args )
{
Q_FOREACH ( const QVariant &arg, args )
{
if ( arg.type() == QVariant::String )
{
QString argString = arg.toString();
int separatorIndex = argString.indexOf( "=" );
if ( separatorIndex >= 0 && argString.left( separatorIndex ) == QLatin1String( "ConfigFileName" ) )
{
return argString.mid( separatorIndex + 1 );
}
}
}
return QString();
}
#undef OKULAR_KEEP_FILE_OPEN
#ifdef OKULAR_KEEP_FILE_OPEN
static bool keepFileOpen()
{
static bool keep_file_open = !qgetenv("OKULAR_NO_KEEP_FILE_OPEN").toInt();
return keep_file_open;
}
#endif
int Okular::Part::numberOfParts = 0;
namespace Okular
{
Part::Part(QWidget *parentWidget,
QObject *parent,
const QVariantList &args,
KComponentData componentData )
: KParts::ReadWritePart(parent),
m_tempfile( 0 ), m_fileWasRemoved( false ), m_showMenuBarAction( 0 ), m_showFullScreenAction( 0 ), m_actionsSearched( false ),
m_cliPresentation(false), m_cliPrint(false), m_embedMode(detectEmbedMode(parentWidget, parent, args)), m_generatorGuiClient(0), m_keeper( 0 )
{
// first, we check if a config file name has been specified
QString configFileName = detectConfigFileName( args );
if ( configFileName.isEmpty() )
{
configFileName = KStandardDirs::locateLocal( "config", "okularpartrc" );
// first necessary step: copy the configuration from kpdf, if available
if ( !QFile::exists( configFileName ) )
{
QString oldkpdfconffile = KStandardDirs::locateLocal( "config", "kpdfpartrc" );
if ( QFile::exists( oldkpdfconffile ) )
QFile::copy( oldkpdfconffile, configFileName );
}
}
Okular::Settings::instance( configFileName );
numberOfParts++;
if (numberOfParts == 1) {
QDBusConnection::sessionBus().registerObject("/okular", this, QDBusConnection::ExportScriptableSlots);
} else {
QDBusConnection::sessionBus().registerObject(QString("/okular%1").arg(numberOfParts), this, QDBusConnection::ExportScriptableSlots);
}
// connect the started signal to tell the job the mimetypes we like,
// and get some more information from it
connect(this, SIGNAL(started(KIO::Job*)), this, SLOT(slotJobStarted(KIO::Job*)));
// connect the completed signal so we can put the window caption when loading remote files
connect(this, SIGNAL(completed()), this, SLOT(setWindowTitleFromDocument()));
connect(this, SIGNAL(canceled(QString)), this, SLOT(loadCancelled(QString)));
// create browser extension (for printing when embedded into browser)
m_bExtension = new BrowserExtension(this);
// create live connect extension (for integrating with browser scripting)
new OkularLiveConnectExtension( this );
// we need an instance
setComponentData( componentData );
GuiUtils::addIconLoader( iconLoader() );
m_sidebar = new Sidebar( parentWidget );
setWidget( m_sidebar );
// build the document
m_document = new Okular::Document(widget());
connect( m_document, SIGNAL(linkFind()), this, SLOT(slotFind()) );
connect( m_document, SIGNAL(linkGoToPage()), this, SLOT(slotGoToPage()) );
connect( m_document, SIGNAL(linkPresentation()), this, SLOT(slotShowPresentation()) );
connect( m_document, SIGNAL(linkEndPresentation()), this, SLOT(slotHidePresentation()) );
connect( m_document, SIGNAL(openUrl(KUrl)), this, SLOT(openUrlFromDocument(KUrl)) );
connect( m_document->bookmarkManager(), SIGNAL(openUrl(KUrl)), this, SLOT(openUrlFromBookmarks(KUrl)) );
connect( m_document, SIGNAL(close()), this, SLOT(close()) );
if ( parent && parent->metaObject()->indexOfSlot( QMetaObject::normalizedSignature( "slotQuit()" ) ) != -1 )
connect( m_document, SIGNAL(quit()), parent, SLOT(slotQuit()) );
else
connect( m_document, SIGNAL(quit()), this, SLOT(cannotQuit()) );
// widgets: ^searchbar (toolbar containing label and SearchWidget)
// m_searchToolBar = new KToolBar( parentWidget, "searchBar" );
// m_searchToolBar->boxLayout()->setSpacing( KDialog::spacingHint() );
// QLabel * sLabel = new QLabel( i18n( "&Search:" ), m_searchToolBar, "kde toolbar widget" );
// m_searchWidget = new SearchWidget( m_searchToolBar, m_document );
// sLabel->setBuddy( m_searchWidget );
// m_searchToolBar->setStretchableWidget( m_searchWidget );
int tbIndex;
// [left toolbox: Table of Contents] | []
m_toc = new TOC( 0, m_document );
connect( m_toc, SIGNAL(hasTOC(bool)), this, SLOT(enableTOC(bool)) );
tbIndex = m_sidebar->addItem( m_toc, KIcon(QApplication::isLeftToRight() ? "format-justify-left" : "format-justify-right"), i18n("Contents") );
enableTOC( false );
// [left toolbox: Thumbnails and Bookmarks] | []
KVBox * thumbsBox = new ThumbnailsBox( 0 );
thumbsBox->setSpacing( 6 );
m_searchWidget = new SearchWidget( thumbsBox, m_document );
m_thumbnailList = new ThumbnailList( thumbsBox, m_document );
// ThumbnailController * m_tc = new ThumbnailController( thumbsBox, m_thumbnailList );
connect( m_thumbnailList, SIGNAL(urlDropped(KUrl)), SLOT(openUrlFromDocument(KUrl)) );
connect( m_thumbnailList, SIGNAL(rightClick(const Okular::Page*,QPoint)), this, SLOT(slotShowMenu(const Okular::Page*,QPoint)) );
tbIndex = m_sidebar->addItem( thumbsBox, KIcon( "view-preview" ), i18n("Thumbnails") );
m_sidebar->setCurrentIndex( tbIndex );
// [left toolbox: Reviews] | []
m_reviewsWidget = new Reviews( 0, m_document );
m_sidebar->addItem( m_reviewsWidget, KIcon("draw-freehand"), i18n("Reviews") );
m_sidebar->setItemEnabled( 2, false );
// [left toolbox: Bookmarks] | []
m_bookmarkList = new BookmarkList( m_document, 0 );
m_sidebar->addItem( m_bookmarkList, KIcon("bookmarks"), i18n("Bookmarks") );
m_sidebar->setItemEnabled( 3, false );
// widgets: [../miniBarContainer] | []
#ifdef OKULAR_ENABLE_MINIBAR
QWidget * miniBarContainer = new QWidget( 0 );
m_sidebar->setBottomWidget( miniBarContainer );
QVBoxLayout * miniBarLayout = new QVBoxLayout( miniBarContainer );
miniBarLayout->setMargin( 0 );
// widgets: [../[spacer/..]] | []
miniBarLayout->addItem( new QSpacerItem( 6, 6, QSizePolicy::Fixed, QSizePolicy::Fixed ) );
// widgets: [../[../MiniBar]] | []
QFrame * bevelContainer = new QFrame( miniBarContainer );
bevelContainer->setFrameStyle( QFrame::StyledPanel | QFrame::Sunken );
QVBoxLayout * bevelContainerLayout = new QVBoxLayout( bevelContainer );
bevelContainerLayout->setMargin( 4 );
m_progressWidget = new ProgressWidget( bevelContainer, m_document );
bevelContainerLayout->addWidget( m_progressWidget );
miniBarLayout->addWidget( bevelContainer );
miniBarLayout->addItem( new QSpacerItem( 6, 6, QSizePolicy::Fixed, QSizePolicy::Fixed ) );
#endif
// widgets: [] | [right 'pageView']
QWidget * rightContainer = new QWidget( 0 );
m_sidebar->setMainWidget( rightContainer );
QVBoxLayout * rightLayout = new QVBoxLayout( rightContainer );
rightLayout->setMargin( 0 );
rightLayout->setSpacing( 0 );
// KToolBar * rtb = new KToolBar( rightContainer, "mainToolBarSS" );
// rightLayout->addWidget( rtb );
m_topMessage = new PageViewTopMessage( rightContainer );
m_topMessage->setup( i18n( "This document has embedded files. <a href=\"okular:/embeddedfiles\">Click here to see them</a> or go to File -> Embedded Files." ), KIcon( "mail-attachment" ) );
connect( m_topMessage, SIGNAL(action()), this, SLOT(slotShowEmbeddedFiles()) );
rightLayout->addWidget( m_topMessage );
m_formsMessage = new PageViewTopMessage( rightContainer );
rightLayout->addWidget( m_formsMessage );
m_pageView = new PageView( rightContainer, m_document );
m_document->d->m_tiledObserver = m_pageView;
QMetaObject::invokeMethod( m_pageView, "setFocus", Qt::QueuedConnection ); //usability setting
// m_splitter->setFocusProxy(m_pageView);
connect( m_pageView, SIGNAL(urlDropped(KUrl)), SLOT(openUrlFromDocument(KUrl)));
connect( m_pageView, SIGNAL(rightClick(const Okular::Page*,QPoint)), this, SLOT(slotShowMenu(const Okular::Page*,QPoint)) );
connect( m_document, SIGNAL(error(QString,int)), m_pageView, SLOT(errorMessage(QString,int)) );
connect( m_document, SIGNAL(warning(QString,int)), m_pageView, SLOT(warningMessage(QString,int)) );
connect( m_document, SIGNAL(notice(QString,int)), m_pageView, SLOT(noticeMessage(QString,int)) );
connect( m_document, SIGNAL(sourceReferenceActivated(const QString&,int,int,bool*)), this, SLOT(slotHandleActivatedSourceReference(const QString&,int,int,bool*)) );
rightLayout->addWidget( m_pageView );
m_findBar = new FindBar( m_document, rightContainer );
rightLayout->addWidget( m_findBar );
m_bottomBar = new QWidget( rightContainer );
QHBoxLayout * bottomBarLayout = new QHBoxLayout( m_bottomBar );
m_pageSizeLabel = new PageSizeLabel( m_bottomBar, m_document );
bottomBarLayout->setMargin( 0 );
bottomBarLayout->setSpacing( 0 );
bottomBarLayout->addWidget( m_pageSizeLabel->antiWidget() );
bottomBarLayout->addItem( new QSpacerItem( 5, 5, QSizePolicy::Expanding, QSizePolicy::Minimum ) );
m_miniBarLogic = new MiniBarLogic( this, m_document );
m_miniBar = new MiniBar( m_bottomBar, m_miniBarLogic );
bottomBarLayout->addWidget( m_miniBar );
bottomBarLayout->addItem( new QSpacerItem( 5, 5, QSizePolicy::Expanding, QSizePolicy::Minimum ) );
bottomBarLayout->addWidget( m_pageSizeLabel );
rightLayout->addWidget( m_bottomBar );
m_pageNumberTool = new MiniBar( 0, m_miniBarLogic );
connect( m_findBar, SIGNAL(forwardKeyPressEvent(QKeyEvent*)), m_pageView, SLOT(externalKeyPressEvent(QKeyEvent*)));
connect( m_miniBar, SIGNAL(forwardKeyPressEvent(QKeyEvent*)), m_pageView, SLOT(externalKeyPressEvent(QKeyEvent*)));
connect( m_pageView, SIGNAL(escPressed()), m_findBar, SLOT(resetSearch()) );
connect( m_pageNumberTool, SIGNAL(forwardKeyPressEvent(QKeyEvent*)), m_pageView, SLOT(externalKeyPressEvent(QKeyEvent*)));
connect( m_reviewsWidget, SIGNAL(openAnnotationWindow(Okular::Annotation*,int)),
m_pageView, SLOT(openAnnotationWindow(Okular::Annotation*,int)) );
// add document observers
m_document->addObserver( this );
m_document->addObserver( m_thumbnailList );
m_document->addObserver( m_pageView );
m_document->registerView( m_pageView );
m_document->addObserver( m_toc );
m_document->addObserver( m_miniBarLogic );
#ifdef OKULAR_ENABLE_MINIBAR
m_document->addObserver( m_progressWidget );
#endif
m_document->addObserver( m_reviewsWidget );
m_document->addObserver( m_pageSizeLabel );
m_document->addObserver( m_bookmarkList );
connect( m_document->bookmarkManager(), SIGNAL(saved()),
this, SLOT(slotRebuildBookmarkMenu()) );
setupViewerActions();
if ( m_embedMode != ViewerWidgetMode )
{
setupActions();
}
else
{
setViewerShortcuts();
}
// document watcher and reloader
m_watcher = new KDirWatch( this );
connect( m_watcher, SIGNAL(dirty(QString)), this, SLOT(slotFileDirty(QString)) );
m_dirtyHandler = new QTimer( this );
m_dirtyHandler->setSingleShot( true );
connect( m_dirtyHandler, SIGNAL(timeout()),this, SLOT(slotDoFileDirty()) );
slotNewConfig();
// keep us informed when the user changes settings
connect( Okular::Settings::self(), SIGNAL(configChanged()), this, SLOT(slotNewConfig()) );
// [SPEECH] check for KTTSD presence and usability
const KService::Ptr kttsd = KService::serviceByDesktopName("kttsd");
Okular::Settings::setUseKTTSD( kttsd );
Okular::Settings::self()->writeConfig();
rebuildBookmarkMenu( false );
if ( m_embedMode == ViewerWidgetMode ) {
// set the XML-UI resource file for the viewer mode
setXMLFile("part-viewermode.rc");
}
else
{
// set our main XML-UI resource file
setXMLFile("part.rc");
}
m_pageView->setupBaseActions( actionCollection() );
m_sidebar->setSidebarVisibility( false );
if ( m_embedMode != PrintPreviewMode )
{
// now set up actions that are required for all remaining modes
m_pageView->setupViewerActions( actionCollection() );
// and if we are not in viewer mode, we want the full GUI
if ( m_embedMode != ViewerWidgetMode )
{
unsetDummyMode();
}
}
// ensure history actions are in the correct state
updateViewActions();
// also update the state of the actions in the page view
m_pageView->updateActionState( false, false, false );
if ( m_embedMode == NativeShellMode )
m_sidebar->setAutoFillBackground( false );
#ifdef OKULAR_KEEP_FILE_OPEN
m_keeper = new FileKeeper();
#endif
}
void Part::setupViewerActions()
{
// ACTIONS
KActionCollection * ac = actionCollection();
// Page Traversal actions
m_gotoPage = KStandardAction::gotoPage( this, SLOT(slotGoToPage()), ac );
m_gotoPage->setShortcut( QKeySequence(Qt::CTRL + Qt::Key_G) );
// dirty way to activate gotopage when pressing miniBar's button
connect( m_miniBar, SIGNAL(gotoPage()), m_gotoPage, SLOT(trigger()) );
connect( m_pageNumberTool, SIGNAL(gotoPage()), m_gotoPage, SLOT(trigger()) );
m_prevPage = KStandardAction::prior(this, SLOT(slotPreviousPage()), ac);
m_prevPage->setIconText( i18nc( "Previous page", "Previous" ) );
m_prevPage->setToolTip( i18n( "Go back to the Previous Page" ) );
m_prevPage->setWhatsThis( i18n( "Moves to the previous page of the document" ) );
m_prevPage->setShortcut( 0 );
// dirty way to activate prev page when pressing miniBar's button
connect( m_miniBar, SIGNAL(prevPage()), m_prevPage, SLOT(trigger()) );
connect( m_pageNumberTool, SIGNAL(prevPage()), m_prevPage, SLOT(trigger()) );
#ifdef OKULAR_ENABLE_MINIBAR
connect( m_progressWidget, SIGNAL(prevPage()), m_prevPage, SLOT(trigger()) );
#endif
m_nextPage = KStandardAction::next(this, SLOT(slotNextPage()), ac );
m_nextPage->setIconText( i18nc( "Next page", "Next" ) );
m_nextPage->setToolTip( i18n( "Advance to the Next Page" ) );
m_nextPage->setWhatsThis( i18n( "Moves to the next page of the document" ) );
m_nextPage->setShortcut( 0 );
// dirty way to activate next page when pressing miniBar's button
connect( m_miniBar, SIGNAL(nextPage()), m_nextPage, SLOT(trigger()) );
connect( m_pageNumberTool, SIGNAL(nextPage()), m_nextPage, SLOT(trigger()) );
#ifdef OKULAR_ENABLE_MINIBAR
connect( m_progressWidget, SIGNAL(nextPage()), m_nextPage, SLOT(trigger()) );
#endif
m_beginningOfDocument = KStandardAction::firstPage( this, SLOT(slotGotoFirst()), ac );
ac->addAction("first_page", m_beginningOfDocument);
m_beginningOfDocument->setText(i18n( "Beginning of the document"));
m_beginningOfDocument->setWhatsThis( i18n( "Moves to the beginning of the document" ) );
m_endOfDocument = KStandardAction::lastPage( this, SLOT(slotGotoLast()), ac );
ac->addAction("last_page",m_endOfDocument);
m_endOfDocument->setText(i18n( "End of the document"));
m_endOfDocument->setWhatsThis( i18n( "Moves to the end of the document" ) );
// we do not want back and next in history in the dummy mode
m_historyBack = 0;
m_historyNext = 0;
m_addBookmark = KStandardAction::addBookmark( this, SLOT(slotAddBookmark()), ac );
m_addBookmarkText = m_addBookmark->text();
m_addBookmarkIcon = m_addBookmark->icon();
m_renameBookmark = ac->addAction("rename_bookmark");
m_renameBookmark->setText(i18n( "Rename Bookmark" ));
m_renameBookmark->setIcon(KIcon( "edit-rename" ));
m_renameBookmark->setWhatsThis( i18n( "Rename the current bookmark" ) );
connect( m_renameBookmark, SIGNAL(triggered()), this, SLOT(slotRenameCurrentViewportBookmark()) );
m_prevBookmark = ac->addAction("previous_bookmark");
m_prevBookmark->setText(i18n( "Previous Bookmark" ));
m_prevBookmark->setIcon(KIcon( "go-up-search" ));
m_prevBookmark->setWhatsThis( i18n( "Go to the previous bookmark" ) );
connect( m_prevBookmark, SIGNAL(triggered()), this, SLOT(slotPreviousBookmark()) );
m_nextBookmark = ac->addAction("next_bookmark");
m_nextBookmark->setText(i18n( "Next Bookmark" ));
m_nextBookmark->setIcon(KIcon( "go-down-search" ));
m_nextBookmark->setWhatsThis( i18n( "Go to the next bookmark" ) );
connect( m_nextBookmark, SIGNAL(triggered()), this, SLOT(slotNextBookmark()) );
m_copy = 0;
m_selectAll = 0;
// Find and other actions
m_find = KStandardAction::find( this, SLOT(slotShowFindBar()), ac );
QList<QKeySequence> s = m_find->shortcuts();
s.append( QKeySequence( Qt::Key_Slash ) );
m_find->setShortcuts( s );
m_find->setEnabled( false );
m_findNext = KStandardAction::findNext( this, SLOT(slotFindNext()), ac);
m_findNext->setEnabled( false );
m_findPrev = KStandardAction::findPrev( this, SLOT(slotFindPrev()), ac );
m_findPrev->setEnabled( false );
m_saveCopyAs = 0;
m_saveAs = 0;
QAction * prefs = KStandardAction::preferences( this, SLOT(slotPreferences()), ac);
if ( m_embedMode == NativeShellMode )
{
prefs->setText( i18n( "Configure Okular..." ) );
}
else
{
// TODO: improve this message
prefs->setText( i18n( "Configure Viewer..." ) );
}
KAction * genPrefs = new KAction( ac );
ac->addAction("options_configure_generators", genPrefs);
if ( m_embedMode == ViewerWidgetMode )
{
genPrefs->setText( i18n( "Configure Viewer Backends..." ) );
}
else
{
genPrefs->setText( i18n( "Configure Backends..." ) );
}
genPrefs->setIcon( KIcon( "configure" ) );
genPrefs->setEnabled( m_document->configurableGenerators() > 0 );
connect( genPrefs, SIGNAL(triggered(bool)), this, SLOT(slotGeneratorPreferences()) );
m_printPreview = KStandardAction::printPreview( this, SLOT(slotPrintPreview()), ac );
m_printPreview->setEnabled( false );
m_showLeftPanel = 0;
m_showBottomBar = 0;
m_showProperties = ac->addAction("properties");
m_showProperties->setText(i18n("&Properties"));
m_showProperties->setIcon(KIcon("document-properties"));
connect(m_showProperties, SIGNAL(triggered()), this, SLOT(slotShowProperties()));
m_showProperties->setEnabled( false );
m_showEmbeddedFiles = 0;
m_showPresentation = 0;
m_exportAs = 0;
m_exportAsMenu = 0;
m_exportAsText = 0;
m_exportAsDocArchive = 0;
m_aboutBackend = ac->addAction("help_about_backend");
m_aboutBackend->setText(i18n("About Backend"));
m_aboutBackend->setEnabled( false );
connect(m_aboutBackend, SIGNAL(triggered()), this, SLOT(slotAboutBackend()));
KAction *reload = ac->add<KAction>( "file_reload" );
reload->setText( i18n( "Reloa&d" ) );
reload->setIcon( KIcon( "view-refresh" ) );
reload->setWhatsThis( i18n( "Reload the current document from disk." ) );
connect( reload, SIGNAL(triggered()), this, SLOT(slotReload()) );
reload->setShortcut( KStandardShortcut::reload() );
m_reload = reload;
m_closeFindBar = ac->addAction( "close_find_bar", this, SLOT(slotHideFindBar()) );
m_closeFindBar->setText( i18n("Close &Find Bar") );
m_closeFindBar->setShortcut( QKeySequence(Qt::Key_Escape) );
m_closeFindBar->setEnabled( false );
KAction *pageno = new KAction( i18n( "Page Number" ), ac );
pageno->setDefaultWidget( m_pageNumberTool );
ac->addAction( "page_number", pageno );
}
void Part::setViewerShortcuts()
{
KActionCollection * ac = actionCollection();
m_gotoPage->setShortcut( QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_G) );
m_find->setShortcuts( QList<QKeySequence>() );
m_findNext->setShortcut( QKeySequence() );
m_findPrev->setShortcut( QKeySequence() );
m_addBookmark->setShortcut( QKeySequence( Qt::CTRL + Qt::ALT + Qt::Key_B ) );
m_beginningOfDocument->setShortcut( QKeySequence( Qt::CTRL + Qt::ALT + Qt::Key_Home ) );
m_endOfDocument->setShortcut( QKeySequence( Qt::CTRL + Qt::ALT + Qt::Key_End ) );
KAction *action = static_cast<KAction*>( ac->action( "file_reload" ) );
if( action ) action->setShortcuts( QList<QKeySequence>() << QKeySequence( Qt::ALT + Qt::Key_F5 ) );
}
void Part::setupActions()
{
KActionCollection * ac = actionCollection();
m_copy = KStandardAction::create( KStandardAction::Copy, m_pageView, SLOT(copyTextSelection()), ac );
m_selectAll = KStandardAction::selectAll( m_pageView, SLOT(selectAll()), ac );
m_saveCopyAs = KStandardAction::saveAs( this, SLOT(slotSaveCopyAs()), ac );
m_saveCopyAs->setText( i18n( "Save &Copy As..." ) );
m_saveCopyAs->setShortcut( KShortcut() );
ac->addAction( "file_save_copy", m_saveCopyAs );
m_saveCopyAs->setEnabled( false );
m_saveAs = KStandardAction::saveAs( this, SLOT(slotSaveFileAs()), ac );
m_saveAs->setEnabled( false );
m_showLeftPanel = ac->add<KToggleAction>("show_leftpanel");
m_showLeftPanel->setText(i18n( "Show &Navigation Panel"));
m_showLeftPanel->setIcon(KIcon( "view-sidetree" ));
connect( m_showLeftPanel, SIGNAL(toggled(bool)), this, SLOT(slotShowLeftPanel()) );
m_showLeftPanel->setShortcut( Qt::Key_F7 );
m_showLeftPanel->setChecked( Okular::Settings::showLeftPanel() );
slotShowLeftPanel();
m_showBottomBar = ac->add<KToggleAction>("show_bottombar");
m_showBottomBar->setText(i18n( "Show &Page Bar"));
connect( m_showBottomBar, SIGNAL(toggled(bool)), this, SLOT(slotShowBottomBar()) );
m_showBottomBar->setChecked( Okular::Settings::showBottomBar() );
slotShowBottomBar();
m_showEmbeddedFiles = ac->addAction("embedded_files");
m_showEmbeddedFiles->setText(i18n("&Embedded Files"));
m_showEmbeddedFiles->setIcon( KIcon( "mail-attachment" ) );
connect(m_showEmbeddedFiles, SIGNAL(triggered()), this, SLOT(slotShowEmbeddedFiles()));
m_showEmbeddedFiles->setEnabled( false );
m_exportAs = ac->addAction("file_export_as");
m_exportAs->setText(i18n("E&xport As"));
m_exportAs->setIcon( KIcon( "document-export" ) );
m_exportAsMenu = new QMenu();
connect(m_exportAsMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotExportAs(QAction*)));
m_exportAs->setMenu( m_exportAsMenu );
m_exportAsText = actionForExportFormat( Okular::ExportFormat::standardFormat( Okular::ExportFormat::PlainText ), m_exportAsMenu );
m_exportAsMenu->addAction( m_exportAsText );
m_exportAs->setEnabled( false );
m_exportAsText->setEnabled( false );
m_exportAsDocArchive = actionForExportFormat( Okular::ExportFormat(
i18nc( "A document format, Okular-specific", "Document Archive" ),
KMimeType::mimeType( "application/vnd.kde.okular-archive" ) ), m_exportAsMenu );
m_exportAsMenu->addAction( m_exportAsDocArchive );
m_exportAsDocArchive->setEnabled( false );
m_showPresentation = ac->addAction("presentation");
m_showPresentation->setText(i18n("P&resentation"));
m_showPresentation->setIcon( KIcon( "view-presentation" ) );
connect(m_showPresentation, SIGNAL(triggered()), this, SLOT(slotShowPresentation()));
m_showPresentation->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_P ) );
m_showPresentation->setEnabled( false );
QAction * importPS = ac->addAction("import_ps");
importPS->setText(i18n("&Import PostScript as PDF..."));
importPS->setIcon(KIcon("document-import"));
connect(importPS, SIGNAL(triggered()), this, SLOT(slotImportPSFile()));
#if 0
QAction * ghns = ac->addAction("get_new_stuff");
ghns->setText(i18n("&Get Books From Internet..."));
ghns->setIcon(KIcon("get-hot-new-stuff"));
connect(ghns, SIGNAL(triggered()), this, SLOT(slotGetNewStuff()));
// TEMP, REMOVE ME!
ghns->setShortcut( Qt::Key_G );
#endif
KToggleAction *blackscreenAction = new KToggleAction( i18n( "Switch Blackscreen Mode" ), ac );
ac->addAction( "switch_blackscreen_mode", blackscreenAction );
blackscreenAction->setShortcut( QKeySequence( Qt::Key_B ) );
blackscreenAction->setIcon( KIcon( "view-presentation" ) );
blackscreenAction->setEnabled( false );
KToggleAction *drawingAction = new KToggleAction( i18n( "Toggle Drawing Mode" ), ac );
ac->addAction( "presentation_drawing_mode", drawingAction );
drawingAction->setIcon( KIcon( "draw-freehand" ) );
drawingAction->setEnabled( false );
KAction *eraseDrawingAction = new KAction( i18n( "Erase Drawings" ), ac );
ac->addAction( "presentation_erase_drawings", eraseDrawingAction );
eraseDrawingAction->setIcon( KIcon( "draw-eraser" ) );
eraseDrawingAction->setEnabled( false );
KAction *configureAnnotations = new KAction( i18n( "Configure Annotations..." ), ac );
ac->addAction( "options_configure_annotations", configureAnnotations );
configureAnnotations->setIcon( KIcon( "configure" ) );
connect(configureAnnotations, SIGNAL(triggered()), this, SLOT(slotAnnotationPreferences()));
}
Part::~Part()
{
GuiUtils::removeIconLoader( iconLoader() );
m_document->removeObserver( this );
if ( m_document->isOpened() )
Part::closeUrl( false );
delete m_toc;
delete m_pageView;
delete m_thumbnailList;
delete m_miniBar;
delete m_pageNumberTool;
delete m_miniBarLogic;
delete m_bottomBar;
#ifdef OKULAR_ENABLE_MINIBAR
delete m_progressWidget;
#endif
delete m_pageSizeLabel;
delete m_reviewsWidget;
delete m_bookmarkList;
delete m_document;
delete m_tempfile;
qDeleteAll( m_bookmarkActions );
delete m_exportAsMenu;
#ifdef OKULAR_KEEP_FILE_OPEN
delete m_keeper;
#endif
}
bool Part::openDocument(const KUrl& url, uint page)
{
Okular::DocumentViewport vp( page - 1 );
vp.rePos.enabled = true;
vp.rePos.normalizedX = 0;
vp.rePos.normalizedY = 0;
vp.rePos.pos = Okular::DocumentViewport::TopLeft;
if ( vp.isValid() )
m_document->setNextDocumentViewport( vp );
return openUrl( url );
}
void Part::startPresentation()
{
m_cliPresentation = true;
}
QStringList Part::supportedMimeTypes() const
{
return m_document->supportedMimeTypes();
}
KUrl Part::realUrl() const
{
if ( !m_realUrl.isEmpty() )
return m_realUrl;
return url();
}
// ViewerInterface
void Part::showSourceLocation(const QString& fileName, int line, int column, bool showGraphically)
{
const QString u = QString( "src:%1 %2" ).arg( line + 1 ).arg( fileName );
GotoAction action( QString(), u );
m_document->processAction( &action );
if( showGraphically )
{
m_pageView->setLastSourceLocationViewport( m_document->viewport() );
}
}
void Part::clearLastShownSourceLocation()
{
m_pageView->clearLastSourceLocationViewport();
}
bool Part::isWatchFileModeEnabled() const
{
return !m_watcher->isStopped();
}
void Part::setWatchFileModeEnabled(bool enabled)
{
if ( enabled && m_watcher->isStopped() )
{
m_watcher->startScan();
}
else if( !enabled && !m_watcher->isStopped() )
{
m_dirtyHandler->stop();
m_watcher->stopScan();
}
}
bool Part::areSourceLocationsShownGraphically() const
{
return m_pageView->areSourceLocationsShownGraphically();
}
void Part::setShowSourceLocationsGraphically(bool show)
{
m_pageView->setShowSourceLocationsGraphically(show);
}
void Part::slotHandleActivatedSourceReference(const QString& absFileName, int line, int col, bool *handled)
{
emit openSourceReference( absFileName, line, col );
if ( m_embedMode == Okular::ViewerWidgetMode )
{
*handled = true;
}
}
void Part::openUrlFromDocument(const KUrl &url)
{
if ( m_embedMode == PrintPreviewMode )
return;
if (KIO::NetAccess::exists(url, KIO::NetAccess::SourceSide, widget()))
{
m_bExtension->openUrlNotify();
m_bExtension->setLocationBarUrl(url.prettyUrl());
openUrl(url);
} else {
KMessageBox::error( widget(), i18n("Could not open '%1'. File does not exist", url.pathOrUrl() ) );
}
}
void Part::openUrlFromBookmarks(const KUrl &_url)
{
KUrl url = _url;
Okular::DocumentViewport vp( _url.htmlRef() );
if ( vp.isValid() )
m_document->setNextDocumentViewport( vp );
url.setHTMLRef( QString() );
if ( m_document->currentDocument() == url )
{
if ( vp.isValid() )
m_document->setViewport( vp );
}
else
openUrl( url );
}
void Part::slotJobStarted(KIO::Job *job)
{
if (job)
{
QStringList supportedMimeTypes = m_document->supportedMimeTypes();
job->addMetaData("accept", supportedMimeTypes.join(", ") + ", */*;q=0.5");
connect(job, SIGNAL(result(KJob*)), this, SLOT(slotJobFinished(KJob*)));
}
}
void Part::slotJobFinished(KJob *job)
{
if ( job->error() == KIO::ERR_USER_CANCELED )
{
m_pageView->noticeMessage( i18n( "The loading of %1 has been canceled.", realUrl().pathOrUrl() ) );
}
}
void Part::loadCancelled(const QString &reason)
{
emit setWindowCaption( QString() );
resetStartArguments();
// when m_viewportDirty.pageNumber != -1 we come from slotDoFileDirty
// so we don't want to show an ugly messagebox just because the document is
// taking more than usual to be recreated
if (m_viewportDirty.pageNumber == -1)
{
if (!reason.isEmpty())
{
KMessageBox::error( widget(), i18n("Could not open %1. Reason: %2", url().prettyUrl(), reason ) );
}
}
}
void Part::setWindowTitleFromDocument()
{
// If 'DocumentTitle' should be used, check if the document has one. If
// either case is false, use the file name.
QString title = Okular::Settings::displayDocumentNameOrPath() == Okular::Settings::EnumDisplayDocumentNameOrPath::Path ? realUrl().pathOrUrl() : realUrl().fileName();
if ( Okular::Settings::displayDocumentTitle() )
{
const QString docTitle = m_document->metaData( "DocumentTitle" ).toString();
if ( !docTitle.isEmpty() && !docTitle.trimmed().isEmpty() )
{
title = docTitle;
}
}
emit setWindowCaption( title );
}
KConfigDialog * Part::slotGeneratorPreferences( )
{
// Create dialog
KConfigDialog * dialog = new KConfigDialog( m_pageView, "generator_prefs", Okular::Settings::self() );
dialog->setAttribute( Qt::WA_DeleteOnClose );
if( m_embedMode == ViewerWidgetMode )
{
dialog->setCaption( i18n( "Configure Viewer Backends" ) );
}
else
{
dialog->setCaption( i18n( "Configure Backends" ) );
}
m_document->fillConfigDialog( dialog );
// Show it
dialog->setWindowModality( Qt::ApplicationModal );
dialog->show();
return dialog;
}
void Part::notifySetup( const QVector< Okular::Page * > & /*pages*/, int setupFlags )
{
if ( !( setupFlags & Okular::DocumentObserver::DocumentChanged ) )
return;
rebuildBookmarkMenu();
updateAboutBackendAction();
m_findBar->resetSearch();
m_searchWidget->setEnabled( m_document->supportsSearching() );
}
void Part::notifyViewportChanged( bool /*smoothMove*/ )
{
updateViewActions();
}
void Part::notifyPageChanged( int page, int flags )
{
if ( flags & Okular::DocumentObserver::NeedSaveAs )
setModified();
if ( !(flags & Okular::DocumentObserver::Bookmark ) )
return;
rebuildBookmarkMenu();
if ( page == m_document->viewport().pageNumber )
updateBookmarksActions();
}
void Part::goToPage(uint i)
{
if ( i <= m_document->pages() )
m_document->setViewportPage( i - 1 );
}
void Part::openDocument( const QString &doc )
{
openUrl( KUrl( doc ) );
}
uint Part::pages()
{
return m_document->pages();
}
uint Part::currentPage()
{
return m_document->pages() ? m_document->currentPage() + 1 : 0;
}
QString Part::currentDocument()
{
return m_document->currentDocument().pathOrUrl();
}
QString Part::documentMetaData( const QString &metaData ) const
{
const Okular::DocumentInfo * info = m_document->documentInfo();
if ( info )
{
QDomElement docElement = info->documentElement();
for ( QDomNode node = docElement.firstChild(); !node.isNull(); node = node.nextSibling() )
{
const QDomElement element = node.toElement();
if ( metaData.compare( element.tagName(), Qt::CaseInsensitive ) == 0 )
return element.attribute( "value" );
}
}
return QString();
}
bool Part::slotImportPSFile()
{
QString app = KStandardDirs::findExe( "ps2pdf" );
if ( app.isEmpty() )
{
// TODO point the user to their distro packages?
KMessageBox::error( widget(), i18n( "The program \"ps2pdf\" was not found, so Okular can not import PS files using it." ), i18n("ps2pdf not found") );
return false;
}
KUrl url = KFileDialog::getOpenUrl( KUrl(), "application/postscript", this->widget() );
if ( url.isLocalFile() )
{
KTemporaryFile tf;
tf.setSuffix( ".pdf" );
tf.setAutoRemove( false );
if ( !tf.open() )
return false;
m_temporaryLocalFile = tf.fileName();
tf.close();
setLocalFilePath( url.toLocalFile() );
QStringList args;
QProcess *p = new QProcess();
args << url.toLocalFile() << m_temporaryLocalFile;
m_pageView->displayMessage(i18n("Importing PS file as PDF (this may take a while)..."));
connect(p, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(psTransformEnded(int,QProcess::ExitStatus)));
p->start(app, args);
return true;
}
m_temporaryLocalFile.clear();
return false;
}
static void addFileToWatcher( KDirWatch *watcher, const QString &filePath)
{
if ( !watcher->contains( filePath ) ) watcher->addFile(filePath);
const QFileInfo fi(filePath);
if ( !watcher->contains( fi.absolutePath() ) ) watcher->addDir(fi.absolutePath());
if ( fi.isSymLink() ) watcher->addFile( fi.readLink() );
}
bool Part::openFile()
{
KMimeType::Ptr mime;
QString fileNameToOpen = localFilePath();
const bool isstdin = url().isLocalFile() && url().fileName( KUrl::ObeyTrailingSlash ) == QLatin1String( "-" );
const QFileInfo fileInfo( fileNameToOpen );
if ( !isstdin && !fileInfo.exists() )
return false;
if ( !arguments().mimeType().isEmpty() )
{
mime = KMimeType::mimeType( arguments().mimeType() );
}
if ( !mime )
{
mime = KMimeType::findByPath( fileNameToOpen );
}
bool isCompressedFile = false;
bool uncompressOk = true;
QString compressedMime = compressedMimeFor( mime->name() );
if ( compressedMime.isEmpty() )
compressedMime = compressedMimeFor( mime->parentMimeType() );
if ( !compressedMime.isEmpty() )
{
isCompressedFile = true;
uncompressOk = handleCompressed( fileNameToOpen, localFilePath(), compressedMime );
mime = KMimeType::findByPath( fileNameToOpen );
}
bool ok = false;
isDocumentArchive = false;
if ( uncompressOk )
{
if ( mime->is( "application/vnd.kde.okular-archive" ) )
{
ok = m_document->openDocumentArchive( fileNameToOpen, url() );
isDocumentArchive = true;
}
else
{
ok = m_document->openDocument( fileNameToOpen, url(), mime );
}
}
bool canSearch = m_document->supportsSearching();
emit mimeTypeChanged( mime );
// update one-time actions
emit enableCloseAction( ok );
m_find->setEnabled( ok && canSearch );
m_findNext->setEnabled( ok && canSearch );
m_findPrev->setEnabled( ok && canSearch );
if( m_saveAs ) m_saveAs->setEnabled( ok && (m_document->canSaveChanges() || isDocumentArchive) );
if( m_saveCopyAs ) m_saveCopyAs->setEnabled( ok );
emit enablePrintAction( ok && m_document->printingSupport() != Okular::Document::NoPrinting );
m_printPreview->setEnabled( ok && m_document->printingSupport() != Okular::Document::NoPrinting );
m_showProperties->setEnabled( ok );
bool hasEmbeddedFiles = ok && m_document->embeddedFiles() && m_document->embeddedFiles()->count() > 0;
if ( m_showEmbeddedFiles ) m_showEmbeddedFiles->setEnabled( hasEmbeddedFiles );
m_topMessage->setVisible( hasEmbeddedFiles && Okular::Settings::showOSD() );
// Warn the user that XFA forms are not supported yet (NOTE: poppler generator only)
if ( ok && m_document->metaData( "HasUnsupportedXfaForm" ).toBool() == true )
{
m_formsMessage->setup( i18n( "This document has XFA forms, which are currently <b>unsupported</b>." ), KIcon( "dialog-warning" ) );
m_formsMessage->setVisible( true );
}
// m_pageView->toggleFormsAction() may be null on dummy mode
else if ( ok && m_pageView->toggleFormsAction() && m_pageView->toggleFormsAction()->isEnabled() )
{
m_formsMessage->setup( i18n( "This document has forms. Click on the button to interact with them, or use View -> Show Forms." ) );
m_formsMessage->setVisible( true );
}
else
{
m_formsMessage->setVisible( false );
}
if ( m_showPresentation ) m_showPresentation->setEnabled( ok );
if ( ok )
{
if ( m_exportAs )
{
m_exportFormats = m_document->exportFormats();
QList<Okular::ExportFormat>::ConstIterator it = m_exportFormats.constBegin();
QList<Okular::ExportFormat>::ConstIterator itEnd = m_exportFormats.constEnd();
QMenu *menu = m_exportAs->menu();
for ( ; it != itEnd; ++it )
{
menu->addAction( actionForExportFormat( *it ) );
}
}
if ( isCompressedFile )
{
m_realUrl = url();
}
#ifdef OKULAR_KEEP_FILE_OPEN
if ( keepFileOpen() )
m_keeper->open( fileNameToOpen );
#endif
}
if ( m_exportAsText ) m_exportAsText->setEnabled( ok && m_document->canExportToText() );
if ( m_exportAsDocArchive ) m_exportAsDocArchive->setEnabled( ok );
if ( m_exportAs ) m_exportAs->setEnabled( ok );
// update viewing actions
updateViewActions();
m_fileWasRemoved = false;
if ( !ok )
{
// if can't open document, update windows so they display blank contents
m_pageView->viewport()->update();
m_thumbnailList->update();
setUrl( KUrl() );
return false;
}
// set the file to the fileWatcher
if ( url().isLocalFile() )
{
addFileToWatcher( m_watcher, localFilePath() );
}
// if the 'OpenTOC' flag is set, open the TOC
if ( m_document->metaData( "OpenTOC" ).toBool() && m_sidebar->isItemEnabled( 0 ) && !m_sidebar->isCollapsed() )
{
m_sidebar->setCurrentIndex( 0, Sidebar::DoNotUncollapseIfCollapsed );
}
// if the 'StartFullScreen' flag is set, or the command line flag was
// specified, start presentation
if ( m_document->metaData( "StartFullScreen" ).toBool() || m_cliPresentation )
{
bool goAheadWithPresentationMode = true;
if ( !m_cliPresentation )
{
const QString text = i18n( "The document requested to be launched in presentation mode.\n"
"Do you want to allow it?" );
const QString caption = i18n( "Presentation Mode" );
const KGuiItem yesItem = KGuiItem( i18n( "Allow" ), "dialog-ok", i18n( "Allow the presentation mode" ) );
const KGuiItem noItem = KGuiItem( i18n( "Do Not Allow" ), "process-stop", i18n( "Do not allow the presentation mode" ) );
const int result = KMessageBox::questionYesNo( widget(), text, caption, yesItem, noItem );
if ( result == KMessageBox::No )
goAheadWithPresentationMode = false;
}
m_cliPresentation = false;
if ( goAheadWithPresentationMode )
QMetaObject::invokeMethod( this, "slotShowPresentation", Qt::QueuedConnection );
}
m_generatorGuiClient = factory() ? m_document->guiClient() : 0;
if ( m_generatorGuiClient )
factory()->addClient( m_generatorGuiClient );
if ( m_cliPrint )
{
m_cliPrint = false;
slotPrint();
}
return true;
}
bool Part::openUrl(const KUrl &_url)
{
// Close current document if any
if ( !closeUrl() )
return false;
KUrl url( _url );
if ( url.hasHTMLRef() )
{
const QString dest = url.htmlRef();
bool ok = true;
const int page = dest.toInt( &ok );
if ( ok )
{
Okular::DocumentViewport vp( page - 1 );
vp.rePos.enabled = true;
vp.rePos.normalizedX = 0;
vp.rePos.normalizedY = 0;
vp.rePos.pos = Okular::DocumentViewport::TopLeft;
m_document->setNextDocumentViewport( vp );
}
else
{
m_document->setNextDocumentDestination( dest );
}
url.setHTMLRef( QString() );
}
// this calls in sequence the 'closeUrl' and 'openFile' methods
bool openOk = KParts::ReadWritePart::openUrl( url );
if ( openOk )
{
m_viewportDirty.pageNumber = -1;
setWindowTitleFromDocument();
}
else
{
resetStartArguments();
KMessageBox::error( widget(), i18n("Could not open %1", url.pathOrUrl() ) );
}
return openOk;
}
bool Part::queryClose()
{
if ( !isReadWrite() || !isModified() )
return true;
const int res = KMessageBox::warningYesNoCancel( widget(),
i18n( "Do you want to save your annotation changes or discard them?" ),
i18n( "Close Document" ),
KStandardGuiItem::saveAs(),
KStandardGuiItem::discard() );
switch ( res )
{
case KMessageBox::Yes: // Save as
slotSaveFileAs();
return !isModified(); // Only allow closing if file was really saved
case KMessageBox::No: // Discard
return true;
default: // Cancel
return false;
}
}
bool Part::closeUrl(bool promptToSave)
{
if ( promptToSave && !queryClose() )
return false;
setModified( false );
if (!m_temporaryLocalFile.isNull() && m_temporaryLocalFile != localFilePath())
{
QFile::remove( m_temporaryLocalFile );
m_temporaryLocalFile.clear();
}
slotHidePresentation();
emit enableCloseAction( false );
m_find->setEnabled( false );
m_findNext->setEnabled( false );
m_findPrev->setEnabled( false );
if( m_saveAs ) m_saveAs->setEnabled( false );
if( m_saveCopyAs ) m_saveCopyAs->setEnabled( false );
m_printPreview->setEnabled( false );
m_showProperties->setEnabled( false );
if ( m_showEmbeddedFiles ) m_showEmbeddedFiles->setEnabled( false );
if ( m_exportAs ) m_exportAs->setEnabled( false );
if ( m_exportAsText ) m_exportAsText->setEnabled( false );
if ( m_exportAsDocArchive ) m_exportAsDocArchive->setEnabled( false );
m_exportFormats.clear();
if ( m_exportAs )
{
QMenu *menu = m_exportAs->menu();
QList<QAction*> acts = menu->actions();
int num = acts.count();
for ( int i = 2; i < num; ++i )
{
menu->removeAction( acts.at(i) );
delete acts.at(i);
}
}
if ( m_showPresentation ) m_showPresentation->setEnabled( false );
emit setWindowCaption("");
emit enablePrintAction(false);
m_realUrl = KUrl();
if ( url().isLocalFile() )
{
m_watcher->removeFile( localFilePath() );
QFileInfo fi(localFilePath());
m_watcher->removeDir( fi.absolutePath() );
if ( fi.isSymLink() ) m_watcher->removeFile( fi.readLink() );
}
m_fileWasRemoved = false;
if ( m_generatorGuiClient )
factory()->removeClient( m_generatorGuiClient );
m_generatorGuiClient = 0;
m_document->closeDocument();
updateViewActions();
delete m_tempfile;
m_tempfile = 0;
if ( widget() )
{
m_searchWidget->clearText();
m_topMessage->setVisible( false );
m_formsMessage->setVisible( false );
}
#ifdef OKULAR_KEEP_FILE_OPEN
m_keeper->close();
#endif
bool r = KParts::ReadWritePart::closeUrl();
setUrl(KUrl());
return r;
}
bool Part::closeUrl()
{
return closeUrl( true );
}
void Part::guiActivateEvent(KParts::GUIActivateEvent *event)
{
updateViewActions();
KParts::ReadWritePart::guiActivateEvent(event);
}
void Part::close()
{
if ( m_embedMode == NativeShellMode )
{
closeUrl();
}
else KMessageBox::information( widget(), i18n( "This link points to a close document action that does not work when using the embedded viewer." ), QString(), "warnNoCloseIfNotInOkular" );
}
void Part::cannotQuit()
{
KMessageBox::information( widget(), i18n( "This link points to a quit application action that does not work when using the embedded viewer." ), QString(), "warnNoQuitIfNotInOkular" );
}
void Part::slotShowLeftPanel()
{
bool showLeft = m_showLeftPanel->isChecked();
Okular::Settings::setShowLeftPanel( showLeft );
Okular::Settings::self()->writeConfig();
// show/hide left panel
m_sidebar->setSidebarVisibility( showLeft );
}
void Part::slotShowBottomBar()
{
const bool showBottom = m_showBottomBar->isChecked();
Okular::Settings::setShowBottomBar( showBottom );
Okular::Settings::self()->writeConfig();
// show/hide bottom bar
m_bottomBar->setVisible( showBottom );
}
void Part::slotFileDirty( const QString& path )
{
// The beauty of this is that each start cancels the previous one.
// This means that timeout() is only fired when there have
// no changes to the file for the last 750 milisecs.
// This ensures that we don't update on every other byte that gets
// written to the file.
if ( path == localFilePath() )
{
// Only start watching the file in case if it wasn't removed
if (QFile::exists(localFilePath()))
m_dirtyHandler->start( 750 );
else
m_fileWasRemoved = true;
}
else
{
const QFileInfo fi(localFilePath());
if ( fi.absolutePath() == path )
{
// Our parent has been dirtified
if (!QFile::exists(localFilePath()))
{
m_fileWasRemoved = true;
}
else if (m_fileWasRemoved && QFile::exists(localFilePath()))
{
// we need to watch the new file
m_watcher->removeFile(localFilePath());
m_watcher->addFile(localFilePath());
m_dirtyHandler->start( 750 );
}
}
else if ( fi.isSymLink() && fi.readLink() == path )
{
if ( QFile::exists( fi.readLink() ))
m_dirtyHandler->start( 750 );
else
m_fileWasRemoved = true;
}
}
}
void Part::slotDoFileDirty()
{
bool tocReloadPrepared = false;
// do the following the first time the file is reloaded
if ( m_viewportDirty.pageNumber == -1 )
{
// store the url of the current document
m_oldUrl = url();
// store the current viewport
m_viewportDirty = m_document->viewport();
// store the current toolbox pane
m_dirtyToolboxIndex = m_sidebar->currentIndex();
m_wasSidebarVisible = m_sidebar->isSidebarVisible();
m_wasSidebarCollapsed = m_sidebar->isCollapsed();
// store if presentation view was open
m_wasPresentationOpen = ((PresentationWidget*)m_presentationWidget != 0);
// preserves the toc state after reload
m_toc->prepareForReload();
tocReloadPrepared = true;
// store the page rotation
m_dirtyPageRotation = m_document->rotation();
// inform the user about the operation in progress
// TODO: Remove this line and integrate reload info in queryClose
m_pageView->displayMessage( i18n("Reloading the document...") );
}
// close and (try to) reopen the document
if ( !closeUrl() )
{
m_viewportDirty.pageNumber = -1;
if ( tocReloadPrepared )
{
m_toc->rollbackReload();
}
return;
}
if ( tocReloadPrepared )
m_toc->finishReload();
// inform the user about the operation in progress
m_pageView->displayMessage( i18n("Reloading the document...") );
if ( KParts::ReadWritePart::openUrl( m_oldUrl ) )
{
// on successful opening, restore the previous viewport
if ( m_viewportDirty.pageNumber >= (int) m_document->pages() )
m_viewportDirty.pageNumber = (int) m_document->pages() - 1;
m_document->setViewport( m_viewportDirty );
m_oldUrl = KUrl();
m_viewportDirty.pageNumber = -1;
m_document->setRotation( m_dirtyPageRotation );
if ( m_sidebar->currentIndex() != m_dirtyToolboxIndex && m_sidebar->isItemEnabled( m_dirtyToolboxIndex )
&& !m_sidebar->isCollapsed() )
{
m_sidebar->setCurrentIndex( m_dirtyToolboxIndex );
}
if ( m_sidebar->isSidebarVisible() != m_wasSidebarVisible )
{
m_sidebar->setSidebarVisibility( m_wasSidebarVisible );
}
if ( m_sidebar->isCollapsed() != m_wasSidebarCollapsed )
{
m_sidebar->setCollapsed( m_wasSidebarCollapsed );
}
if (m_wasPresentationOpen) slotShowPresentation();
emit enablePrintAction(true && m_document->printingSupport() != Okular::Document::NoPrinting);
}
else
{
// start watching the file again (since we dropped it on close)
addFileToWatcher( m_watcher, localFilePath() );
m_dirtyHandler->start( 750 );
}
}
void Part::updateViewActions()
{
bool opened = m_document->pages() > 0;
if ( opened )
{
m_gotoPage->setEnabled( m_document->pages() > 1 );
// Check if you are at the beginning or not
if (m_document->currentPage() != 0)
{
m_beginningOfDocument->setEnabled( true );
m_prevPage->setEnabled( true );
}
else
{
if (m_pageView->verticalScrollBar()->value() != 0)
{
// The page isn't at the very beginning
m_beginningOfDocument->setEnabled( true );
}
else
{
// The page is at the very beginning of the document
m_beginningOfDocument->setEnabled( false );
}
// The document is at the first page, you can go to a page before
m_prevPage->setEnabled( false );
}
if (m_document->pages() == m_document->currentPage() + 1 )
{
// If you are at the end, disable go to next page
m_nextPage->setEnabled( false );
if (m_pageView->verticalScrollBar()->value() == m_pageView->verticalScrollBar()->maximum())
{
// If you are the end of the page of the last document, you can't go to the last page
m_endOfDocument->setEnabled( false );
}
else
{
// Otherwise you can move to the endif
m_endOfDocument->setEnabled( true );
}
}
else
{
// If you are not at the end, enable go to next page
m_nextPage->setEnabled( true );
m_endOfDocument->setEnabled( true );
}
if (m_historyBack) m_historyBack->setEnabled( !m_document->historyAtBegin() );
if (m_historyNext) m_historyNext->setEnabled( !m_document->historyAtEnd() );
m_reload->setEnabled( true );
if (m_copy) m_copy->setEnabled( true );
if (m_selectAll) m_selectAll->setEnabled( true );
}
else
{
m_gotoPage->setEnabled( false );
m_beginningOfDocument->setEnabled( false );
m_endOfDocument->setEnabled( false );
m_prevPage->setEnabled( false );
m_nextPage->setEnabled( false );
if (m_historyBack) m_historyBack->setEnabled( false );
if (m_historyNext) m_historyNext->setEnabled( false );
m_reload->setEnabled( false );
if (m_copy) m_copy->setEnabled( false );
if (m_selectAll) m_selectAll->setEnabled( false );
}
if ( factory() )
{
QWidget *menu = factory()->container("menu_okular_part_viewer", this);
if (menu) menu->setEnabled( opened );
menu = factory()->container("view_orientation", this);
if (menu) menu->setEnabled( opened );
}
emit viewerMenuStateChange( opened );
updateBookmarksActions();
}
void Part::updateBookmarksActions()
{
bool opened = m_document->pages() > 0;
if ( opened )
{
m_addBookmark->setEnabled( true );
if ( m_document->bookmarkManager()->isBookmarked( m_document->viewport() ) )
{
m_addBookmark->setText( i18n( "Remove Bookmark" ) );
m_addBookmark->setIcon( KIcon( "edit-delete-bookmark" ) );
m_renameBookmark->setEnabled( true );
}
else
{
m_addBookmark->setText( m_addBookmarkText );
m_addBookmark->setIcon( m_addBookmarkIcon );
m_renameBookmark->setEnabled( false );
}
}
else
{
m_addBookmark->setEnabled( false );
m_addBookmark->setText( m_addBookmarkText );
m_addBookmark->setIcon( m_addBookmarkIcon );
m_renameBookmark->setEnabled( false );
}
}
void Part::enableTOC(bool enable)
{
m_sidebar->setItemEnabled(0, enable);
// If present, show the TOC when a document is opened
if ( enable )
{
m_sidebar->setCurrentIndex( 0, Sidebar::DoNotUncollapseIfCollapsed );
}
}
void Part::slotRebuildBookmarkMenu()
{
rebuildBookmarkMenu();
}
void Part::slotShowFindBar()
{
m_findBar->show();
m_findBar->focusAndSetCursor();
m_closeFindBar->setEnabled( true );
}
void Part::slotHideFindBar()
{
if ( m_findBar->maybeHide() )
{
m_pageView->setFocus();
m_closeFindBar->setEnabled( false );
}
}
//BEGIN go to page dialog
class GotoPageDialog : public KDialog
{
public:
GotoPageDialog(QWidget *p, int current, int max) : KDialog(p)
{
setCaption(i18n("Go to Page"));
setButtons(Ok | Cancel);
setDefaultButton(Ok);
QWidget *w = new QWidget(this);
setMainWidget(w);
QVBoxLayout *topLayout = new QVBoxLayout(w);
topLayout->setMargin(0);
topLayout->setSpacing(spacingHint());
e1 = new KIntNumInput(current, w);
e1->setRange(1, max);
e1->setEditFocus(true);
e1->setSliderEnabled(true);
QLabel *label = new QLabel(i18n("&Page:"), w);
label->setBuddy(e1);
topLayout->addWidget(label);
topLayout->addWidget(e1);
// A little bit extra space
topLayout->addSpacing(spacingHint());
topLayout->addStretch(10);
e1->setFocus();
}
int getPage() const
{
return e1->value();
}
protected:
KIntNumInput *e1;
};
//END go to page dialog
void Part::slotGoToPage()
{
GotoPageDialog pageDialog( m_pageView, m_document->currentPage() + 1, m_document->pages() );
if ( pageDialog.exec() == QDialog::Accepted )
m_document->setViewportPage( pageDialog.getPage() - 1 );
}
void Part::slotPreviousPage()
{
if ( m_document->isOpened() && !(m_document->currentPage() < 1) )
m_document->setViewportPage( m_document->currentPage() - 1 );
}
void Part::slotNextPage()
{
if ( m_document->isOpened() && m_document->currentPage() < (m_document->pages() - 1) )
m_document->setViewportPage( m_document->currentPage() + 1 );
}
void Part::slotGotoFirst()
{
if ( m_document->isOpened() ) {
m_document->setViewportPage( 0 );
m_beginningOfDocument->setEnabled( false );
}
}
void Part::slotGotoLast()
{
if ( m_document->isOpened() )
{
DocumentViewport endPage(m_document->pages() -1 );
endPage.rePos.enabled = true;
endPage.rePos.normalizedX = 0;
endPage.rePos.normalizedY = 1;
endPage.rePos.pos = Okular::DocumentViewport::TopLeft;
m_document->setViewport(endPage);
m_endOfDocument->setEnabled(false);
}
}
void Part::slotHistoryBack()
{
m_document->setPrevViewport();
}
void Part::slotHistoryNext()
{
m_document->setNextViewport();
}
void Part::slotAddBookmark()
{
DocumentViewport vp = m_document->viewport();
if ( m_document->bookmarkManager()->isBookmarked( vp ) )
{
m_document->bookmarkManager()->removeBookmark( vp );
}
else
{
m_document->bookmarkManager()->addBookmark( vp );
}
}
void Part::slotRenameBookmark( const DocumentViewport &viewport )
{
Q_ASSERT(m_document->bookmarkManager()->isBookmarked( viewport ));
if ( m_document->bookmarkManager()->isBookmarked( viewport ) )
{
KBookmark bookmark = m_document->bookmarkManager()->bookmark( viewport );
const QString newName = KInputDialog::getText( i18n( "Rename Bookmark" ), i18n( "Enter the new name of the bookmark:" ), bookmark.fullText(), 0, widget());
if (!newName.isEmpty())
{
m_document->bookmarkManager()->renameBookmark(&bookmark, newName);
}
}
}
void Part::slotRenameBookmarkFromMenu()
{
QAction *action = dynamic_cast<QAction *>(sender());
Q_ASSERT( action );
if ( action )
{
DocumentViewport vp( action->data().toString() );
slotRenameBookmark( vp );
}
}
void Part::slotRenameCurrentViewportBookmark()
{
slotRenameBookmark( m_document->viewport() );
}
void Part::slotAboutToShowContextMenu(KMenu * /*menu*/, QAction *action, QMenu *contextMenu)
{
const QList<QAction*> actions = contextMenu->findChildren<QAction*>("OkularPrivateRenameBookmarkActions");
foreach(QAction *a, actions)
{
contextMenu->removeAction(a);
delete a;
}
KBookmarkAction *ba = dynamic_cast<KBookmarkAction*>(action);
if (ba != NULL)
{
QAction *separatorAction = contextMenu->addSeparator();
separatorAction->setObjectName("OkularPrivateRenameBookmarkActions");
QAction *renameAction = contextMenu->addAction( KIcon( "edit-rename" ), i18n( "Rename this Bookmark" ), this, SLOT(slotRenameBookmarkFromMenu()) );
renameAction->setData(ba->property("htmlRef").toString());
renameAction->setObjectName("OkularPrivateRenameBookmarkActions");
}
}
void Part::slotPreviousBookmark()
{
const KBookmark bookmark = m_document->bookmarkManager()->previousBookmark( m_document->viewport() );
if ( !bookmark.isNull() )
{
DocumentViewport vp( bookmark.url().htmlRef() );
m_document->setViewport( vp );
}
}
void Part::slotNextBookmark()
{
const KBookmark bookmark = m_document->bookmarkManager()->nextBookmark( m_document->viewport() );
if ( !bookmark.isNull() )
{
DocumentViewport vp( bookmark.url().htmlRef() );
m_document->setViewport( vp );
}
}
void Part::slotFind()
{
// when in presentation mode, there's already a search bar, taking care of
// the 'find' requests
if ( (PresentationWidget*)m_presentationWidget != 0 )
{
m_presentationWidget->slotFind();
}
else
{
slotShowFindBar();
}
}
void Part::slotFindNext()
{
if (m_findBar->isHidden())
slotShowFindBar();
else
m_findBar->findNext();
}
void Part::slotFindPrev()
{
if (m_findBar->isHidden())
slotShowFindBar();
else
m_findBar->findPrev();
}
bool Part::saveFile()
{
kDebug() << "Okular part doesn't support saving the file in the location from which it was opened";
return false;
}
void Part::slotSaveFileAs()
{
if ( m_embedMode == PrintPreviewMode )
return;
/* Show a warning before saving if the generator can't save annotations,
* unless we are going to save a .okular archive. */
if ( !isDocumentArchive && !m_document->canSaveChanges( Document::SaveAnnotationsCapability ) )
{
/* Search local annotations */
bool containsLocalAnnotations = false;
const int pagecount = m_document->pages();
for ( int pageno = 0; pageno < pagecount; ++pageno )
{
const Okular::Page *page = m_document->page( pageno );
foreach ( const Okular::Annotation *ann, page->annotations() )
{
if ( !(ann->flags() & Okular::Annotation::External) )
{
containsLocalAnnotations = true;
break;
}
}
if ( containsLocalAnnotations )
break;
}
/* Don't show it if there are no local annotations */
if ( containsLocalAnnotations )
{
int res = KMessageBox::warningContinueCancel( widget(), i18n("Your annotations will not be exported.\nYou can export the annotated document using File -> Export As -> Document Archive") );
if ( res != KMessageBox::Continue )
return; // Canceled
}
}
KUrl saveUrl = KFileDialog::getSaveUrl( url(),
QString(), widget(), QString(),
KFileDialog::ConfirmOverwrite );
if ( !saveUrl.isValid() || saveUrl.isEmpty() )
return;
saveAs( saveUrl );
}
bool Part::saveAs( const KUrl & saveUrl )
{
KTemporaryFile tf;
QString fileName;
if ( !tf.open() )
{
KMessageBox::information( widget(), i18n("Could not open the temporary file for saving." ) );
return false;
}
fileName = tf.fileName();
tf.close();
QString errorText;
bool saved;
if ( isDocumentArchive )
saved = m_document->saveDocumentArchive( fileName );
else
saved = m_document->saveChanges( fileName, &errorText );
if ( !saved )
{
if (errorText.isEmpty())
{
KMessageBox::information( widget(), i18n("File could not be saved in '%1'. Try to save it to another location.", fileName ) );
}
else
{
KMessageBox::information( widget(), i18n("File could not be saved in '%1'. %2", fileName, errorText ) );
}
return false;
}
KIO::Job *copyJob = KIO::file_copy( fileName, saveUrl, -1, KIO::Overwrite );
if ( !KIO::NetAccess::synchronousRun( copyJob, widget() ) )
{
KMessageBox::information( widget(), i18n("File could not be saved in '%1'. Try to save it to another location.", saveUrl.prettyUrl() ) );
return false;
}
setModified( false );
return true;
}
void Part::slotSaveCopyAs()
{
if ( m_embedMode == PrintPreviewMode )
return;
KUrl saveUrl = KFileDialog::getSaveUrl( KUrl("kfiledialog:///okular/" + url().fileName()),
QString(), widget(), QString(),
KFileDialog::ConfirmOverwrite );
if ( saveUrl.isValid() && !saveUrl.isEmpty() )
{
// make use of the already downloaded (in case of remote URLs) file,
// no point in downloading that again
KUrl srcUrl = KUrl::fromPath( localFilePath() );
KTemporaryFile * tempFile = 0;
// duh, our local file disappeared...
if ( !QFile::exists( localFilePath() ) )
{
if ( url().isLocalFile() )
{
#ifdef OKULAR_KEEP_FILE_OPEN
// local file: try to get it back from the open handle on it
if ( ( tempFile = m_keeper->copyToTemporary() ) )
srcUrl = KUrl::fromPath( tempFile->fileName() );
#else
const QString msg = i18n( "Okular cannot copy %1 to the specified location.\n\nThe document does not exist anymore.", localFilePath() );
KMessageBox::sorry( widget(), msg );
return;
#endif
}
else
{
// we still have the original remote URL of the document,
// so copy the document from there
srcUrl = url();
}
}
KIO::Job *copyJob = KIO::file_copy( srcUrl, saveUrl, -1, KIO::Overwrite );
if ( !KIO::NetAccess::synchronousRun( copyJob, widget() ) )
KMessageBox::information( widget(), i18n("File could not be saved in '%1'. Try to save it to another location.", saveUrl.prettyUrl() ) );
delete tempFile;
}
}
void Part::slotGetNewStuff()
{
#if 0
KNS::Engine engine(widget());
engine.init( "okular.knsrc" );
// show the modal dialog over pageview and execute it
KNS::Entry::List entries = engine.downloadDialogModal( m_pageView );
Q_UNUSED( entries )
#endif
}
void Part::slotPreferences()
{
// Create dialog
PreferencesDialog * dialog = new PreferencesDialog( m_pageView, Okular::Settings::self(), m_embedMode );
dialog->setAttribute( Qt::WA_DeleteOnClose );
// Show it
dialog->show();
}
void Part::slotAnnotationPreferences()
{
// Create dialog
PreferencesDialog * dialog = new PreferencesDialog( m_pageView, Okular::Settings::self(), m_embedMode );
dialog->setAttribute( Qt::WA_DeleteOnClose );
// Show it
dialog->switchToAnnotationsPage();
dialog->show();
}
void Part::slotNewConfig()
{
// Apply settings here. A good policy is to check whether the setting has
// changed before applying changes.
// Watch File
setWatchFileModeEnabled(Okular::Settings::watchFile());
// Main View (pageView)
m_pageView->reparseConfig();
// update document settings
m_document->reparseConfig();
// update TOC settings
if ( m_sidebar->isItemEnabled(0) )
m_toc->reparseConfig();
// update ThumbnailList contents
if ( Okular::Settings::showLeftPanel() && !m_thumbnailList->isHidden() )
m_thumbnailList->updateWidgets();
// update Reviews settings
if ( m_sidebar->isItemEnabled(2) )
m_reviewsWidget->reparseConfig();
setWindowTitleFromDocument ();
}
void Part::slotPrintPreview()
{
if (m_document->pages() == 0) return;
QPrinter printer;
// Native printing supports KPrintPreview, Postscript needs to use FilePrinterPreview
if ( m_document->printingSupport() == Okular::Document::NativePrinting )
{
KPrintPreview previewdlg( &printer, widget() );
setupPrint( printer );
doPrint( printer );
previewdlg.exec();
}
else
{
// Generate a temp filename for Print to File, then release the file so generator can write to it
KTemporaryFile tf;
tf.setAutoRemove( true );
tf.setSuffix( ".ps" );
tf.open();
printer.setOutputFileName( tf.fileName() );
tf.close();
setupPrint( printer );
doPrint( printer );
if ( QFile::exists( printer.outputFileName() ) )
{
Okular::FilePrinterPreview previewdlg( printer.outputFileName(), widget() );
previewdlg.exec();
}
}
}
void Part::slotShowMenu(const Okular::Page *page, const QPoint &point)
{
if ( m_embedMode == PrintPreviewMode )
return;
bool reallyShow = false;
const bool currentPage = page && page->number() == m_document->viewport().pageNumber;
if (!m_actionsSearched)
{
// the quest for options_show_menubar
KActionCollection *ac;
QAction *act;
if (factory())
{
const QList<KXMLGUIClient*> clients(factory()->clients());
for(int i = 0 ; (!m_showMenuBarAction || !m_showFullScreenAction) && i < clients.size(); ++i)
{
ac = clients.at(i)->actionCollection();
// show_menubar
act = ac->action("options_show_menubar");
if (act && qobject_cast<KToggleAction*>(act))
m_showMenuBarAction = qobject_cast<KToggleAction*>(act);
// fullscreen
act = ac->action("fullscreen");
if (act && qobject_cast<KToggleFullScreenAction*>(act))
m_showFullScreenAction = qobject_cast<KToggleFullScreenAction*>(act);
}
}
m_actionsSearched = true;
}
KMenu *popup = new KMenu( widget() );
QAction *addBookmark = 0;
QAction *removeBookmark = 0;
QAction *fitPageWidth = 0;
if (page)
{
popup->addTitle( i18n( "Page %1", page->number() + 1 ) );
if ( ( !currentPage && m_document->bookmarkManager()->isBookmarked( page->number() ) ) ||
( currentPage && m_document->bookmarkManager()->isBookmarked( m_document->viewport() ) ) )
removeBookmark = popup->addAction( KIcon("edit-delete-bookmark"), i18n("Remove Bookmark") );
else
addBookmark = popup->addAction( KIcon("bookmark-new"), i18n("Add Bookmark") );
if ( m_pageView->canFitPageWidth() )
fitPageWidth = popup->addAction( KIcon("zoom-fit-best"), i18n("Fit Width") );
popup->addAction( m_prevBookmark );
popup->addAction( m_nextBookmark );
reallyShow = true;
}
/*
//Albert says: I have not ported this as i don't see it does anything
if ( d->mouseOnRect ) // and rect->objectType() == ObjectRect::Image ...
{
m_popup->insertItem( SmallIcon("document-save"), i18n("Save Image..."), 4 );
m_popup->setItemEnabled( 4, false );
}*/
if ((m_showMenuBarAction && !m_showMenuBarAction->isChecked()) || (m_showFullScreenAction && m_showFullScreenAction->isChecked()))
{
popup->addTitle( i18n( "Tools" ) );
if (m_showMenuBarAction && !m_showMenuBarAction->isChecked()) popup->addAction(m_showMenuBarAction);
if (m_showFullScreenAction && m_showFullScreenAction->isChecked()) popup->addAction(m_showFullScreenAction);
reallyShow = true;
}
if (reallyShow)
{
QAction *res = popup->exec(point);
if (res)
{
if (res == addBookmark)
{
if (currentPage)
m_document->bookmarkManager()->addBookmark( m_document->viewport() );
else
m_document->bookmarkManager()->addBookmark( page->number() );
}
else if (res == removeBookmark)
{
if (currentPage)
m_document->bookmarkManager()->removeBookmark( m_document->viewport() );
else
m_document->bookmarkManager()->removeBookmark( page->number() );
}
else if (res == fitPageWidth)
{
m_pageView->fitPageWidth( page->number() );
}
}
}
delete popup;
}
void Part::slotShowProperties()
{
PropertiesDialog *d = new PropertiesDialog(widget(), m_document);
d->exec();
delete d;
}
void Part::slotShowEmbeddedFiles()
{
EmbeddedFilesDialog *d = new EmbeddedFilesDialog(widget(), m_document);
d->exec();
delete d;
}
void Part::slotShowPresentation()
{
if ( !m_presentationWidget )
{
m_presentationWidget = new PresentationWidget( widget(), m_document, actionCollection() );
}
}
void Part::slotHidePresentation()
{
if ( m_presentationWidget )
delete (PresentationWidget*) m_presentationWidget;
}
void Part::slotTogglePresentation()
{
if ( m_document->isOpened() )
{
if ( !m_presentationWidget )
m_presentationWidget = new PresentationWidget( widget(), m_document, actionCollection() );
else delete (PresentationWidget*) m_presentationWidget;
}
}
void Part::reload()
{
if ( m_document->isOpened() )
{
slotReload();
}
}
void Part::enableStartWithPrint()
{
m_cliPrint = true;
}
void Part::slotAboutBackend()
{
const KComponentData *data = m_document->componentData();
if ( !data )
return;
KAboutData aboutData( *data->aboutData() );
if ( aboutData.programIconName().isEmpty() || aboutData.programIconName() == aboutData.appName() )
{
if ( const Okular::DocumentInfo *documentInfo = m_document->documentInfo() )
{
const QString mimeTypeName = documentInfo->get("mimeType");
if ( !mimeTypeName.isEmpty() )
{
if ( KMimeType::Ptr type = KMimeType::mimeType( mimeTypeName ) )
aboutData.setProgramIconName( type->iconName() );
}
}
}
KAboutApplicationDialog dlg( &aboutData, widget() );
dlg.exec();
}
void Part::slotExportAs(QAction * act)
{
QList<QAction*> acts = m_exportAs->menu() ? m_exportAs->menu()->actions() : QList<QAction*>();
int id = acts.indexOf( act );
if ( ( id < 0 ) || ( id >= acts.count() ) )
return;
QString filter;
switch ( id )
{
case 0:
filter = "text/plain";
break;
case 1:
filter = "application/vnd.kde.okular-archive";
break;
default:
filter = m_exportFormats.at( id - 2 ).mimeType()->name();
break;
}
QString fileName = KFileDialog::getSaveFileName( url().isLocalFile() ? url().directory() : QString(),
filter, widget(), QString(),
KFileDialog::ConfirmOverwrite );
if ( !fileName.isEmpty() )
{
bool saved = false;
switch ( id )
{
case 0:
saved = m_document->exportToText( fileName );
break;
case 1:
saved = m_document->saveDocumentArchive( fileName );
break;
default:
saved = m_document->exportTo( fileName, m_exportFormats.at( id - 2 ) );
break;
}
if ( !saved )
KMessageBox::information( widget(), i18n("File could not be saved in '%1'. Try to save it to another location.", fileName ) );
}
}
void Part::slotReload()
{
// stop the dirty handler timer, otherwise we may conflict with the
// auto-refresh system
m_dirtyHandler->stop();
slotDoFileDirty();
}
void Part::slotPrint()
{
if (m_document->pages() == 0) return;
#ifdef Q_WS_WIN
QPrinter printer(QPrinter::HighResolution);
#else
QPrinter printer;
#endif
QPrintDialog *printDialog = 0;
QWidget *printConfigWidget = 0;
// Must do certain QPrinter setup before creating QPrintDialog
setupPrint( printer );
// Create the Print Dialog with extra config widgets if required
if ( m_document->canConfigurePrinter() )
{
printConfigWidget = m_document->printConfigurationWidget();
}
if ( printConfigWidget )
{
printDialog = KdePrint::createPrintDialog( &printer, QList<QWidget*>() << printConfigWidget, widget() );
}
else
{
printDialog = KdePrint::createPrintDialog( &printer, widget() );
}
if ( printDialog )
{
// Set the available Print Range
printDialog->setMinMax( 1, m_document->pages() );
printDialog->setFromTo( 1, m_document->pages() );
// If the user has bookmarked pages for printing, then enable Selection
if ( !m_document->bookmarkedPageRange().isEmpty() )
{
printDialog->addEnabledOption( QAbstractPrintDialog::PrintSelection );
}
// If the Document type doesn't support print to both PS & PDF then disable the Print Dialog option
if ( printDialog->isOptionEnabled( QAbstractPrintDialog::PrintToFile ) &&
!m_document->supportsPrintToFile() )
{
printDialog->setEnabledOptions( printDialog->enabledOptions() ^ QAbstractPrintDialog::PrintToFile );
}
#if QT_VERSION >= KDE_MAKE_VERSION(4,7,0)
// Enable the Current Page option in the dialog.
if ( m_document->pages() > 1 && currentPage() > 0 )
{
printDialog->setOption( QAbstractPrintDialog::PrintCurrentPage );
}
#endif
if ( printDialog->exec() )
doPrint( printer );
delete printDialog;
}
}
void Part::setupPrint( QPrinter &printer )
{
printer.setOrientation(m_document->orientation());
// title
QString title = m_document->metaData( "DocumentTitle" ).toString();
if ( title.isEmpty() )
{
title = m_document->currentDocument().fileName();
}
if ( !title.isEmpty() )
{
printer.setDocName( title );
}
}
void Part::doPrint(QPrinter &printer)
{
if (!m_document->isAllowed(Okular::AllowPrint))
{
KMessageBox::error(widget(), i18n("Printing this document is not allowed."));
return;
}
if (!m_document->print(printer))
{
const QString error = m_document->printError();
if (error.isEmpty())
{
KMessageBox::error(widget(), i18n("Could not print the document. Unknown error. Please report to bugs.kde.org"));
}
else
{
KMessageBox::error(widget(), i18n("Could not print the document. Detailed error is \"%1\". Please report to bugs.kde.org", error));
}
}
}
void Part::restoreDocument(const KConfigGroup &group)
{
KUrl url ( group.readPathEntry( "URL", QString() ) );
if ( url.isValid() )
{
QString viewport = group.readEntry( "Viewport" );
if (!viewport.isEmpty()) m_document->setNextDocumentViewport( Okular::DocumentViewport( viewport ) );
openUrl( url );
}
}
void Part::saveDocumentRestoreInfo(KConfigGroup &group)
{
group.writePathEntry( "URL", url().url() );
group.writeEntry( "Viewport", m_document->viewport().toString() );
}
void Part::psTransformEnded(int exit, QProcess::ExitStatus status)
{
Q_UNUSED( exit )
if ( status != QProcess::NormalExit )
return;
QProcess *senderobj = sender() ? qobject_cast< QProcess * >( sender() ) : 0;
if ( senderobj )
{
senderobj->close();
senderobj->deleteLater();
}
setLocalFilePath( m_temporaryLocalFile );
openUrl( m_temporaryLocalFile );
m_temporaryLocalFile.clear();
}
void Part::unsetDummyMode()
{
if ( m_embedMode == PrintPreviewMode )
return;
m_sidebar->setItemEnabled( 2, true );
m_sidebar->setItemEnabled( 3, true );
m_sidebar->setSidebarVisibility( Okular::Settings::showLeftPanel() );
// add back and next in history
m_historyBack = KStandardAction::documentBack( this, SLOT(slotHistoryBack()), actionCollection() );
m_historyBack->setWhatsThis( i18n( "Go to the place you were before" ) );
connect(m_pageView, SIGNAL(mouseBackButtonClick()), m_historyBack, SLOT(trigger()));
m_historyNext = KStandardAction::documentForward( this, SLOT(slotHistoryNext()), actionCollection());
m_historyNext->setWhatsThis( i18n( "Go to the place you were after" ) );
connect(m_pageView, SIGNAL(mouseForwardButtonClick()), m_historyNext, SLOT(trigger()));
m_pageView->setupActions( actionCollection() );
// attach the actions of the children widgets too
m_formsMessage->setActionButton( m_pageView->toggleFormsAction() );
// ensure history actions are in the correct state
updateViewActions();
}
bool Part::handleCompressed( QString &destpath, const QString &path, const QString &compressedMimetype )
{
m_tempfile = 0;
// we are working with a compressed file, decompressing
// temporary file for decompressing
KTemporaryFile *newtempfile = new KTemporaryFile();
newtempfile->setAutoRemove(true);
if ( !newtempfile->open() )
{
KMessageBox::error( widget(),
i18n("<qt><strong>File Error!</strong> Could not create temporary file "
"<nobr><strong>%1</strong></nobr>.</qt>",
strerror(newtempfile->error())));
delete newtempfile;
return false;
}
// decompression filer
QIODevice* filterDev = KFilterDev::deviceForFile( path, compressedMimetype );
if (!filterDev)
{
delete newtempfile;
return false;
}
if ( !filterDev->open(QIODevice::ReadOnly) )
{
KMessageBox::detailedError( widget(),
i18n("<qt><strong>File Error!</strong> Could not open the file "
"<nobr><strong>%1</strong></nobr> for uncompression. "
"The file will not be loaded.</qt>", path),
i18n("<qt>This error typically occurs if you do "
"not have enough permissions to read the file. "
"You can check ownership and permissions if you "
"right-click on the file in the Dolphin "
"file manager and then choose the 'Properties' tab.</qt>"));
delete filterDev;
delete newtempfile;
return false;
}
char buf[65536];
int read = 0, wrtn = 0;
while ((read = filterDev->read(buf, sizeof(buf))) > 0)
{
wrtn = newtempfile->write(buf, read);
if ( read != wrtn )
break;
}
delete filterDev;
if ((read != 0) || (newtempfile->size() == 0))
{
KMessageBox::detailedError(widget(),
i18n("<qt><strong>File Error!</strong> Could not uncompress "
"the file <nobr><strong>%1</strong></nobr>. "
"The file will not be loaded.</qt>", path ),
i18n("<qt>This error typically occurs if the file is corrupt. "
"If you want to be sure, try to decompress the file manually "
"using command-line tools.</qt>"));
delete newtempfile;
return false;
}
m_tempfile = newtempfile;
destpath = m_tempfile->fileName();
return true;
}
void Part::rebuildBookmarkMenu( bool unplugActions )
{
if ( unplugActions )
{
unplugActionList( "bookmarks_currentdocument" );
qDeleteAll( m_bookmarkActions );
m_bookmarkActions.clear();
}
KUrl u = m_document->currentDocument();
if ( u.isValid() )
{
m_bookmarkActions = m_document->bookmarkManager()->actionsForUrl( u );
}
bool havebookmarks = true;
if ( m_bookmarkActions.isEmpty() )
{
havebookmarks = false;
QAction * a = new KAction( 0 );
a->setText( i18n( "No Bookmarks" ) );
a->setEnabled( false );
m_bookmarkActions.append( a );
}
plugActionList( "bookmarks_currentdocument", m_bookmarkActions );
if (factory())
{
const QList<KXMLGUIClient*> clients(factory()->clients());
bool containerFound = false;
for (int i = 0; !containerFound && i < clients.size(); ++i)
{
QWidget *container = factory()->container("bookmarks", clients[i]);
if (container && container->actions().contains(m_bookmarkActions.first()))
{
Q_ASSERT(dynamic_cast<KMenu*>(container));
disconnect(container, 0, this, 0);
connect(container, SIGNAL(aboutToShowContextMenu(KMenu*,QAction*,QMenu*)), this, SLOT(slotAboutToShowContextMenu(KMenu*,QAction*,QMenu*)));
containerFound = true;
}
}
}
m_prevBookmark->setEnabled( havebookmarks );
m_nextBookmark->setEnabled( havebookmarks );
}
void Part::updateAboutBackendAction()
{
const KComponentData *data = m_document->componentData();
if ( data )
{
m_aboutBackend->setEnabled( true );
}
else
{
m_aboutBackend->setEnabled( false );
}
}
void Part::resetStartArguments()
{
m_cliPrint = false;
}
void Part::setReadWrite(bool readwrite)
{
m_document->setAnnotationEditingEnabled( readwrite );
ReadWritePart::setReadWrite( readwrite );
}
} // namespace Okular
#include "part.moc"
/* kate: replace-tabs on; indent-width 4; */
|
gpl-2.0
|
ubiquitypress/OJS-Draft-Editorial
|
plugins/reports/timedView/TimedViewReportForm.inc.php
|
7639
|
<?php
/**
* @file plugins/generic/timedView/TimedViewReportForm.inc.php
*
* Copyright (c) 2013 Simon Fraser University Library
* Copyright (c) 2003-2013 John Willinsky
* Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
*
* @class TimedViewReportForm
*/
import('lib.pkp.classes.form.Form');
class TimedViewReportForm extends Form {
/**
* Constructor
*/
function TimedViewReportForm(&$plugin) {
parent::Form($plugin->getTemplatePath() . 'timedViewReportForm.tpl');
// Start date is provided and is valid
$this->addCheck(new FormValidator($this, 'dateStartYear', 'required', 'plugins.reports.timedView.form.dateStartRequired'));
$this->addCheck(new FormValidatorCustom($this, 'dateStartYear', 'required', 'plugins.reports.timedView.form.dateStartValid', create_function('$dateStartYear', '$minYear = date(\'Y\') + TIMED_VIEW_REPORT_YEAR_OFFSET_PAST; $maxYear = date(\'Y\') + TIMED_VIEW_REPORT_YEAR_OFFSET_FUTURE; return ($dateStartYear >= $minYear && $dateStartYear <= $maxYear) ? true : false;')));
$this->addCheck(new FormValidator($this, 'dateStartMonth', 'required', 'plugins.reports.timedView.form.dateStartRequired'));
$this->addCheck(new FormValidatorCustom($this, 'dateStartMonth', 'required', 'plugins.reports.timedView.form.dateStartValid', create_function('$dateStartMonth', 'return ($dateStartMonth >= 1 && $dateStartMonth <= 12) ? true : false;')));
$this->addCheck(new FormValidator($this, 'dateStartDay', 'required', 'plugins.reports.timedView.form.dateStartRequired'));
$this->addCheck(new FormValidatorCustom($this, 'dateStartDay', 'required', 'plugins.reports.timedView.form.dateStartValid', create_function('$dateStartDay', 'return ($dateStartDay >= 1 && $dateStartDay <= 31) ? true : false;')));
// End date is provided and is valid
$this->addCheck(new FormValidator($this, 'dateEndYear', 'required', 'plugins.reports.timedView.form.dateEndRequired'));
$this->addCheck(new FormValidatorCustom($this, 'dateEndYear', 'required', 'plugins.reports.timedView.form.dateEndValid', create_function('$dateEndYear', '$minYear = date(\'Y\') + TIMED_VIEW_REPORT_YEAR_OFFSET_PAST; $maxYear = date(\'Y\') + TIMED_VIEW_REPORT_YEAR_OFFSET_FUTURE; return ($dateEndYear >= $minYear && $dateEndYear <= $maxYear) ? true : false;')));
$this->addCheck(new FormValidator($this, 'dateEndMonth', 'required', 'plugins.reports.timedView.form.dateEndRequired'));
$this->addCheck(new FormValidatorCustom($this, 'dateEndMonth', 'required', 'plugins.reports.timedView.form.dateEndValid', create_function('$dateEndMonth', 'return ($dateEndMonth >= 1 && $dateEndMonth <= 12) ? true : false;')));
$this->addCheck(new FormValidator($this, 'dateEndDay', 'required', 'plugins.reports.timedView.form.dateEndRequired'));
$this->addCheck(new FormValidatorCustom($this, 'dateEndDay', 'required', 'plugins.reports.timedView.form.dateEndValid', create_function('$dateEndDay', 'return ($dateEndDay >= 1 && $dateEndDay <= 31) ? true : false;')));
$this->addCheck(new FormValidatorPost($this));
}
/**
* Display the form.
*/
function display() {
$templateMgr = &TemplateManager::getManager();
$journal = &Request::getJournal();
$templateMgr->assign('yearOffsetPast', TIMED_VIEW_REPORT_YEAR_OFFSET_PAST);
$templateMgr->assign('yearOffsetFuture', TIMED_VIEW_REPORT_YEAR_OFFSET_FUTURE);
parent::display();
}
/**
* Assign form data to user-submitted data.
*/
function readInputData() {
$this->readUserVars(array('dateStartYear', 'dateStartMonth', 'dateStartDay', 'dateEndYear', 'dateEndMonth', 'dateEndDay', 'useTimedViewRecords'));
$this->_data['dateStart'] = date('Ymd', mktime(0, 0, 0, $this->_data['dateStartMonth'], $this->_data['dateStartDay'], $this->_data['dateStartYear']));
$this->_data['dateEnd'] = date('Ymd', mktime(0, 0, 0, $this->_data['dateEndMonth'], $this->_data['dateEndDay'], $this->_data['dateEndYear']));
}
/**
* Save subscription.
*/
function execute() {
$journal =& Request::getJournal();
$journalId = $journal->getId();
$articleData = $galleyLabels = $galleyViews = array();
$issueDao =& DAORegistry::getDAO('IssueDAO');
$publishedArticleDao =& DAORegistry::getDAO('PublishedArticleDAO');
$galleyDao =& DAORegistry::getDAO('ArticleGalleyDAO'); /* @var $galleyDao ArticleGalleyDAO */
$dateStart = $this->getData('dateStart');
$dateEnd = $this->getData('dateEnd');
if ($this->getData('useTimedViewRecords')) {
$metricType = OJS_METRIC_TYPE_TIMED_VIEWS;
} else {
$metricType = OJS_METRIC_TYPE_COUNTER;
}
$metricsDao = DAORegistry::getDAO('MetricsDAO'); /* @var $metricsDao MetricsDAO */
$columns = array(STATISTICS_DIMENSION_ASSOC_ID);
$filter = array(STATISTICS_DIMENSION_ASSOC_TYPE => ASSOC_TYPE_ARTICLE,
STATISTICS_DIMENSION_CONTEXT_ID => $journalId);
if ($dateStart && $dateEnd) {
$filter[STATISTICS_DIMENSION_DAY] = array('from' => $dateStart, 'to' => $dateEnd);
}
$abstractViewCounts = $metricsDao->getMetrics($metricType, $columns, $filter);
foreach ($abstractViewCounts as $row) {
$galleyViewTotal = 0;
$articleId = $row['assoc_id'];
$publishedArticle =& $publishedArticleDao->getPublishedArticleByArticleId($articleId);
if (!$publishedArticle) continue;
$issueId = $publishedArticle->getIssueId();
$issue =& $issueDao->getIssueById($issueId);
$articleData[$articleId] = array(
'id' => $articleId,
'title' => $publishedArticle->getLocalizedTitle(),
'issue' => $issue->getIssueIdentification(),
'datePublished' => $publishedArticle->getDatePublished(),
'totalAbstractViews' => $row['metric']
);
// For each galley, store the label and the count
$columns = array(STATISTICS_DIMENSION_ASSOC_ID);
$filter = array(STATISTICS_DIMENSION_ASSOC_TYPE => ASSOC_TYPE_GALLEY, STATISTICS_DIMENSION_SUBMISSION_ID => $articleId);
if ($dateStart && $dateEnd) {
$filter[STATISTICS_DIMENSION_DAY] = array('from' => $dateStart, 'to' => $dateEnd);
}
$galleyCounts = $metricsDao->getMetrics($metricType, $columns, $filter);
$galleyViews[$articleId] = array();
$galleyViewTotal = 0;
foreach ($galleyCounts as $record) {
$galleyId = $record['assoc_id'];
$galley =& $galleyDao->getGalley($galleyId);
$label = $galley->getLabel();
$i = array_search($label, $galleyLabels);
if ($i === false) {
$i = count($galleyLabels);
$galleyLabels[] = $label;
}
// Make sure the array is the same size as in previous iterations
// so that we insert values into the right location
$galleyViews[$articleId] = array_pad($galleyViews[$articleId], count($galleyLabels), '');
$views = $record['metric'];
$galleyViews[$articleId][$i] = $views;
$galleyViewTotal += $views;
}
$articleData[$articleId]['galleyViews'] = $galleyViewTotal;
// Clean up
unset($row, $galleys);
}
header('content-type: text/comma-separated-values');
header('content-disposition: attachment; filename=report.csv');
$fp = fopen('php://output', 'wt');
$reportColumns = array(
__('plugins.reports.timedView.report.articleId'),
__('plugins.reports.timedView.report.articleTitle'),
__('issue.issue'),
__('plugins.reports.timedView.report.datePublished'),
__('plugins.reports.timedView.report.abstractViews'),
__('plugins.reports.timedView.report.galleyViews'),
);
fputcsv($fp, array_merge($reportColumns, $galleyLabels));
$dateFormatShort = Config::getVar('general', 'date_format_short');
foreach ($articleData as $articleId => $article) {
fputcsv($fp, array_merge($articleData[$articleId], $galleyViews[$articleId]));
}
fclose($fp);
}
}
?>
|
gpl-2.0
|
byrialsen/HA4IoT
|
SDK/HA4IoT.Hardware/Knx/KnxClient.cs
|
4301
|
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using HA4IoT.Contracts.Logging;
using Buffer = Windows.Storage.Streams.Buffer;
namespace HA4IoT.Hardware.Knx
{
public sealed class KnxClient : IDisposable
{
private readonly StreamSocket _socket = new StreamSocket();
private readonly HostName _hostName;
private readonly int _port;
private readonly string _password;
private bool _isConnected;
private bool _isDisposed;
public KnxClient(HostName hostName, int port, string password)
{
if (hostName == null) throw new ArgumentNullException(nameof(hostName));
_hostName = hostName;
_port = port;
_password = password;
_socket.Control.KeepAlive = true;
_socket.Control.NoDelay = true;
}
public int Timeout { get; set; } = 150;
public void Connect()
{
ThrowIfDisposed();
Log.Verbose($"KnxClient: Connecting with {_hostName}...");
var connectTask = _socket.ConnectAsync(_hostName, _port.ToString()).AsTask();
connectTask.ConfigureAwait(false);
if (!connectTask.Wait(Timeout))
{
throw new TimeoutException("Timeout while connecting KNX Client.");
}
_isConnected = true;
Authenticate();
Log.Verbose("KnxClient: Connected");
}
public void SendRequest(string request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
ThrowIfDisposed();
ThrowIfNotConnected();
WriteToSocket(request);
}
public string SendRequestAndWaitForResponse(string request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
ThrowIfDisposed();
ThrowIfNotConnected();
WriteToSocket(request);
return ReadFromSocket();
}
private void Authenticate()
{
Log.Verbose("KnxClient: Authenticating...");
string response = SendRequestAndWaitForResponse($"p={_password}");
ThrowIfNotAuthenticated(response);
}
private void ThrowIfNotAuthenticated(string response)
{
if (!response.Equals("p=ok\x03"))
{
throw new InvalidOperationException("Invalid password specified for KNX client.");
}
}
private void ThrowIfNotConnected()
{
if (!_isConnected)
{
throw new InvalidOperationException("The KNX Client is not connected.");
}
}
private void WriteToSocket(string request)
{
byte[] payload = Encoding.UTF8.GetBytes(request + "\x03");
var writeTask = _socket.OutputStream.WriteAsync(payload.AsBuffer()).AsTask();
writeTask.ConfigureAwait(false);
if (!writeTask.Wait(Timeout))
{
throw new TimeoutException("Timeout while sending KNX Client request.");
}
Log.Verbose($"KnxClient: Sent {request}");
}
private string ReadFromSocket()
{
Log.Verbose("KnxClient: Waiting for response...");
var buffer = new Buffer(64);
var readTask = _socket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial).AsTask();
readTask.ConfigureAwait(false);
if (!readTask.Wait(Timeout))
{
throw new TimeoutException("Timeout while reading KNX Client response.");
}
var response = Encoding.UTF8.GetString(buffer.ToArray());
Log.Verbose($"KnxClient: Received {response}");
return response;
}
private void ThrowIfDisposed()
{
if (_isDisposed) throw new InvalidOperationException("The KNX client is already disposed.");
}
public void Dispose()
{
_isDisposed = true;
_socket.Dispose();
}
}
}
|
gpl-2.0
|
wrbraga/JGrafix
|
src/grafix/graficos/indices/Indice.java
|
8113
|
/*
Copyright (C) 2001-2012, Joao Medeiros, Paulo Vilela (grafix2.com)
Este arquivo é parte do programa Grafix2.com
Grafix2.com é um software livre; você pode redistribui-lo e/ou
modifica-lo dentro dos termos da Licença Pública Geral GNU como
publicada pela Fundação do Software Livre (FSF); na versão 2 da
Licença.
Este programa é distribuido na esperança que possa ser útil,
mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer
MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a
Licença Pública Geral GNU para maiores detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral GNU
junto com este programa, se não, veja uma cópia em
<http://www.gnu.org/licenses/>
*/
package grafix.graficos.indices;
import grafix.graficos.IndiceToolTipGenerator;
import grafix.principal.Acao;
import grafix.telas.JanelaGraficos;
import java.awt.*;
import javax.swing.JOptionPane;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.*;
import org.jfree.data.xy.XYDataset;
import org.jfree.util.ShapeUtilities;
public abstract class Indice {
private int id;
protected String abrevIndice;
private String nomeIndice;
private Color cor;
private int espessura;
private boolean tracoContinuo = true;
private ValoresIndice valores;
private String fileLua;
private String nomeFlag = null;
private boolean flag;
private String nomeParam1 = null;
private int param1;
private String nomeParam2 = null;
private int param2;
private String nomeParam3 = null;
private int param3;
public Indice(int id, String abrev, Color cor, int espessura, boolean f, int p1, int p2, int p3) {
this.setId(id);
if(cor!=null) {
this.cor = cor;
} else {
this.cor = getCorInicial();
}
this.setEspessura(espessura);
this.setAbrevIndice(abrev);
this.configurarIndice();
}
abstract protected void calcularValoresIndice(Acao acao);
abstract protected void configurarIndice();
@Override
public String toString() {
return getAbrevIndice() + " - " + this.getNomeIndice();
}
public ResumoIndice gerarResumo() {
ResumoIndice resultado = new ResumoIndice(this);
return resultado;
}
protected XYDataset getDataSet(JanelaGraficos janela) {
if(valoresEstaoDesatualizados(janela)) {
calcularValoresIndice(janela.getAcao());
}
if(getValores() == null) {
setValores(new ValoresIndice(this, janela.getAcao(), new double[janela.getAcao().getNumeroRegistros()]));
JOptionPane.showMessageDialog(null, "Índice " + this.getNomeIndice() + " não retorna dados!");
}
return getValores().getDataSet(janela);
}
public void plotar(final XYPlot plot, final JanelaGraficos janela, final int contador) {
XYLineAndShapeRenderer indicesRenderer = new XYLineAndShapeRenderer();
indicesRenderer.setSeriesLinesVisible(0, isTracoContinuo());
indicesRenderer.setSeriesShapesVisible(0, !isTracoContinuo());
indicesRenderer.setSeriesShape(0, ShapeUtilities.createDiamond(1.5f));
indicesRenderer.setStroke(new BasicStroke(getEspessura() * 0.5f));
indicesRenderer.setToolTipGenerator(new IndiceToolTipGenerator(this));
indicesRenderer.setPaint(getCor());
plot.setRenderer(contador, indicesRenderer);
plot.setDataset(contador, getDataSet(janela));
}
protected Color getCorInicial() {
return new Color((float)Math.pow(Math.random(),2), (float)Math.pow(Math.random(),2), (float)Math.pow(Math.random(),2));
//return Color.BLACK;
}
public ValoresIndice getValores() {
return valores;
}
public void setValores(ValoresIndice valores) {
this.valores = valores;
}
private boolean valoresEstaoDesatualizados(JanelaGraficos janela) {
if(getValores() == null) {
return true;
}
return !getValores().isAtualizado(janela);
}
public String getTagIndice() {
if(param2!=0) {
return getAbrevIndice() + "-" + param1 + "/" + param2;
} else if(param1!=0) {
return getAbrevIndice() + "-" + param1;
} else {
return getAbrevIndice();
}
}
protected static double[] dadosZerados(int tam) {
double[] resultado = new double[tam];
for (int i = 0; i < resultado.length; i++) {
resultado[i] = ValoresIndice.SEM_VALOR;
}
return resultado;
}
public String getNomeIndice() {
return nomeIndice;
}
public void setNomeIndice(String nomeIndice) {
this.nomeIndice = nomeIndice;
}
public Color getCor() {
return cor;
}
public void setCor(Color cor) {
this.cor = cor;
}
public boolean isTracoContinuo() {
return tracoContinuo;
}
public void setTracoContinuo(boolean tracoContinuo) {
this.tracoContinuo = tracoContinuo;
}
public String getFileLua() {
return fileLua;
}
public void setFileLua(String fileLua) {
this.fileLua = fileLua;
}
// abstract public String definirAbrevIndice();
public String getAbrevIndice() {
// if(abrevIndice == null) {
// abrevIndice = definirAbrevIndice();
// }
return abrevIndice;
}
public void setAbrevIndice(String abrevIndice) {
this.abrevIndice = abrevIndice;
}
// PARAMETROS --------------------------------------------------------------------------
protected void criarFlag(String nome, boolean f) {
setNomeFlag(nome);
setFlag(f);
}
protected void criarParam1(String nome, int p) {
setNomeParam1(nome);
setParam1(p);
}
protected void criarParam2(String nome, int p) {
setNomeParam2(nome);
setParam2(p);
}
protected void criarParam3(String nome, int p) {
setNomeParam3(nome);
setParam3(p);
}
public String getNomeFlag() {
return nomeFlag;
}
public void setNomeFlag(String nomeFlag) {
this.nomeFlag = nomeFlag;
}
public boolean isFlag() {
return flag;
}
public boolean getFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String getNomeParam1() {
return nomeParam1;
}
public void setNomeParam1(String nomeParam1) {
this.nomeParam1 = nomeParam1;
}
public int getParam1() {
return param1;
}
public void setParam1(int param1) {
this.param1 = param1;
}
public String getNomeParam2() {
return nomeParam2;
}
public void setNomeParam2(String nomeParam2) {
this.nomeParam2 = nomeParam2;
}
public int getParam2() {
return param2;
}
public void setParam2(int param2) {
this.param2 = param2;
}
public String getNomeParam3() {
return nomeParam3;
}
public void setNomeParam3(String nomeParam3) {
this.nomeParam3 = nomeParam3;
}
public int getParam3() {
return param3;
}
public void setParam3(int param3) {
this.param3 = param3;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEspessura() {
return espessura;
}
public void setEspessura(int espessura) {
this.espessura = espessura;
}
}
|
gpl-2.0
|
tier5/lakemeawaybj
|
wp-content/plugins/VRPConnector-master/themes/mountainsunset/vrpComplexes.php
|
672
|
<?php
/**
* [vrpComplexes] ShortCode view
*/
foreach($data as $complex) { ?>
<div class="row">
<div class="row">
<h2>
<a href="/vrp/complex/<?php echo esc_attr($complex->page_slug); ?>">
<?php echo esc_html($complex->name); ?>
</a>
</h2>
</div>
<div class="row">
<div class="col-md-4">
<img src="<?php echo esc_url($complex->Photo); ?>" style="width:100%">
</div>
<div class="col-md-8">
<?php echo wp_kses_post($complex->shortdescription); ?>
</div>
</div>
</div>
<?php
}
|
gpl-2.0
|
ulearn/spanishblogwp
|
wp-content/themes/shift/includes/widgets/widget-custom-page.php
|
2251
|
<?php
add_action('widgets_init', create_function('', 'return register_widget("stag_custom_page");'));
class stag_custom_page extends WP_Widget{
function stag_custom_page(){
$widget_ops = array('classname' => 'section-block', 'description' => __('Display content from an specific page.', 'stag'));
$control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'stag_custom_page');
$this->WP_Widget('stag_custom_page', __('Custom Page', 'stag'), $widget_ops, $control_ops);
}
function widget($args, $instance){
extract($args);
// VARS FROM WIDGET SETTINGS
$page = $instance['page'];
echo $before_widget;
$the_page = get_page($page);
?>
<!-- BEGIN .hentry -->
<article id="<?php echo $the_page->ID; ?>" class="">
<?php
echo $before_title.$the_page->post_title.$after_title;
echo '<div class="entry-content">'.apply_filters('the_content', $the_page->post_content).'</div>';
?>
<!-- END .hentry -->
</article>
<?php
echo $after_widget;
}
function update($new_instance, $old_instance){
$instance = $old_instance;
// STRIP TAGS TO REMOVE HTML
$instance['page'] = strip_tags($new_instance['page']);
return $instance;
}
function form($instance){
$defaults = array(
/* Deafult options goes here */
'page' => 0,
);
$instance = wp_parse_args((array) $instance, $defaults);
/* HERE GOES THE FORM */
?>
<p>
<label for="<?php echo $this->get_field_id('page'); ?>"><?php _e('Select Page:', 'stag'); ?></label>
<select id="<?php echo $this->get_field_id( 'page' ); ?>" name="<?php echo $this->get_field_name( 'page' ); ?>" class="widefat">
<?php
$args = array(
'sort_order' => 'ASC',
'sort_column' => 'post_title',
);
$pages = get_pages($args);
foreach($pages as $paged){ ?>
<option value="<?php echo $paged->ID; ?>" <?php if($instance['page'] == $paged->ID) echo "selected"; ?>><?php echo $paged->post_title; ?></option>
<?php }
?>
</select>
<span class="description"><?php _e('This page will be used to display content.', 'stag'); ?></span>
</p>
<?php
}
}
?>
|
gpl-2.0
|
Petermck8806/FunTeamEasterEggHunt
|
FunTeamEasterEggHunt/Question.cs
|
1037
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunTeamEasterEggHunt
{
public class Question
{
public string QuestionImage { get; set; }
public string QuestionPrompt { get; set; }
public string Answer { get; set; }
public bool isAnswered = false;
public int SortOrder;
public Question()
{
QuestionImage = "";
QuestionPrompt = "";
Answer = "";
isAnswered = false;
}
public Question(string questionImage, string questionPrompt, string answer, int sortOrder)
{
this.QuestionImage = questionImage;
this.QuestionPrompt = questionPrompt;
this.Answer = answer;
this.isAnswered = false;
this.SortOrder = sortOrder;
}
public bool isAnswerCorrect(string answer)
{
return isAnswered = answer.Equals(this.Answer);
}
}
}
|
gpl-2.0
|
niloc132/mauve-gwt
|
src/main/java/gnu/testlet/java/lang/UnsupportedClassVersionError/classInfo/getName.java
|
1735
|
// Test for method java.lang.UnsupportedClassVersionError.getClass().getName()
// Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com>
// This file is part of Mauve.
// Mauve 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, or (at your option)
// any later version.
// Mauve 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 Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street,
// Fifth Floor, Boston, MA 02110-1301 USA.
// Tags: JDK1.5
package gnu.testlet.java.lang.UnsupportedClassVersionError.classInfo;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import java.lang.UnsupportedClassVersionError;
/**
* Test for method java.lang.UnsupportedClassVersionError.getClass().getName()
*/
public class getName implements Testlet
{
/**
* Runs the test using the specified harness.
*
* @param harness the test harness (<code>null</code> not permitted).
*/
public void test(TestHarness harness)
{
// create instance of a class UnsupportedClassVersionError
final Object o = new UnsupportedClassVersionError("UnsupportedClassVersionError");
// get a runtime class of an object "o"
final Class c = o.getClass();
harness.check(c.getName(), "java.lang.UnsupportedClassVersionError");
}
}
|
gpl-2.0
|
nopticon/jcg
|
administrator/components/com_claroforms/tables/game.php
|
1505
|
<?php
/**
* Claroforms Model for Claroforms Component
*
* @package Claroforms
* @subpackage com_claroforms
* @license GNU/GPL v2
*
* Created with Marco's Component Creator for Joomla! 1.5
* http://www.mmleoni.net/joomla-component-builder
*
*/
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
/**
* Claroforms Table
*
* @package Joomla.Components
* @subpackage Claroforms
*/
class TableGame extends JTable{
/** jcb code */
/**
* Primary Key
*
* @var int
*/
var $idGame = null;
/**
*
* @var string
*/
var $name = null;
/**
*
* @var datetime
*/
var $creationDate = null;
/**
*
* @var datetime
*/
var $activationDate = null;
/**
*
* @var datetime
*/
var $expirationDate = null;
/**
*
* @var string
*/
var $description = null;
/**
*
* @var string
*/
var $creationIp = null;
/**
*
* @var string
*/
var $expirationIp = null;
/**
*
* @var int
*/
var $idStatus = null;
/**
*
* @var int
*/
var $idFileFlash = null;
/**
*
* @var int
*/
var $idFilePreview = null;
/**
*
* @var int
*/
var $idFileThumbnail = null;
/** jcb code */
/**
* Constructor
*
* @param object Database connector object
*/
function TableGame(& $db){
parent::__construct('game', 'idGame', $db);
}
function check(){
// write here data validation code
return parent::check();
}
}
|
gpl-2.0
|
JulieKuehl/voices
|
footer.php
|
571
|
<?php
/**
* The template for displaying the footer.
*
* Contains the closing of the #content div and all content after
*
* @package areavoices
*/
?>
</div><!-- #content -->
<footer id="colophon" class="site-footer" role="contentinfo">
<div class="copyright">
<?php printf( esc_html__( '© Copyright ', 'areavoices' )); ?><?php echo date( 'Y' ); ?> <?php echo bloginfo( 'name' ); ?> | <a href="http://areavoices.com/">Area Voices</a>
</div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
|
gpl-2.0
|
xh4zr/fence-app
|
app/src/build/app.js
|
13046
|
var app = angular.module('fenceProject',[]);
var mainCtrl = app.controller('mainCtrl',['$scope','api', function ($scope, api) {
window.debug = $scope;
$scope.api = api;
//Set up
var drawLayer = document.getElementById("layer1");
var saveLayer = document.getElementById("layer2");
var gridLayer = document.getElementById("layer3");
var draw = drawLayer.getContext("2d");
var save = saveLayer.getContext("2d");
var grid = gridLayer.getContext("2d");
//Determine size of canvas
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (w < 800) {
$scope.small = true;
}
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
draw.canvas.width = w * .75; //offset - just trial and error
draw.canvas.height = h*.75;
save.canvas.width = draw.canvas.width;
save.canvas.height = draw.canvas.height;
grid.canvas.width = draw.canvas.width;
grid.canvas.height = draw.canvas.height;
$scope.canvasHeight = draw.canvas.height;
//The good stuff
$scope.allow = true;
$scope.sections = [];
var line = {start:null, mid:null, end:null, length:null, gate: false, showDialog: true};
$scope.handleClick = function(e) {
if (!$scope.allow)
return;
e.preventDefault();
var pos = $scope.resources.getClickPos(e);
var snap = $scope.resources.snap(pos);
if (snap != -1) {
pos = snap;
}
if (!line.start) {
line.start = pos;
}
else {
line.end = pos;
line.mid = $scope.resources.getMidPts(line);
if ($scope.sections.length >= 1)
line.length = $scope.length;
//Don't draw lines that are smaller than 10 px
if (!(Math.sqrt(Math.pow((line.end.x - line.start.x),2) + Math.pow((line.end.y - line.start.y),2)) < 10)) {
$scope.sections.push(line);
$scope.allow = false;
draw.clearRect(0, 0, drawLayer.width, drawLayer.height);
$scope.resources.draw(line, save, '#000000');
}
line = {start:null, mid:null, end:null, length:null, gate: false, showDialog: true};
}
};
$scope.scale = 1;
$scope.dist = 0;
$scope.length = 0;
function distance(start, end) {
return Math.sqrt(Math.pow(end.y - start.y, 2) + Math.pow(end.x - start.x, 2));
}
$scope.handleMove = function(e) {
e.preventDefault();
draw.clearRect(0, 0, drawLayer.width, drawLayer.height);
if (line.start) {
line.end = $scope.resources.getClickPos(e);
$scope.resources.draw(line, draw, '#000000');
//Scaling stuff
line.mid = $scope.resources.getMidPts(line);
$scope.dist = distance(line.start, line.end);
$scope.length = Math.round($scope.dist * $scope.scale);
if ($scope.sections.length >= 1)
$scope.resources.drawText(line, $scope.length, false, draw);
}
var snap = $scope.resources.snap($scope.resources.getClickPos(e));
if (snap != -1) {
$scope.resources.drawSnap(snap);
}
//New feature draw dotted line when x or y match
//$scope.resources.checkGrid
};
$scope.error = false;
$scope.errorMsg;
$scope.removeDialog = function(index, length, gate) {
if (length > 10 && gate) {
$scope.errorMsg = "Gate length must be less than 10";
$scope.error = true;
return;
}
if (length < 0) {
$scope.errorMsg = "Only positive numbers are valid";
$scope.error = true;
return;
}
$scope.sections[index].showDialog = false;
$scope.resources.drawText($scope.sections[index], $scope.sections[index].length);
$scope.error = false;
$scope.allow = true;
// var obj = {};
// angular.copy($scope.sections[index], obj);
// $scope.scaledSections.push(obj);
if ($scope.sections.length == 1)
$scope.scale = length / $scope.dist;
};
$scope.resources = {
getClickPos: function(e) {
var canvas = drawLayer.getBoundingClientRect();
//Offset based on canvas position
x = e.clientX - canvas.left;
y = e.clientY - canvas.top;
return {x: x, y: y};
},
snap: function(pos) {
if ($scope.sections && $scope.sections.length > 0) {
for (var i in $scope.sections) {
if (Math.abs($scope.sections[i].start.x - pos.x) <= 10 &&
Math.abs($scope.sections[i].start.y - pos.y) <= 10) {
return $scope.sections[i].start;
} else if (Math.abs($scope.sections[i].end.x - pos.x) <= 10 &&
Math.abs($scope.sections[i].end.y - pos.y) <= 10) {
return $scope.sections[i].end;
} else if (Math.abs($scope.sections[i].mid.x - pos.x) <= 10 &&
Math.abs($scope.sections[i].mid.y - pos.y) <= 10) {
return $scope.sections[i].mid;
}
}
}
return -1;
},
drawSnap: function(pos) {
draw.beginPath();
draw.lineWidth = 1;
draw.arc(pos.x,pos.y,10,0,2*Math.PI);
draw.stroke();
},
drawGrid: function(save) {
var h = save.canvas.height;
var w = save.canvas.width;
for (var i = 0; i < save.canvas.height; i=i+10) {
$scope.resources.draw({start:{x:0,y:i},end:{x:w,y:i}},save, '#f1f1f1',1);
}
for (var i = 0; i < save.canvas.width; i=i+10) {
$scope.resources.draw({start:{x:i,y:0},end:{x:i,y:h}},save, '#f1f1f1',1);
}
},
getMidPts: function(line) {
var x = line.end.x - line.start.x;
x = x/2;
x = line.start.x + x;
var y = line.end.y - line.start.y;
y = y/2;
y = line.start.y + y;
return {x: x, y: y};
},
draw: function(line, layer, color, width) {
layer.strokeStyle = color;
layer.lineWidth = (width)?width:3;
layer.beginPath();
layer.moveTo(line.start.x,line.start.y);
layer.lineTo(line.end.x,line.end.y);
layer.stroke();
},
undo: function() {
if ($scope.sections.length > 0) {
var section = $scope.sections.pop();
$scope.resources.draw(section, save, '#ffffff',2);
$scope.resources.drawText(section, null, true);
}
},
drawText: function(line, value, erase, layer) {
var x;
var y;
var s = (line.end.y - line.start.y)/(line.end.x - line.start.x);
var pos = line.mid;
if (s < 0 && s > -30) {
x = pos.x + 5;
y = pos.y + 5;
}
else if (s > 0 && s < 30) {
x = pos.x - 5;
y = pos.y - 5;
}
else if (s == 0) {
x = pos.x;
y = pos.y - 5;
}
else if (Math.abs(s) > 30 || s == Number.POSITIVE_INFINITY || s == Number.NEGATIVE_INFINITY) {
x = pos.x + 3;
y = pos.y;
}
if (erase){
save.strokeStyle = '#FFFFFF';
save.beginPath();
save.arc(x,y,10,0,2*Math.PI);
save.fillStyle = '#FFFFFF';
save.fill();
save.stroke();
} else {
if (layer)
layer.fillText(Number(value), x, y);
else
save.fillText(Number(value), x, y);
}
},
submitCanvas: function() {
window.location.href = '#discover';
if ($scope.sections.length > 0) {
$scope.resources.submitted = true;
}
if ($scope.selected) {
$scope.calculateMaterials();
}
},
clearCanvas: function() {
draw.clearRect(0, 0, drawLayer.width, drawLayer.height);
save.clearRect(0, 0, drawLayer.width, drawLayer.height);
line = {start:null, mid:null, end:null, length:null, gate: false, showDialog: true};
$scope.sections.length = 0;
//$scope.resources.drawGrid(save);
},
submitted: false
};
//Selecting
$scope.selected;
$scope.selectedStyle;
$scope.selectedHeight = {};
$scope.selectedColor;
$scope.select = function(data) {
$scope.selected = data;
$scope.selectedColor = (data.colors.length > 0)?data.colors[0]:null;
$scope.selectedStyle = (data.styles.length > 0)?data.styles[0]:null;
$scope.selectedHeight = (data.sizes.length > 0)?data.sizes[1]:null;
}
$scope.selectColor = function(color) {
$scope.selectedColor = color;
}
$scope.selectHeight = function(height) {
$scope.selectedHeight = height;
}
$scope.selectStyle = function(style) {
$scope.selectedStyle = style;
}
$scope.materials = {};
$scope.$watch('selected', function(newValue, oldValue) {
if (newValue) {
$scope.materials.components = newValue.sectionComponents;
//$scope.materials.gates = newValue.gate;
if ($scope.resources.submitted) {
$scope.calculateMaterials();
}
}
});
$scope.calculateMaterials = function() {
var posts = [];
var lgates = 0;
var sgates = 0;
var sectLen = $scope.selectedHeight.length;
var fenceSects = 0;
var postLen = 0;
var totalLen = 0;
var remainder = 0;
for (var i in $scope.sections) {
if (posts.indexOf($scope.sections[i].start) == -1) {
posts.push($scope.sections[i].start);
}
if (posts.indexOf($scope.sections[i].end) == -1) {
posts.push($scope.sections[i].end);
}
if ($scope.sections[i].gate) {
if (Number($scope.sections[i].length) <= 4)
sgates++;
else
lgates++;
}
else {
totalLen += Number($scope.sections[i].length);
//remainder += Number($scope.sections[i].length % sectLen);
fenceSects += Math.ceil(Number($scope.sections[i].length / sectLen));
postLen += Math.ceil(Number($scope.sections[i].length / sectLen) - 1)
}
}
$scope.materials.posts = posts.length + postLen;
$scope.materials.sections = fenceSects; //+ Math.ceil(remainder/sectLen);
$scope.materials.totalLength = totalLen;
for (var k in $scope.materials.components) {
if ($scope.materials.components[k].name == '6\' Pickets') {
if (Number($scope.selectedHeight.name.substr(0,1)) == 3)
$scope.materials.components[k].value = Math.ceil($scope.selected.ppf * totalLen / 2);
else
$scope.materials.components[k].value = Math.ceil($scope.selected.ppf * totalLen);
}
else
$scope.materials.components[k].value *= $scope.materials.sections;
}
$scope.materials.gates = [];
if (lgates > 0) {
for (var j in $scope.selected.gate.large) {
$scope.materials.gates.push({name:$scope.selected.gate.large[j].name, value:$scope.selected.gate.large[j].value * lgates});
}
} else if (sgates > 0) {
for (var j in $scope.selected.gate.small) {
$scope.materials.gates.push({name:$scope.selected.gate.small[j].name, value:$scope.selected.gate.small[j].value * sgates});
}
}
window.location.href = '#discover';
};
$scope.resources.drawGrid(grid);
}]);
app.factory('api', function(){
var factory = {};
factory.data = [{
name:'Trex Composite',
icon:'img/Small-Trex.jpg',
colors: [{name:'Saddle',src:'img/saddle.png'}, {name:'Winchester Grey',src:'img/wgrey.png'}, {name:'Woodland Brown',src:'img/wb.png'}],
sizes: [{name:'3 foot',length:8}, {name:'6 foot',length:8}],
styles: ['Flat Top'],
sectionComponents: [{
name:'6\' Pickets',
value:19
},{
name:'8\' Top Rail',
value:1
},{
name:'8\' Bottom Rail',
value:2
},{
name:'8\' Aluminum Bottom Rail Insert',
value:1
},{
name:'8\' Top Rail',
value:1
},{
name:'Brackets',
value:4
}],
ppf:2.375,
gate: {
small:[{
name:'Steel Post Insert',
value:1
},{
name:'Gate Hardware',
value:1
},{
name:'Gate Panel (Standard)',
value:1
}],
large:[{
name:'Steel Post Insert',
value:1
},{
name:'Gate Hardware',
value:1
},{
name:'Gate Panel (Large)',
value:1
}]
}
},{
name:'Fortress Iron',
icon:'img/Small-Fortress.jpg',
colors: [{name:'Black',src:'img/black.jpg'}],
sizes: [{name:'4 foot',length:8}, {name:'6 foot',length:8}],
styles: ['Spear Top', 'Flat Top', 'Extended Top'],
sectionComponents: [{
name:'8\' Panel',
value:1
},{
name:'Brackets',
value:4
}],
gate: {
small:[{
name:'Gate Hardware',
value:1
},{
name:'Gate Panel (Standard)',
value:1
}],large:[{
name:'Gate Hardware',
value:1
},{
name:'Gate Panel (Large)',
value:1
}]
}
},{
name:'Cedar Wood',
icon:'img/Small-Cedar.jpg',
colors: [{name:'No Color Options'}],
sizes: [{name:'3 foot',length:8}, {name:'6 foot',length:8}],
styles: ['Flat Top', 'Dog Ear'],
sectionComponents: [{
name:'6\' Pickets',
value:16
},{
name:'2x4x8\' Rail',
value:2
},{
name:'Brackets',
value:4
}],
ppf:2.1,
gate: {
small:[{
name:'6\' Pickets',
value:8
},{
name:'2x4x8\' Rail',
value:1
},{
name:'Gate Hardware',
value:1
}],
large:[{
name:'6\' Pickets',
value:16
},{
name:'2x4x8\' Rail',
value:3
},{
name:'Gate Hardware',
value:1
}]
}
},{
name:'SimTek Composite',
icon:'img/Small-Simtek.jpg',
colors: [{name:'White'}, {name:'Grey'}, {name:'Black'}, {name:'Red'}],
sizes: [{name:'3 foot',length:6}, {name:'4 foot',length:8}, {name:'6 foot',length:6}],
styles: ['No Style Options'],
sectionComponents: [{
name:'6\' Panel',
value:1
},{
name:'Brackets',
value:4
}],
gate: {
small:[{
name:'Steel Gate Post',
value:1
},{
name:'Gate Hardware',
value:1
},{
name:'Gate Panel (Standard)',
value:1
}],
large:[{
name:'Steel Gate Post',
value:1
},{
name:'Gate Hardware',
value:1
},{
name:'Gate Panel (Large)',
value:1
}]
}
}
];
return factory;
});
|
gpl-2.0
|
Multigaming/WoW434
|
src/server/scripts/EasternKingdoms/Scholomance/boss_illucia_barov.cpp
|
3706
|
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.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, see <http://www.gnu.org/licenses/>.
*/
/*
Name: Boss_Illucia_Barov
%Complete: 100
Comment:
Category: Scholomance
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "scholomance.h"
enum Spells
{
SPELL_CURSEOFAGONY = 34794,
SPELL_SHADOWSHOCK = 34799,
SPELL_SILENCE = 34803,
SPELL_FEAR = 34803
};
enum Events
{
EVENT_CURSEOFAGONY = 1,
EVENT_SHADOWSHOCK = 2,
EVENT_SILENCE = 3,
EVENT_FEAR = 4
};
class boss_illucia_barov : public CreatureScript
{
public: boss_illucia_barov() : CreatureScript("boss_illucia_barov") { }
struct boss_illuciabarovAI : public BossAI
{
boss_illuciabarovAI(Creature* creature) : BossAI(creature,DATA_LADYILLUCIABAROV) {}
void Reset() {}
void JustDied(Unit* /*killer*/)
{
if (instance)
instance->SetData(DATA_LADYILLUCIABAROV, DONE);
}
void EnterCombat(Unit* /*who*/)
{
events.ScheduleEvent(EVENT_CURSEOFAGONY, 18000);
events.ScheduleEvent(EVENT_SHADOWSHOCK, 9000);
events.ScheduleEvent(EVENT_SILENCE, 5000);
events.ScheduleEvent(EVENT_FEAR, 30000);
}
void UpdateAI(uint32 const diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CURSEOFAGONY:
DoCastVictim(SPELL_CURSEOFAGONY, true);
events.ScheduleEvent(EVENT_CURSEOFAGONY, 30000);
break;
case EVENT_SHADOWSHOCK:
DoCast(SelectTarget(SELECT_TARGET_RANDOM,0, 100, true),SPELL_SHADOWSHOCK,true);
events.ScheduleEvent(EVENT_SHADOWSHOCK, 12000);
break;
case EVENT_SILENCE:
DoCastVictim(SPELL_SILENCE, true);
events.ScheduleEvent(EVENT_SILENCE, 14000);
break;
case EVENT_FEAR:
DoCastVictim(SPELL_FEAR, true);
events.ScheduleEvent(EVENT_FEAR, 30000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_illuciabarovAI (creature);
}
};
void AddSC_boss_illuciabarov()
{
new boss_illucia_barov();
}
|
gpl-2.0
|
BitCoding/BitCore-PHP
|
src/Core/Traits/InstanceConfig.php
|
6699
|
<?php
/**
* BitCore-PHP: Rapid Development Framework (https://phpcore.bitcoding.eu)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @link https://phpcore.bitcoding.eu BitCore-PHP Project
* @since 0.7.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Bit\Core\Traits;
use Bit\Core\Exception\Exception;
use Bit\Utility\Hash;
/**
* A trait for reading and writing instance config
*
* Implementing objects are expected to declare a `$_defaultConfig` property.
*/
trait InstanceConfig
{
/**
* Runtime config
*
* @var array
*/
protected $_config = [];
/**
* Whether the config property has already been configured with defaults
*
* @var bool
*/
protected $_configInitialized = false;
/**
* ### Usage
*
* Reading the whole config:
*
* ```
* $this->config();
* ```
*
* Reading a specific value:
*
* ```
* $this->config('key');
* ```
*
* Reading a nested value:
*
* ```
* $this->config('some.nested.key');
* ```
*
* Setting a specific value:
*
* ```
* $this->config('key', $value);
* ```
*
* Setting a nested value:
*
* ```
* $this->config('some.nested.key', $value);
* ```
*
* Updating multiple config settings at the same time:
*
* ```
* $this->config(['one' => 'value', 'another' => 'value']);
* ```
*
* @param string|array|null $key The key to get/set, or a complete array of configs.
* @param mixed|null $value The value to set.
* @param bool $merge Whether to recursively merge or overwrite existing config, defaults to true.
* @return mixed Config value being read, or the object itself on write operations.
* @throws \Bit\Core\Exception\Exception When trying to set a key that is invalid.
*/
public function config($key = null, $value = null, $merge = true)
{
if (!$this->_configInitialized) {
$this->_config = $this->_defaultConfig;
$this->_configInitialized = true;
}
if (is_array($key) || func_num_args() >= 2) {
$this->_configWrite($key, $value, $merge);
return $this;
}
return $this->_configRead($key);
}
/**
* Merge provided config with existing config. Unlike `config()` which does
* a recursive merge for nested keys, this method does a simple merge.
*
* Setting a specific value:
*
* ```
* $this->config('key', $value);
* ```
*
* Setting a nested value:
*
* ```
* $this->config('some.nested.key', $value);
* ```
*
* Updating multiple config settings at the same time:
*
* ```
* $this->config(['one' => 'value', 'another' => 'value']);
* ```
*
* @param string|array $key The key to set, or a complete array of configs.
* @param mixed|null $value The value to set.
* @return $this The object itself.
*/
public function configShallow($key, $value = null)
{
if (!$this->_configInitialized) {
$this->_config = $this->_defaultConfig;
$this->_configInitialized = true;
}
$this->_configWrite($key, $value, 'shallow');
return $this;
}
/**
* Read a config variable
*
* @param string|null $key Key to read.
* @return mixed
*/
protected function _configRead($key)
{
if ($key === null) {
return $this->_config;
}
if (strpos($key, '.') === false) {
return isset($this->_config[$key]) ? $this->_config[$key] : null;
}
$return = $this->_config;
foreach (explode('.', $key) as $k) {
if (!is_array($return) || !isset($return[$k])) {
$return = null;
break;
}
$return = $return[$k];
}
return $return;
}
/**
* Write a config variable
*
* @param string|array $key Key to write to.
* @param mixed $value Value to write.
* @param bool|string $merge True to merge recursively, 'shallow' for simple merge,
* false to overwrite, defaults to false.
* @return void
* @throws \Bit\Core\Exception\Exception if attempting to clobber existing config
*/
protected function _configWrite($key, $value, $merge = false)
{
if (is_string($key) && $value === null) {
$this->_configDelete($key);
return;
}
if ($merge) {
$update = is_array($key) ? $key : [$key => $value];
if ($merge === 'shallow') {
$this->_config = array_merge($this->_config, Hash::expand($update));
} else {
$this->_config = Hash::merge($this->_config, Hash::expand($update));
}
return;
}
if (is_array($key)) {
foreach ($key as $k => $val) {
$this->_configWrite($k, $val);
}
return;
}
if (strpos($key, '.') === false) {
$this->_config[$key] = $value;
return;
}
$update =& $this->_config;
$stack = explode('.', $key);
foreach ($stack as $k) {
if (!is_array($update)) {
throw new Exception(sprintf('Cannot set %s value', $key));
}
if (!isset($update[$k])) {
$update[$k] = [];
}
$update =& $update[$k];
}
$update = $value;
}
/**
* Delete a single config key
*
* @param string $key Key to delete.
* @return void
* @throws \Bit\Core\Exception\Exception if attempting to clobber existing config
*/
protected function _configDelete($key)
{
if (strpos($key, '.') === false) {
unset($this->_config[$key]);
return;
}
$update =& $this->_config;
$stack = explode('.', $key);
$length = count($stack);
foreach ($stack as $i => $k) {
if (!is_array($update)) {
throw new Exception(sprintf('Cannot unset %s value', $key));
}
if (!isset($update[$k])) {
break;
}
if ($i === $length - 1) {
unset($update[$k]);
break;
}
$update =& $update[$k];
}
}
}
|
gpl-2.0
|
pranavladkat/3dVPM
|
examples/post_process_wind_turbine.py
|
6025
|
"""
post process wind turbine Cp data
"""
import csv
import math
import matplotlib.pyplot as plt
def normalize_x(x):
minimum = min(x)
x = [i+abs(minimum) for i in x]
maximum = max(x)
for i in range(0,len(x),1):
x[i] = (x[i]) / maximum
return x
def main():
with open('pressure_data.csv','rb') as csvfile:
file_data = csv.reader(csvfile)
data = list(file_data)
data = data[1:]
x = []
y = []
z = []
cp = []
for i in range(0,len(data),1):
x.append(data[i][0])
y.append(data[i][1])
z.append(data[i][2])
cp.append(data[i][3])
x_30 = []
cp_30 = []
for i in range(0,len(z),1):
if float(z[i]) > 1.45 and float(z[i]) < 1.6 :
x_30.append(float(x[i])/0.711)
cp_30.append(float(cp[i]))
x_30 = normalize_x(x_30)
# experimental data
xu_30 = [ 1, 0.8, 0.68, 0.56, 0.36, 0.2, 0.1, 0.06, 0.04, 0.02, 0.01, 0.005, 0, 0, 0.005, 0.01, 0.02, 0.06, 0.14, 0.28, 0.44, 0.68, 0.92, 1]
cpu_30 = [ 0.167175, -0.006089, -0.16294, -0.466726, -0.969941, -1.134659, -1.220121, -1.430707, -1.626495, -1.815081, -1.780514, -2.114277, -2.752586, -2.752586, 0.576019, 0.918158, 1, 0.855112, 0.506722, -0.008466, -0.223934, 0.172738, 0.292909, 0.167175]
plt.figure()
plt.plot(x_30,cp_30,'r-',marker='v',label='panel method')
plt.plot(xu_30,cpu_30,'bo',label='NREL Expt')
plt.ylim([-3,2])
plt.legend(loc=1)
plt.xlabel('x/c')
plt.ylabel('Cp')
plt.title('30% span, U = 7 m/s')
plt.gca().invert_yaxis()
#plt.show()
plt.savefig('cp_7ms_30.eps')
plt.close()
x_47 = []
cp_47 = []
for i in range(0,len(z),1):
if float(z[i]) > 2.2 and float(z[i]) < 2.4 :
x_47.append(float(x[i])/0.627)
cp_47.append(float(cp[i]))
x_47 = normalize_x(x_47)
# experimental data
xu_47 = [0, 0.005, 0.01, 0.02, 0.06, 0.14, 0.28, 0.44, 0.68, 0.92, 1,
1, 0.8, 0.68, 0.56, 0.36, 0.2, 0.1, 0.06, 0.04, 0.02, 0.01, 0.005, 0]
cpu_47 = [-2.575825, 0.332103, 0.829754, 1, 0.852922, 0.496046, -0.019364, -0.195252, 0.179667, 0.307379, 0.102799,
0.102799, -0.047678, -0.204188, -0.466682, -1.053567, -1.288154, -1.469653, -1.655028, -1.843953, -2.274761, -2.467014, -2.321913, -2.575825]
plt.figure()
plt.plot(x_47,cp_47,'r-',marker='v',label='panel method')
plt.plot(xu_47,cpu_47,'bo',label='NREL Expt')
plt.ylim([-3,2])
plt.gca().invert_yaxis()
plt.legend(loc=1)
plt.xlabel('x/c')
plt.ylabel('Cp')
plt.title('47% span, U = 7 m/s')
#plt.show()
plt.savefig('cp_7ms_47.eps')
plt.close()
x_63 = []
cp_63 = []
for i in range(0,len(z),1):
if float(z[i]) > 3.2 and float(z[i]) < 3.25 :
x_63.append(float(x[i])/0.543)
cp_63.append(float(cp[i]))
x_63 = normalize_x(x_63)
# experimental data
xu_63 = [0, 0.005, 0.01, 0.02, 0.06, 0.14, 0.28, 0.44, 0.68, 0.92, 1,
1, 0.8, 0.68, 0.56, 0.36, 0.2, 0.1, 0.06, 0.04, 0.02, 0.01, 0.005, 0]
cpu_63 = [-1.919118, 0.663699, 0.953923, 1, 0.792005, 0.402968, -0.091503, -0.278885, 0.182597, 0.352175, 0.174389,
0.174389, -0.058211, -0.259285, -0.605071, -1.068455, -1.229872, -1.365889, -1.512394, -1.724331, -1.915798, -1.995034, -1.840502, -1.919118]
plt.figure()
plt.plot(x_63,cp_63,'r-',marker='v',label='panel method')
plt.plot(xu_63,cpu_63,'bo',label='NREL Expt')
plt.ylim([-3,2])
plt.gca().invert_yaxis()
plt.legend(loc=1)
plt.xlabel('x/c')
plt.ylabel('Cp')
plt.title('63% span, U = 7 m/s')
#plt.show()
plt.savefig('cp_7ms_63.eps')
plt.close()
x_80 = []
cp_80 = []
for i in range(0,len(z),1):
if float(z[i]) > 3.8 and float(z[i]) < 4.1 :
x_80.append(float(x[i])/0.457)
cp_80.append(float(cp[i]))
x_80 = normalize_x(x_80)
# experimental data
xu_80 = [ 0, 0.005, 0.01, 0.02, 0.06, 0.14, 0.28, 0.44, 0.68, 0.92, 1,
1, 0.8, 0.68, 0.56, 0.36, 0.2, 0.1, 0.06, 0.04, 0.02, 0.01, 0.005, 0]
cpu_80 = [-1.460808, 0.814826, 1, 0.981287, 0.724081, 0.3118, -0.160666, -0.348032, 0.126752, 0.346738, 0.211074,
0.211074, -0.068508, -0.255429, -0.596876, -1.079419, -1.13962, -1.241882, -1.286436, -1.385176, -1.591168, -1.71867, -1.55582, -1.460808]
plt.figure()
plt.plot(x_80,cp_80,'r-',marker='v',label='panel method')
plt.plot(xu_80,cpu_80,'bo',label='NREL Expt')
plt.ylim([-3,2])
plt.gca().invert_yaxis()
plt.legend(loc=1)
plt.xlabel('x/c')
plt.ylabel('Cp')
plt.title('80% span, U = 7 m/s')
#plt.show()
plt.savefig('cp_7ms_80.eps')
plt.close()
x_95 = []
cp_95 = []
for i in range(0,len(z),1):
if float(z[i]) > 4.9 :
x_95.append(float(x[i])/0.358)
cp_95.append(float(cp[i]))
x_95 = normalize_x(x_95)
# experimental data
xu_95 = [0, 0.005, 0.01, 0.02, 0.06, 0.14, 0.28, 0.44, 0.68, 0.92, 1,
1, 0.8, 0.68, 0.56, 0.36, 0.2, 0.1, 0.06, 0.04, 0.02, 0.01, 0.005, 0]
cpu_95 = [-0.469789, 0.916363, 1, 0.906636, 0.591274, 0.197514, -0.342239, -0.479616, 0.107823, 0.312772, 0.22502,
0.22502, -0.031503, -0.184658, -0.390161, -0.838815, -0.874251, -0.942373, -0.988781, -1.066789, -1.132228, -0.998347, -0.722063, -0.469789]
plt.figure()
plt.plot(x_95,cp_95,'r-',marker='v',label='panel method')
plt.plot(xu_95,cpu_95,'bo',label='NREL Expt')
plt.ylim([-3,2])
plt.gca().invert_yaxis()
plt.legend(loc=1)
plt.xlabel('x/c')
plt.ylabel('Cp')
plt.title('95% span, U = 7 m/s')
#plt.show()
plt.savefig('cp_7ms_95.eps')
plt.close()
if __name__ == "__main__":
main()
|
gpl-2.0
|
FRCHumans4501/Trusspasser
|
src/org/firsthumans/trusspasser/util/VisionListener.java
|
520
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.firsthumans.trusspasser.util;
/**
*
* @author Humans
*/
public interface VisionListener {
public void onVisionProcessed(boolean hot,
float distance,
int vertCenterX,
int vertCenterY,
int horizCenterX,
int horizCenterY);
}
|
gpl-2.0
|
1nv4d3r5/eshop
|
system/core/Controller.php
|
1592
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc.
* @license http://ellislab.com/codeigniter/user_guide/license.html
* @link http://ellislab.com/codeigniter
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Application Controller Class
*
* This class object is the super class that every library in
* CodeIgniter will be assigned to.
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author ExpressionEngine Dev Team
* @link http://ellislab.com/codeigniter/user_guide/general/controllers.html
*/
class CI_Controller {
private static $instance;
/**
* Constructor
*/
public function __construct()
{
self::$instance =& $this;
// Assign all the class objects that were instantiated by the
// bootstrap file (CodeIgniter.php) to local class variables
// so that CI can run as one big super object.
foreach (is_loaded() as $var => $class)
{
$this->$var =& load_class($class);
}
$this->load =& load_class('Loader', 'core');
$this->load->initialize();
log_message('debug', "Controller Class Initialized");
}
public static function &get_instance()
{
return self::$instance;
}
}
// END Controller class
/* End of file Controller.php */
/* Location: ./system/core/Controller.php */
|
gpl-2.0
|
reversetrex/infotectraing-pantheon
|
sites/all/modules/custom/infotec/classes/dmanager/dman.php
|
22664
|
<?php
namespace infotec {
use ecpi\dbc;
/**
* @package infotec module
* @subpackage data manager class
* @version 1.0
* @author gbellucci (ECPI University)
* @copyright (c) 2015 ECPI University
* @license Proprietary
* @abstract
*
* This class is responsible for converting sql data objects and data arrays received from sql requests into html tags or
* text used by the web site. This is a collection of formatting routines. Each formatting function handles a specific
* requirement.
*/
class dman {
/**
* @var \ecpi\dbc - logging class
*/
private $dbg;
/**
* @var object - configuration object
*/
private $cfg;
// constructor
function __construct($configFile) {
$this->cfg = new \ecpi\cfgObj($configFile);
$this->dbg = new \ecpi\dbc('dataManager');
$this->dbg->set_debug((intval($this->cfg->get('dman.debug'), 10)));
}
/**
* Shortform options formatter. This routine expects an array of data records. Each record contains:
*
* [<index>] => stdClass Object
* (
* [GroupName] => A (sub) group name
* [CategoryName] => A category name
* [CourseNumber] => A course identifier
* [CourseWebName] => Name of the course
* [DeliveryMethodName] => The Group this sub group belongs to
* )
* This function produces options for a select tag. Each option belongs to a delivery method group and sub group.
* Classes are applied to each option allowing the short-form javascript to control which option groups are displayed
* in the select tag. Selection visibility is determined by the user's group and sub group selections in the form.
*
* The value for each option is the URL for the web site's course page. The URL is constructed as:
*
* //courses/<DeliveryMethodName>/<CourseNumber/<CourseWebName>/
*
* @param $data - array of data records from sql query
* @param $type - string
*
* @return string - html tags
*/
public function sfOptionsFormat($data, $type='url') {
$dbg = new dbc('sort');
$courseList = array();
extract($data);
// sprintf formats
$optFormat = '<option class="%s" value="%s">%s</option>';
$grpFormat = '<option value="%s">%s</option>';
$methodList = $categoryList = $courses = $methodFilter = $categoryFilter = array();
$methodName = $categoryName = '';
$tmp1 = $tmp2 = array();
// begin by sorting into delivery methods
for($idx = 0; $idx < count($courseList); $idx++) {
$r = $courseList[$idx];
$tmp1[$r->DeliveryMethodName][] = array(
'category' => $r->CategoryName,
'name' => $r->CourseWebName,
'id' => $r->CourseNumber
);
}
// sort delivery methods into categories
foreach($tmp1 as $deliveryMethod => $group) {
for($idx = 0; $idx < count($group); $idx++) {
$rec = $group[$idx];
$tmp2[$deliveryMethod][$rec['category']][] = array(
'name' => $rec['name'],
'id' => $rec['id'],
'class' => $this->sanitize_title_with_dashes("{$deliveryMethod}-{$rec['category']}")
);
}
}
//$dbg->log_entry('method/category', $tmp2);
// for each delivery method
foreach($tmp2 as $deliveryMethod => $category) {
$methodName = $this->sanitize_title_with_dashes($deliveryMethod);
if(!in_array($deliveryMethod, $methodFilter)) {
$methodFilter[] = $deliveryMethod;
//'<option value="%s">%s</option>';
$methodList[] = sprintf($grpFormat, $methodName, $deliveryMethod);
}
// reset the category filter - do this because other delivery methods have
// the same categories.
$categoryFilter = array();
// for each category assigned to this delivery method....
foreach($category as $catName => $items) {
$categoryName = $this->sanitize_title_with_dashes($catName);
if(!in_array( $catName, $categoryFilter)) {
$categoryFilter[] = $catName;
// '<option class="%s" value="%s">%s</option>';
$categoryList[] = sprintf($optFormat, "{$methodName} opt", "{$methodName}-{$categoryName}", $catName);
}
// for each item in this category...
foreach($items as $item) {
$url = $this->makeCourseUrl($deliveryMethod, $item['id'], $item['name']);
// '<option class="%s" value="%s">%s</option>';
$courses[] = sprintf($optFormat, "{$item['class']} opt", ($type == 'url' ? $url : $item['name']), $item['name']);
}
}
}
// sort the category and course lists
sort($categoryList);
sort($courses);
// push these onto the front of the array
array_unshift($methodList, sprintf($optFormat, 'static', '', 'Choose Training Method'));
array_unshift($categoryList, sprintf($optFormat, 'static', '', 'Choose Type'));
array_unshift($courses, sprintf($optFormat, 'static', '', 'Choose Course'));
//$dbg->log_entry('methods:', $_methodList);
//$dbg->log_entry('categories:', $_categoryList);
//$dbg->log_entry('courses:', $_courses);
// returns an array containing the groups, sub groups and courses
return(
array('groups' => join(' ', $methodList), // category
'subgroups' => join(' ', $categoryList), // group
'courses' => join(' ', $courses) // courses
)
);
}
/**
* Creates a url from course components
*
* @param $method - delivery method name
* @param $number - course number
* @param $title - course title
*
* @return string
*/
public function makeCourseUrl($method, $number, $title) {
// the course url must follow the format below
$urlFormat = '/course/%s/%s/%s/';
return(
sprintf($urlFormat,
$this->sanitize_title_with_dashes($method),
$number,
$this->sanitize_title_with_dashes($title)
)
);
}
/**
* Contact Form Options formatter
* @param $data
*
* @return string
*/
public function cfOptionsFormat($data) {
return($this->sfOptionsFormat($data, 'names'));
}
/**
* Page format function
* Creates a render array for a drupal page template
*
* @param $data - data record from sql query
*
* @return mixed
*/
function pageFormat($data) {
$this->dbg->log_entry(__FUNCTION__, $data);
$templateData = $page = array();
$courseDetails = $courseSched = $courseFormats = $relatedCourses = array();
$sections = array();
try {
extract($data);
if(empty($courseDetails)) {
throw new \Exception($this->exString(__FUNCTION__, __LINE__, 'Course Details were not found'));
}
// setup the course record
$r = $courseDetails[0];
// load the table - empty values are ignored
$table = array(
'code' => $r->CourseCode,
'category' => $r->CategoryName,
'title' => $r->CourseWebName,
'length' => $r->LengthDecription,
'group' => $r->GroupName,
'method' => $r->DeliveryMethodName,
'vendor' => $r->VendorName
);
// these are added to the template
foreach ($table as $key => $value) {
if (!empty($value)) {
$page[$key] = $value;
}
}
/**
* Related courses
* convert this array into an un-numbered list
* each course is wrapped in an anchor containing the url
*/
if (count($relatedCourses) > 0) {
$tags = array();
$tags[] = '<ul class="list">';
foreach ($relatedCourses as $related) {
$url = $this->makeCourseUrl($related->MethodName, $related->CourseNumber, $related->CourseName);
$tags[] = sprintf(
'<li><a title="%s" href="%s" class="courseUrl">%s</a></li>',
$related->CourseName, $url, $related->CourseName
);
}
$tags[] = "</ul>";
$page['related'] = implode("\n", $tags);
}
/**
* This course in other formats
* Converts the returned array into one or more un-numbered lists
* grouped by Delivery Method
*/
if (count($courseFormats) > 0) {
$lists = $tags = array();
$fmt = '<li><a title="%s" href="%s" class="courseUrl">%s</a></li>';
foreach ($courseFormats as $f) {
$url = $this->makeCourseUrl($f->MethodName, $f->CourseNumber, $f->CourseName);
$lists[$f->MethodName][] = sprintf($fmt, $f->CourseName, $url, $f->CourseName);
}
foreach ($lists as $listName => $list) {
$tags[] = sprintf('<h6 class="format-header">%s</h6>', $listName);
$tags[] = '<ul class="list">';
foreach ($list as $item) {
$tags[] = $item;
}
$tags[] = '</ul>';
}
$page['formats'] = implode("\n", $tags);
}
// -------------------------------------------
// Sections are processed in a specific order
// Each text file is assigned to a page section.
// build the schedule table (if any)
if (count($courseSched) > 0 && stristr($r->DeliveryMethodName, 'instruct')) {
$leadIn = '';
// only a single entry?
if(count($courseSched) == 1) {
// the first one is always the empty record.
if(empty($courseSched[0]->StartDate) && empty($courseSched[0]->EndDate) && !empty($courseSched[0]->defaultText)) {
$table = '<p class="warning">' . trim($courseSched[0]->defaultText) . '</p>';
}
}
else {
$table = $this->makeSchedTable($courseSched);
$leadIn = sprintf("<p>%s is scheduled for the following dates and times:</p>", $r->CourseWebName);
}
$sections[] = array(
"title" => "Course Schedule:",
"content" => $leadIn . $table,
"class" => "course-schedule schedule-div"
);
}
// get the overview text file (if any)
if (!empty($r->Overview)) {
$text = $this->get_file_contents(
$_SERVER['DOCUMENT_ROOT'] . $this->cfg->get('dman.overviewDir'),
$r->Overview,
'overview'
);
$sections[] = array(
"title" => "Overview",
"content" => $text,
"class" => "overview-div"
);
}
// get the objectives text file (if any)
if (!empty($r->Objectives)) {
$text = $this->get_file_contents(
$_SERVER['DOCUMENT_ROOT'] . $this->cfg->get('dman.objectivesDir'),
$r->Objectives,
'objectives'
);
$sections[] = array(
"title" => "Objectives",
"content" => $text,
"class" => "objectives-div"
);
}
// get the course content text file (if any)
if (!empty($r->CourseContent)) {
$text = $this->get_file_contents(
$_SERVER['DOCUMENT_ROOT'] . $this->cfg->get('dman.contentDir'),
$r->CourseContent,
'course-content',
true
);
$sections[] = array(
"title" => "Course Content",
"content" => $text,
"class" => "course-content-div"
);
}
// add the page sections
$page['sections'] = $sections;
$this->dbg->log_entry(__FUNCTION__, $page);
}
catch(\Exception $e) {
$page['sections'][] = array(
"title" => "Not Found",
"content" => "<p>Course information is not available</p>",
"class" => "course-content-div"
);
}
// return the template data
$templateData = array('page' => $page);
return($templateData);
}
/**
* Returns a course schedule table
*
* @param $schedule array
*
* @return null|string
*/
function makeSchedTable($schedule) {
$markup = $thead = $tbody = null;
if (is_array($schedule)) {
$fmtRow = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>";
$fmtTable = '<table class="schedule-table"><thead>%s</thead><tbody>%s</tbody></table>';
$thead = '<th>Start Date</th><th>End Date</th><th>Start Time</th><th>Location</th>';
foreach ($schedule as $entry) {
// ignore the empty record
if(empty($entry->StartDate) && empty($entry->EndDate)) {
continue;
}
else {
$tbody .= sprintf(
$fmtRow,
str_replace('12:00:00:000AM', '', $entry->StartDate), // remove weird time format added to the date
str_replace('12:00:00:000AM', '', $entry->EndDate), // remove weird time format added to the date
$entry->StartTime,
$entry->Location
);
}
$markup = sprintf($fmtTable, $thead, $tbody);
}
}
return($markup);
}
/**
* Returns the contents of a text file
*
* @param $dir
* @param $filename
* @param string $class
* @param int $addMore - true = add read more button
*
* @return null|string
* @internal param string $prefix
*/
function get_file_contents($dir, $filename, $class = '', $addMore = 0) {
$this->dbg->log_entry(__FUNCTION__, compact('dir', 'filename', 'class'));
ini_set('mbstring.substitute_character', " ");
$_addMore = $addMore;
$fmt = "%s<d" . "iv class=\"%s read-more\" %s>%s</div>%s";
$style = $more = '';
$text = $ret = null;
$file = $this->remove_trailing_slash($dir) . '/' . $filename;
$err = 0;
if(empty($filename)) {
$ret = null;
}
else {
if (file_exists($file)) {
$text = $this->remove_utf8_bom(file_get_contents($file));
$text = mb_convert_encoding($text, 'ISO-8859-1', 'UTF-8');
// $text = utf8_encode($text);
// format adjustments (for really bad html)
$search = $replace = array();
$rsTable = array(
// search item => replacement item
'<ul>' => '<ul class="list">',
'<blockquote>' => '<p>',
'</blockquote>' => '</p>',
'<h4>' => '<h6>',
'</h4>' => '</h6>',
'<h3>' => '<h5>',
'</h3>' => '</h5>',
'<h2>' => '<h4>',
'</h2>' => '</h4>',
'<li><em>' => '<li class="italic">',
'</em>' => '',
'?' => ' '
);
// replace: <p><strong>something that should be a header</strong></p>
// with a header tag
$text = str_replace(array_keys($rsTable), array_values($rsTable), $text);
}
else {
$this->dbg->log_entry(__FUNCTION__, sprintf('file: %s was not found', $file));
$class .= " error";
$style = 'style="color:red;"';
$text = $filename . ' (not found)';
$err = true;
}
if(!$err) {
if( !empty($text) ) {
if (strlen($text) > 1000 && $addMore) {
$more = sprintf('<a id="open-read-more" href="%s" class="button default small">read more</a>', '#more');
$style = 'style="display:none;"';
$_addMore = true;
}
else {
$_addMore = false;
}
// format the text - add a more button if necessary;
$ret = sprintf(
$fmt,
$more,
$class,
$style,
$text,
(($_addMore) ? $this->add_more_script() : '')
);
}
else {
$ret = null;
}
}
}
return($ret);
}
/**
* Removes a BOM (Byte-Order-Mark) from a file
* @param $text
* @return mixed
*/
function remove_utf8_bom($text) {
$bom = pack('H*','EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
/**
* Append a button script to the text and return it
*
* @param $text
*
* @return string
*/
function add_more_script($text='') {
ob_start(); ?>
<script type="application/javascript">
(function($) {
$(document).ready(function ($) {
$('body').on('click', '#open-read-more', function() {
$('.read-more').fadeIn(1200);
$(this).hide();
});
});
})(jQuery);
</script>
<?php
$script = ob_get_clean();
return($text . $script);
}
/**
* Removes a trailing slash from a directory pathname
* @param $path
*
* @return string
*/
function remove_trailing_slash($path) {
return(rtrim($path, '/'));
}
/**
* Sanitizes a title, replacing whitespace and a few other characters with dashes.
*
* Limits the output to alphanumeric characters, underscore (_) and dash (-).
* Whitespace becomes a dash.
*
* @param string $title The title to be sanitized.
* @param string $raw_title Optional. Not used.
* @param string $context Optional. The operation for which the string is sanitized.
*
* @since 1.0
*
* @return string The sanitized title.
*/
function sanitize_title_with_dashes($title, $raw_title = '', $context = 'display') {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if ($this->seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = $this->utf8_uri_encode($title, 200);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
if ('save' == $context) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace(array('%c2%a0', '%e2%80%93', '%e2%80%94'), '-', $title);
// Strip these characters entirely
$title = str_replace(
array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// acute accents
'%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
// grave accent, macron, caron
'%cc%80', '%cc%84', '%cc%8c',
), '', $title
);
// Convert times to x
$title = str_replace('%c3%97', 'x', $title);
}
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
/**
* Encode the Unicode values to be used in the URI.
*
* @since 1.0
*
* @param string $utf8_string
* @param int $length Max length of the string
*
* @return string String with Unicode encoded for URI.
*/
private function utf8_uri_encode($utf8_string, $length = 0) {
$unicode = '';
$values = array();
$num_octets = 1;
$unicode_length = 0;
$this->mbstring_binary_safe_encoding();
$string_length = strlen($utf8_string);
$this->reset_mbstring_encoding();
for ($i = 0; $i < $string_length; $i++) {
$value = ord($utf8_string[$i]);
if ($value < 128) {
if ($length && ($unicode_length >= $length)) {
break;
}
$unicode .= chr($value);
$unicode_length++;
}
else {
if (count($values) == 0) {
$num_octets = ($value < 224) ? 2 : 3;
}
$values[] = $value;
if ($length && ($unicode_length + ($num_octets * 3)) > $length) {
break;
}
if (count($values) == $num_octets) {
if ($num_octets == 3) {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
$unicode_length += 9;
}
else {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
$unicode_length += 6;
}
$values = array();
$num_octets = 1;
}
}
}
return $unicode;
}
/**
* Set the mbstring internal encoding to a binary safe encoding when func_overload
* is enabled.
*
* When mbstring.func_overload is in use for multi-byte encodings, the results from
* strlen() and similar functions respect the utf8 characters, causing binary data
* to return incorrect lengths.
*
* This function overrides the mbstring encoding to a binary-safe encoding, and
* resets it to the users expected encoding afterwards through the
* `reset_mbstring_encoding` function.
*
* It is safe to recursively call this function, however each
* `mbstring_binary_safe_encoding()` call must be followed up with an equal number
* of `reset_mbstring_encoding()` calls.
*
* @since 1.0
*
* @see reset_mbstring_encoding()
*
* @param bool $reset Optional. Whether to reset the encoding back to a previously-set encoding.
* Default false.
*/
private function mbstring_binary_safe_encoding($reset = false) {
static $encodings = array();
static $overloaded = null;
if (is_null($overloaded)) {
$overloaded = function_exists('mb_internal_encoding') && (ini_get('mbstring.func_overload') & 2);
}
if (false === $overloaded) {
return;
}
if (!$reset) {
$encoding = mb_internal_encoding();
array_push($encodings, $encoding);
mb_internal_encoding('ISO-8859-1');
}
if ($reset && $encodings) {
$encoding = array_pop($encodings);
mb_internal_encoding($encoding);
}
}
/**
* Reset the mbstring internal encoding to a users previously set encoding.
*
* @see mbstring_binary_safe_encoding()
*
* @since 1.0
*/
private function reset_mbstring_encoding() {
$this->mbstring_binary_safe_encoding(true);
}
/**
* Checks to see if a string is utf8 encoded.
*
* NOTE: This function checks for 5-Byte sequences, UTF8
* has Bytes Sequences with a maximum length of 4.
*
* @param string $str The string to be checked
*
* @return bool True if $str fits a UTF-8 model, false otherwise.
*/
private function seems_utf8($str) {
$this->mbstring_binary_safe_encoding();
$length = strlen($str);
$this->reset_mbstring_encoding();
for ($i = 0; $i < $length; $i++) {
$c = ord($str[$i]);
if ($c < 0x80) {
$n = 0;
} # 0bbbbbbb
elseif (($c & 0xE0) == 0xC0) {
$n = 1;
} # 110bbbbb
elseif (($c & 0xF0) == 0xE0) {
$n = 2;
} # 1110bbbb
elseif (($c & 0xF8) == 0xF0) {
$n = 3;
} # 11110bbb
elseif (($c & 0xFC) == 0xF8) {
$n = 4;
} # 111110bb
elseif (($c & 0xFE) == 0xFC) {
$n = 5;
} # 1111110b
else {
return false;
} # Does not match any model
for ($j = 0; $j < $n; $j++) { # n bytes matching 10bbbbbb follow ?
if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80)) {
return false;
}
}
}
return true;
}
/**
* Creates an exception message string
*
* @param $func
* @param $line
* @param $exception
*
* @return string
*/
function exString($func, $line, $exception) {
$err = new \ecpi\dbc("dataManager.exceptions");
$msg = sprintf("%s->%s() (line: %s) - %s", __CLASS__, $func, $line, $exception);
$err->log_entry("exception", $msg);
return ($msg);
}
}
}
|
gpl-2.0
|
rex-xxx/mt6572_x201
|
frameworks/av/services/audioflinger/AudioPolicyService.cpp
|
58994
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "AudioPolicyService"
//#define LOG_NDEBUG 0
#undef __STRICT_ANSI__
#define __STDINT_LIMITS
#define __STDC_LIMIT_MACROS
#include <stdint.h>
#include <sys/time.h>
#include <binder/IServiceManager.h>
#include <utils/Log.h>
#include <cutils/properties.h>
#include <binder/IPCThreadState.h>
#include <utils/String16.h>
#include <utils/threads.h>
#include "AudioPolicyService.h"
#include "ServiceUtilities.h"
#include <hardware_legacy/power.h>
#include <media/AudioEffect.h>
#include <media/EffectsFactoryApi.h>
#include <hardware/hardware.h>
#include <system/audio.h>
#include <system/audio_policy.h>
#include <hardware/audio_policy.h>
#include <audio_effects/audio_effects_conf.h>
#ifdef MTK_AUDIO
#include <cutils/xlog.h>
#include <linux/rtpm_prio.h>
#include "AudioIoctl.h"
#endif
#ifdef MTK_AUDIO
#define MTK_ALOG_V(fmt, arg...) SXLOGV(fmt, ##arg)
#define MTK_ALOG_D(fmt, arg...) SXLOGD(fmt, ##arg)
#define MTK_ALOG_W(fmt, arg...) SXLOGW(fmt, ##arg)
#define MTK_ALOG_E(fmt, arg...) SXLOGE("Err: %5d:, "fmt, __LINE__, ##arg)
#undef ALOGV
#define ALOGV MTK_ALOG_V
#else
#define MTK_ALOG_V(fmt, arg...) do { } while(0)
#define MTK_ALOG_D(fmt, arg...) do { } while(0)
#define MTK_ALOG_W(fmt, arg...) do { } while(0)
#define MTK_ALOG_E(fmt, arg...) do { } while(0)
#endif
namespace android {
static const char kDeadlockedString[] = "AudioPolicyService may be deadlocked\n";
static const char kCmdDeadlockedString[] = "AudioPolicyService command thread may be deadlocked\n";
static const int kDumpLockRetries = 50;
static const int kDumpLockSleepUs = 20000;
#ifdef MTK_AUDIO
// return true if string nned to be filter
static bool ParaMetersNeedFilter(String8 Pair){
//String8 FilterString1(keyAddtForceuseNormal);
String8 FilterString2(keyInitVoume);
String8 FilterString3(keySetStreamStart);
String8 FilterString4(keySetStreamStop);
String8 FilterString5(keySetRecordStreamStart);
String8 FilterString6(keySetRecordStreamStop);
MTK_ALOG_V("ParaMetersNeedFilter Pair = %s,",Pair.string ());
if(FilterString2 == Pair || FilterString3 == Pair
|| FilterString4 == Pair || FilterString5 == Pair || FilterString6 == Pair){
MTK_ALOG_V("Pair = %s",Pair.string ());
return false;
}
return true;
}
#endif //MTK_AUDIO
namespace {
extern struct audio_policy_service_ops aps_ops;
#ifdef MTK_AUDIO
bool kHeadsetjavaStart = false;
#endif
};
// ----------------------------------------------------------------------------
#ifdef MTK_AUDIO
//static
void AudioPolicyService::AudioEarphoneCallback(void * user,int device, bool on)
{
ALOGD("+AudioEarphoneCallback device 0x%x, on %d",device,on);
AudioPolicyService * policy = (AudioPolicyService * )user;
const char * addr="";
audio_policy_dev_state_t state = \
on ? AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
policy->setDeviceConnectionState((audio_devices_t)device,state,addr);
ALOGD("-AudioEarphoneCallback device 0x%x, on %d",device,on);
}
#endif
AudioPolicyService::AudioPolicyService()
: BnAudioPolicyService() , mpAudioPolicyDev(NULL) , mpAudioPolicy(NULL)
{
char value[PROPERTY_VALUE_MAX];
const struct hw_module_t *module;
int forced_val;
int rc;
Mutex::Autolock _l(mLock);
// start tone playback thread
mTonePlaybackThread = new AudioCommandThread(String8(""));
// start audio commands thread
mAudioCommandThread = new AudioCommandThread(String8("ApmCommand"));
/* instantiate the audio policy manager */
rc = hw_get_module(AUDIO_POLICY_HARDWARE_MODULE_ID, &module);
if (rc)
return;
rc = audio_policy_dev_open(module, &mpAudioPolicyDev);
ALOGE_IF(rc, "couldn't open audio policy device (%s)", strerror(-rc));
if (rc)
return;
rc = mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, &aps_ops, this,
&mpAudioPolicy);
ALOGE_IF(rc, "couldn't create audio policy (%s)", strerror(-rc));
if (rc)
return;
rc = mpAudioPolicy->init_check(mpAudioPolicy);
ALOGE_IF(rc, "couldn't init_check the audio policy (%s)", strerror(-rc));
if (rc)
return;
#ifdef MTK_AUDIO
property_get("ro.camera.sound.forced", value, "0");
forced_val = strtol(value, NULL, 0);
mpAudioPolicy->set_can_mute_enforced_audible(mpAudioPolicy, !forced_val);
#endif
ALOGI("Loaded audio policy from %s (%s)", module->name, module->id);
// load audio pre processing modules
if (access(AUDIO_EFFECT_VENDOR_CONFIG_FILE, R_OK) == 0) {
loadPreProcessorConfig(AUDIO_EFFECT_VENDOR_CONFIG_FILE);
} else if (access(AUDIO_EFFECT_DEFAULT_CONFIG_FILE, R_OK) == 0) {
loadPreProcessorConfig(AUDIO_EFFECT_DEFAULT_CONFIG_FILE);
}
#ifdef MTK_AUDIO
mHeadsetDetect = new HeadsetDetect(this,&AudioEarphoneCallback); //earphone callback
if(mHeadsetDetect) mHeadsetDetect->start();
#endif
}
AudioPolicyService::~AudioPolicyService()
{
mTonePlaybackThread->exit();
mTonePlaybackThread.clear();
mAudioCommandThread->exit();
mAudioCommandThread.clear();
// release audio pre processing resources
for (size_t i = 0; i < mInputSources.size(); i++) {
delete mInputSources.valueAt(i);
}
mInputSources.clear();
for (size_t i = 0; i < mInputs.size(); i++) {
mInputs.valueAt(i)->mEffects.clear();
delete mInputs.valueAt(i);
}
mInputs.clear();
if (mpAudioPolicy != NULL && mpAudioPolicyDev != NULL)
mpAudioPolicyDev->destroy_audio_policy(mpAudioPolicyDev, mpAudioPolicy);
if (mpAudioPolicyDev != NULL)
audio_policy_dev_close(mpAudioPolicyDev);
#ifdef MTK_AUDIO
if(mHeadsetDetect)
delete mHeadsetDetect;
#endif
}
status_t AudioPolicyService::setDeviceConnectionState(audio_devices_t device,
audio_policy_dev_state_t state,
const char *device_address)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
if (!audio_is_output_device(device) && !audio_is_input_device(device)) {
return BAD_VALUE;
}
if (state != AUDIO_POLICY_DEVICE_STATE_AVAILABLE &&
state != AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
return BAD_VALUE;
}
ALOGV("setDeviceConnectionState() tid %d", gettid());
Mutex::Autolock _l(mLock);
#ifdef MTK_AUDIO
if(!kHeadsetjavaStart && mHeadsetDetect!=NULL)
{
//if this function is called by other threads, headsetdetect can exit.
if(!mHeadsetDetect->isCurrentThread())
{
kHeadsetjavaStart = true;
mHeadsetDetect->stop();
}
}
#endif
return mpAudioPolicy->set_device_connection_state(mpAudioPolicy, device,
state, device_address);
}
audio_policy_dev_state_t AudioPolicyService::getDeviceConnectionState(
audio_devices_t device,
const char *device_address)
{
if (mpAudioPolicy == NULL) {
return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
}
return mpAudioPolicy->get_device_connection_state(mpAudioPolicy, device,
device_address);
}
status_t AudioPolicyService::setPhoneState(audio_mode_t state)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
if (uint32_t(state) >= AUDIO_MODE_CNT) {
return BAD_VALUE;
}
ALOGD("+setPhoneState() tid %d", gettid());
// TODO: check if it is more appropriate to do it in platform specific policy manager
AudioSystem::setMode(state);
Mutex::Autolock _l(mLock);
mpAudioPolicy->set_phone_state(mpAudioPolicy, state);
ALOGD("-setPhoneState() tid %d", gettid());
return NO_ERROR;
}
status_t AudioPolicyService::setForceUse(audio_policy_force_use_t usage,
audio_policy_forced_cfg_t config)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
if (usage < 0 || usage >= AUDIO_POLICY_FORCE_USE_CNT) {
return BAD_VALUE;
}
if (config < 0 || config >= AUDIO_POLICY_FORCE_CFG_CNT) {
return BAD_VALUE;
}
ALOGV("setForceUse() tid %d", gettid());
Mutex::Autolock _l(mLock);
mpAudioPolicy->set_force_use(mpAudioPolicy, usage, config);
return NO_ERROR;
}
audio_policy_forced_cfg_t AudioPolicyService::getForceUse(audio_policy_force_use_t usage)
{
if (mpAudioPolicy == NULL) {
return AUDIO_POLICY_FORCE_NONE;
}
if (usage < 0 || usage >= AUDIO_POLICY_FORCE_USE_CNT) {
return AUDIO_POLICY_FORCE_NONE;
}
return mpAudioPolicy->get_force_use(mpAudioPolicy, usage);
}
audio_io_handle_t AudioPolicyService::getOutput(audio_stream_type_t stream,
uint32_t samplingRate,
audio_format_t format,
audio_channel_mask_t channelMask,
audio_output_flags_t flags)
{
if (mpAudioPolicy == NULL) {
return 0;
}
ALOGV("getOutput() tid %d", gettid());
Mutex::Autolock _l(mLock);
return mpAudioPolicy->get_output(mpAudioPolicy, stream, samplingRate, format, channelMask, flags);
}
status_t AudioPolicyService::startOutput(audio_io_handle_t output,
audio_stream_type_t stream,
int session)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
ALOGV("startOutput() tid %d", gettid());
Mutex::Autolock _l(mLock);
return mpAudioPolicy->start_output(mpAudioPolicy, output, stream, session);
}
status_t AudioPolicyService::stopOutput(audio_io_handle_t output,
audio_stream_type_t stream,
int session)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
ALOGV("stopOutput() tid %d", gettid());
Mutex::Autolock _l(mLock);
return mpAudioPolicy->stop_output(mpAudioPolicy, output, stream, session);
}
void AudioPolicyService::releaseOutput(audio_io_handle_t output)
{
if (mpAudioPolicy == NULL) {
return;
}
ALOGV("releaseOutput() tid %d", gettid());
Mutex::Autolock _l(mLock);
mpAudioPolicy->release_output(mpAudioPolicy, output);
}
audio_io_handle_t AudioPolicyService::getInput(audio_source_t inputSource,
uint32_t samplingRate,
audio_format_t format,
audio_channel_mask_t channelMask,
int audioSession)
{
if (mpAudioPolicy == NULL) {
return 0;
}
// already checked by client, but double-check in case the client wrapper is bypassed
if (uint32_t(inputSource) >= AUDIO_SOURCE_CNT) {
return 0;
}
Mutex::Autolock _l(mLock);
// the audio_in_acoustics_t parameter is ignored by get_input()
audio_io_handle_t input = mpAudioPolicy->get_input(mpAudioPolicy, inputSource, samplingRate,
format, channelMask, (audio_in_acoustics_t) 0);
if (input == 0) {
return input;
}
// create audio pre processors according to input source
ssize_t index = mInputSources.indexOfKey(inputSource);
if (index < 0) {
return input;
}
ssize_t idx = mInputs.indexOfKey(input);
InputDesc *inputDesc;
if (idx < 0) {
inputDesc = new InputDesc(audioSession);
mInputs.add(input, inputDesc);
} else {
inputDesc = mInputs.valueAt(idx);
}
Vector <EffectDesc *> effects = mInputSources.valueAt(index)->mEffects;
for (size_t i = 0; i < effects.size(); i++) {
EffectDesc *effect = effects[i];
sp<AudioEffect> fx = new AudioEffect(NULL, &effect->mUuid, -1, 0, 0, audioSession, input);
status_t status = fx->initCheck();
if (status != NO_ERROR && status != ALREADY_EXISTS) {
ALOGW("Failed to create Fx %s on input %d", effect->mName, input);
// fx goes out of scope and strong ref on AudioEffect is released
continue;
}
for (size_t j = 0; j < effect->mParams.size(); j++) {
fx->setParameter(effect->mParams[j]);
}
inputDesc->mEffects.add(fx);
}
setPreProcessorEnabled(inputDesc, true);
return input;
}
status_t AudioPolicyService::startInput(audio_io_handle_t input)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
Mutex::Autolock _l(mLock);
return mpAudioPolicy->start_input(mpAudioPolicy, input);
}
status_t AudioPolicyService::stopInput(audio_io_handle_t input)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
Mutex::Autolock _l(mLock);
return mpAudioPolicy->stop_input(mpAudioPolicy, input);
}
void AudioPolicyService::releaseInput(audio_io_handle_t input)
{
if (mpAudioPolicy == NULL) {
return;
}
Mutex::Autolock _l(mLock);
mpAudioPolicy->release_input(mpAudioPolicy, input);
ssize_t index = mInputs.indexOfKey(input);
if (index < 0) {
return;
}
InputDesc *inputDesc = mInputs.valueAt(index);
setPreProcessorEnabled(inputDesc, false);
delete inputDesc;
mInputs.removeItemsAt(index);
}
status_t AudioPolicyService::initStreamVolume(audio_stream_type_t stream,
int indexMin,
int indexMax)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
return BAD_VALUE;
}
Mutex::Autolock _l(mLock);
mpAudioPolicy->init_stream_volume(mpAudioPolicy, stream, indexMin, indexMax);
return NO_ERROR;
}
status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream,
int index,
audio_devices_t device)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
if (!settingsAllowed()) {
return PERMISSION_DENIED;
}
if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
return BAD_VALUE;
}
Mutex::Autolock _l(mLock);
if (mpAudioPolicy->set_stream_volume_index_for_device) {
return mpAudioPolicy->set_stream_volume_index_for_device(mpAudioPolicy,
stream,
index,
device);
} else {
return mpAudioPolicy->set_stream_volume_index(mpAudioPolicy, stream, index);
}
}
status_t AudioPolicyService::getStreamVolumeIndex(audio_stream_type_t stream,
int *index,
audio_devices_t device)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
return BAD_VALUE;
}
Mutex::Autolock _l(mLock);
if (mpAudioPolicy->get_stream_volume_index_for_device) {
return mpAudioPolicy->get_stream_volume_index_for_device(mpAudioPolicy,
stream,
index,
device);
} else {
return mpAudioPolicy->get_stream_volume_index(mpAudioPolicy, stream, index);
}
}
uint32_t AudioPolicyService::getStrategyForStream(audio_stream_type_t stream)
{
if (mpAudioPolicy == NULL) {
return 0;
}
return mpAudioPolicy->get_strategy_for_stream(mpAudioPolicy, stream);
}
//audio policy: use audio_device_t appropriately
audio_devices_t AudioPolicyService::getDevicesForStream(audio_stream_type_t stream)
{
if (mpAudioPolicy == NULL) {
return (audio_devices_t)0;
}
return mpAudioPolicy->get_devices_for_stream(mpAudioPolicy, stream);
}
audio_io_handle_t AudioPolicyService::getOutputForEffect(const effect_descriptor_t *desc)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
Mutex::Autolock _l(mLock);
return mpAudioPolicy->get_output_for_effect(mpAudioPolicy, desc);
}
status_t AudioPolicyService::registerEffect(const effect_descriptor_t *desc,
audio_io_handle_t io,
uint32_t strategy,
int session,
int id)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
return mpAudioPolicy->register_effect(mpAudioPolicy, desc, io, strategy, session, id);
}
status_t AudioPolicyService::unregisterEffect(int id)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
return mpAudioPolicy->unregister_effect(mpAudioPolicy, id);
}
status_t AudioPolicyService::setEffectEnabled(int id, bool enabled)
{
if (mpAudioPolicy == NULL) {
return NO_INIT;
}
return mpAudioPolicy->set_effect_enabled(mpAudioPolicy, id, enabled);
}
bool AudioPolicyService::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
{
if (mpAudioPolicy == NULL) {
return 0;
}
Mutex::Autolock _l(mLock);
return mpAudioPolicy->is_stream_active(mpAudioPolicy, stream, inPastMs);
}
bool AudioPolicyService::isSourceActive(audio_source_t source) const
{
if (mpAudioPolicy == NULL) {
return false;
}
if (mpAudioPolicy->is_source_active == 0) {
return false;
}
Mutex::Autolock _l(mLock);
return mpAudioPolicy->is_source_active(mpAudioPolicy, source);
}
#ifdef MTK_AUDIO
status_t AudioPolicyService::SetPolicyManagerParameters(int par1, int par2, int par3 , int par4)
{
if (mpAudioPolicy == NULL) {
return 0;
}
//SetPolicyManagerParameters no need to hold mlock.
//Mutex::Autolock _l(mLock);
return mpAudioPolicy->set_policy_parameters(mpAudioPolicy, par1, par2,par3,par4);
}
#endif
status_t AudioPolicyService::queryDefaultPreProcessing(int audioSession,
effect_descriptor_t *descriptors,
uint32_t *count)
{
if (mpAudioPolicy == NULL) {
*count = 0;
return NO_INIT;
}
Mutex::Autolock _l(mLock);
status_t status = NO_ERROR;
size_t index;
for (index = 0; index < mInputs.size(); index++) {
if (mInputs.valueAt(index)->mSessionId == audioSession) {
break;
}
}
if (index == mInputs.size()) {
*count = 0;
return BAD_VALUE;
}
Vector< sp<AudioEffect> > effects = mInputs.valueAt(index)->mEffects;
for (size_t i = 0; i < effects.size(); i++) {
effect_descriptor_t desc = effects[i]->descriptor();
if (i < *count) {
descriptors[i] = desc;
}
}
if (effects.size() > *count) {
status = NO_MEMORY;
}
*count = effects.size();
return status;
}
void AudioPolicyService::binderDied(const wp<IBinder>& who) {
ALOGW("binderDied() %p, tid %d, calling pid %d", who.unsafe_get(), gettid(),
IPCThreadState::self()->getCallingPid());
}
static bool tryLock(Mutex& mutex)
{
bool locked = false;
for (int i = 0; i < kDumpLockRetries; ++i) {
if (mutex.tryLock() == NO_ERROR) {
locked = true;
break;
}
usleep(kDumpLockSleepUs);
}
return locked;
}
status_t AudioPolicyService::dumpInternals(int fd)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "PolicyManager Interface: %p\n", mpAudioPolicy);
result.append(buffer);
snprintf(buffer, SIZE, "Command Thread: %p\n", mAudioCommandThread.get());
result.append(buffer);
snprintf(buffer, SIZE, "Tones Thread: %p\n", mTonePlaybackThread.get());
result.append(buffer);
write(fd, result.string(), result.size());
return NO_ERROR;
}
status_t AudioPolicyService::dump(int fd, const Vector<String16>& args)
{
if (!dumpAllowed()) {
dumpPermissionDenial(fd);
} else {
bool locked = tryLock(mLock);
if (!locked) {
String8 result(kDeadlockedString);
write(fd, result.string(), result.size());
}
dumpInternals(fd);
if (mAudioCommandThread != 0) {
mAudioCommandThread->dump(fd);
}
if (mTonePlaybackThread != 0) {
mTonePlaybackThread->dump(fd);
}
if (mpAudioPolicy) {
mpAudioPolicy->dump(mpAudioPolicy, fd);
}
if (locked) mLock.unlock();
}
return NO_ERROR;
}
status_t AudioPolicyService::dumpPermissionDenial(int fd)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "Permission Denial: "
"can't dump AudioPolicyService from pid=%d, uid=%d\n",
IPCThreadState::self()->getCallingPid(),
IPCThreadState::self()->getCallingUid());
result.append(buffer);
write(fd, result.string(), result.size());
return NO_ERROR;
}
void AudioPolicyService::setPreProcessorEnabled(const InputDesc *inputDesc, bool enabled)
{
const Vector<sp<AudioEffect> > &fxVector = inputDesc->mEffects;
for (size_t i = 0; i < fxVector.size(); i++) {
fxVector.itemAt(i)->setEnabled(enabled);
}
}
status_t AudioPolicyService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
return BnAudioPolicyService::onTransact(code, data, reply, flags);
}
// ----------- AudioPolicyService::AudioCommandThread implementation ----------
AudioPolicyService::AudioCommandThread::AudioCommandThread(String8 name)
: Thread(false), mName(name)
{
mpToneGenerator = NULL;
}
AudioPolicyService::AudioCommandThread::~AudioCommandThread()
{
if (mName != "" && !mAudioCommands.isEmpty()) {
release_wake_lock(mName.string());
}
mAudioCommands.clear();
delete mpToneGenerator;
}
void AudioPolicyService::AudioCommandThread::onFirstRef()
{
if (mName != "") {
run(mName.string(), ANDROID_PRIORITY_AUDIO);
} else {
run("AudioCommand", ANDROID_PRIORITY_AUDIO);
}
}
#ifdef MTK_AUDIO
status_t AudioPolicyService::AudioCommandThread::readyToRun()
{
struct sched_param sched_p;
sched_getparam(0, &sched_p);
sched_p.sched_priority = RTPM_PRIO_AUDIO_COMMAND;
if(0 != sched_setscheduler(0, SCHED_RR, &sched_p)) {
MTK_ALOG_E("[%s] failed, errno: %d", __func__, errno);
}
else {
sched_p.sched_priority = RTPM_PRIO_AUDIO_COMMAND;
sched_getparam(0, &sched_p);
MTK_ALOG_D("sched_setscheduler ok, priority: %d", sched_p.sched_priority);
}
return NO_ERROR;
}
#endif
bool AudioPolicyService::AudioCommandThread::threadLoop()
{
nsecs_t waitTime = INT64_MAX;
mLock.lock();
while (!exitPending())
{
while (!mAudioCommands.isEmpty()) {
nsecs_t curTime = systemTime();
// commands are sorted by increasing time stamp: execute them from index 0 and up
if (mAudioCommands[0]->mTime <= curTime) {
AudioCommand *command = mAudioCommands[0];
mAudioCommands.removeAt(0);
mLastCommand = *command;
switch (command->mCommand) {
case START_TONE: {
mLock.unlock();
ToneData *data = (ToneData *)command->mParam;
ALOGV("AudioCommandThread() processing start tone %d on stream %d",
data->mType, data->mStream);
delete mpToneGenerator;
mpToneGenerator = new ToneGenerator(data->mStream, 1.0);
mpToneGenerator->startTone(data->mType);
delete data;
mLock.lock();
}break;
case STOP_TONE: {
mLock.unlock();
ALOGV("AudioCommandThread() processing stop tone");
if (mpToneGenerator != NULL) {
mpToneGenerator->stopTone();
delete mpToneGenerator;
mpToneGenerator = NULL;
}
mLock.lock();
}break;
case SET_VOLUME: {
VolumeData *data = (VolumeData *)command->mParam;
ALOGV("AudioCommandThread() processing set volume stream %d, \
volume %f, output %d", data->mStream, data->mVolume, data->mIO);
command->mStatus = AudioSystem::setStreamVolume(data->mStream,
data->mVolume,
data->mIO);
if (command->mWaitStatus) {
command->mCond.signal();
mWaitWorkCV.wait(mLock);
}
delete data;
}break;
case SET_PARAMETERS: {
ParametersData *data = (ParametersData *)command->mParam;
ALOGV("AudioCommandThread() processing set parameters string %s, io %d",
data->mKeyValuePairs.string(), data->mIO);
#ifdef MTK_AUDIO
AudioParameter param = AudioParameter(data->mKeyValuePairs);
float value = 0.0;
// use setmastervolume instead of setparameter
if((param.getFloat (String8("SetMasterVolume"), value)) == NO_ERROR){
MTK_ALOG_D("SET_PARAMETERS SetMasterVolume value = %f",value);
AudioSystem::setMasterVolume (value);
}
else{
command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
}
#else
command->mStatus = AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
#endif
if (command->mWaitStatus) {
command->mCond.signal();
mWaitWorkCV.wait(mLock);
}
delete data;
}break;
case SET_VOICE_VOLUME: {
VoiceVolumeData *data = (VoiceVolumeData *)command->mParam;
ALOGV("AudioCommandThread() processing set voice volume volume %f",
data->mVolume);
command->mStatus = AudioSystem::setVoiceVolume(data->mVolume);
if (command->mWaitStatus) {
command->mCond.signal();
mWaitWorkCV.wait(mLock);
}
delete data;
}break;
default:
ALOGW("AudioCommandThread() unknown command %d", command->mCommand);
}
delete command;
waitTime = INT64_MAX;
} else {
waitTime = mAudioCommands[0]->mTime - curTime;
break;
}
}
// release delayed commands wake lock
if (mName != "" && mAudioCommands.isEmpty()) {
release_wake_lock(mName.string());
}
ALOGV("AudioCommandThread() going to sleep");
mWaitWorkCV.waitRelative(mLock, waitTime);
ALOGV("AudioCommandThread() waking up");
}
mLock.unlock();
return false;
}
status_t AudioPolicyService::AudioCommandThread::dump(int fd)
{
const size_t SIZE = 256;
char buffer[SIZE];
String8 result;
snprintf(buffer, SIZE, "AudioCommandThread %p Dump\n", this);
result.append(buffer);
write(fd, result.string(), result.size());
bool locked = tryLock(mLock);
if (!locked) {
String8 result2(kCmdDeadlockedString);
write(fd, result2.string(), result2.size());
}
snprintf(buffer, SIZE, "- Commands:\n");
result = String8(buffer);
result.append(" Command Time Wait pParam\n");
for (size_t i = 0; i < mAudioCommands.size(); i++) {
mAudioCommands[i]->dump(buffer, SIZE);
result.append(buffer);
}
result.append(" Last Command\n");
mLastCommand.dump(buffer, SIZE);
result.append(buffer);
write(fd, result.string(), result.size());
if (locked) mLock.unlock();
return NO_ERROR;
}
void AudioPolicyService::AudioCommandThread::startToneCommand(ToneGenerator::tone_type type,
audio_stream_type_t stream)
{
AudioCommand *command = new AudioCommand();
command->mCommand = START_TONE;
ToneData *data = new ToneData();
data->mType = type;
data->mStream = stream;
command->mParam = (void *)data;
Mutex::Autolock _l(mLock);
insertCommand_l(command);
ALOGV("AudioCommandThread() adding tone start type %d, stream %d", type, stream);
mWaitWorkCV.signal();
}
void AudioPolicyService::AudioCommandThread::stopToneCommand()
{
AudioCommand *command = new AudioCommand();
command->mCommand = STOP_TONE;
command->mParam = NULL;
Mutex::Autolock _l(mLock);
insertCommand_l(command);
ALOGV("AudioCommandThread() adding tone stop");
mWaitWorkCV.signal();
}
status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
float volume,
audio_io_handle_t output,
int delayMs)
{
status_t status = NO_ERROR;
AudioCommand *command = new AudioCommand();
command->mCommand = SET_VOLUME;
VolumeData *data = new VolumeData();
data->mStream = stream;
data->mVolume = volume;
data->mIO = output;
command->mParam = data;
#ifdef MTK_AUDIO
Mutex::Autolock _t(mFunLock); //must get funlock;
#endif
Mutex::Autolock _l(mLock);
insertCommand_l(command, delayMs);
ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
stream, volume, output);
mWaitWorkCV.signal();
if (command->mWaitStatus) {
command->mCond.wait(mLock);
status = command->mStatus;
mWaitWorkCV.signal();
}
return status;
}
status_t AudioPolicyService::AudioCommandThread::parametersCommand(audio_io_handle_t ioHandle,
const char *keyValuePairs,
int delayMs)
{
status_t status = NO_ERROR;
AudioCommand *command = new AudioCommand();
command->mCommand = SET_PARAMETERS;
ParametersData *data = new ParametersData();
data->mIO = ioHandle;
data->mKeyValuePairs = String8(keyValuePairs);
command->mParam = data;
#ifdef MTK_AUDIO
Mutex::Autolock _t(mFunLock); //must get funlock;
#endif
Mutex::Autolock _l(mLock);
insertCommand_l(command, delayMs);
ALOGV("AudioCommandThread() adding set parameter string %s, io %d ,delay %d",
keyValuePairs, ioHandle, delayMs);
mWaitWorkCV.signal();
if (command->mWaitStatus) {
command->mCond.wait(mLock);
status = command->mStatus;
mWaitWorkCV.signal();
}
return status;
}
status_t AudioPolicyService::AudioCommandThread::voiceVolumeCommand(float volume, int delayMs)
{
status_t status = NO_ERROR;
AudioCommand *command = new AudioCommand();
command->mCommand = SET_VOICE_VOLUME;
VoiceVolumeData *data = new VoiceVolumeData();
data->mVolume = volume;
command->mParam = data;
#ifdef MTK_AUDIO
Mutex::Autolock _t(mFunLock); //must get funlock;
#endif
Mutex::Autolock _l(mLock);
insertCommand_l(command, delayMs);
ALOGV("AudioCommandThread() adding set voice volume volume %f", volume);
mWaitWorkCV.signal();
if (command->mWaitStatus) {
command->mCond.wait(mLock);
status = command->mStatus;
mWaitWorkCV.signal();
}
return status;
}
// insertCommand_l() must be called with mLock held
void AudioPolicyService::AudioCommandThread::insertCommand_l(AudioCommand *command, int delayMs)
{
ssize_t i; // not size_t because i will count down to -1
Vector <AudioCommand *> removedCommands;
nsecs_t time = 0;
#ifdef MTK_AUDIO
//<----weiguo alps00053099 adjust matv volume when record sound stoping, matv sound will out through speaker.
// delay -1 to put volume setting command at the end of command queue in audiopolicy service
// attentation : this is only for matv, if for other type ,you should test it.
if(delayMs == -1)
{
int lastcmdid = mAudioCommands.size()-1;
if( lastcmdid >=0 )
{
AudioCommand *lastcommand = mAudioCommands[lastcmdid];
command->mTime = lastcommand->mTime + 1; // put it at the end of command queue
}
else
{
command->mTime = systemTime(); //no command in queue.
}
//MTK_ALOG_V("command wait time=%lld ms",ns2ms(command->mTime - systemTime()));
}//weiguo---->
else
{
command->mTime = systemTime() + milliseconds(delayMs);
}
#else
command->mTime = systemTime() + milliseconds(delayMs);
#endif
// acquire wake lock to make sure delayed commands are processed
if (mName != "" && mAudioCommands.isEmpty()) {
acquire_wake_lock(PARTIAL_WAKE_LOCK, mName.string());
}
// check same pending commands with later time stamps and eliminate them
for (i = mAudioCommands.size()-1; i >= 0; i--) {
AudioCommand *command2 = mAudioCommands[i];
// commands are sorted by increasing time stamp: no need to scan the rest of mAudioCommands
if (command2->mTime <= command->mTime) break;
if (command2->mCommand != command->mCommand) continue;
switch (command->mCommand) {
case SET_PARAMETERS: {
ParametersData *data = (ParametersData *)command->mParam;
ParametersData *data2 = (ParametersData *)command2->mParam;
if (data->mIO != data2->mIO) break;
ALOGV("Comparing parameter command %s to new command %s",
data2->mKeyValuePairs.string(), data->mKeyValuePairs.string());
AudioParameter param = AudioParameter(data->mKeyValuePairs);
AudioParameter param2 = AudioParameter(data2->mKeyValuePairs);
for (size_t j = 0; j < param.size(); j++) {
String8 key;
String8 value;
param.getAt(j, key, value);
#ifdef MTK_AUDIO
if(!ParaMetersNeedFilter(key)) continue; // add policy for certain string
#endif
for (size_t k = 0; k < param2.size(); k++) {
String8 key2;
String8 value2;
param2.getAt(k, key2, value2);
if (key2 == key) {
param2.remove(key2);
ALOGV("Filtering out parameter %s", key2.string());
break;
}
}
}
// if all keys have been filtered out, remove the command.
// otherwise, update the key value pairs
if (param2.size() == 0) {
#ifdef MTK_AUDIO
delete data2;
#endif
removedCommands.add(command2);
} else {
data2->mKeyValuePairs = param2.toString();
}
time = command2->mTime;
} break;
case SET_VOLUME: {
VolumeData *data = (VolumeData *)command->mParam;
VolumeData *data2 = (VolumeData *)command2->mParam;
if (data->mIO != data2->mIO) break;
if (data->mStream != data2->mStream) break;
ALOGV("Filtering out volume command on output %d for stream %d",
data->mIO, data->mStream);
#ifdef MTK_AUDIO
delete data2;
#endif
removedCommands.add(command2);
time = command2->mTime;
} break;
case START_TONE:
case STOP_TONE:
default:
break;
}
}
// remove filtered commands
for (size_t j = 0; j < removedCommands.size(); j++) {
// removed commands always have time stamps greater than current command
for (size_t k = i + 1; k < mAudioCommands.size(); k++) {
if (mAudioCommands[k] == removedCommands[j]) {
ALOGV("suppressing command: %d", mAudioCommands[k]->mCommand);
mAudioCommands.removeAt(k);
break;
}
}
}
removedCommands.clear();
// wait for status only if delay is 0 and command time was not modified above
if (delayMs == 0 && time == 0) {
command->mWaitStatus = true;
} else {
command->mWaitStatus = false;
}
// update command time if modified above
if (time != 0) {
command->mTime = time;
}
// insert command at the right place according to its time stamp
ALOGV("inserting command: %d at index %d, num commands %d",
command->mCommand, (int)i+1, mAudioCommands.size());
mAudioCommands.insertAt(command, i + 1);
}
void AudioPolicyService::AudioCommandThread::exit()
{
ALOGV("AudioCommandThread::exit");
{
AutoMutex _l(mLock);
requestExit();
mWaitWorkCV.signal();
}
requestExitAndWait();
}
void AudioPolicyService::AudioCommandThread::AudioCommand::dump(char* buffer, size_t size)
{
snprintf(buffer, size, " %02d %06d.%03d %01u %p\n",
mCommand,
(int)ns2s(mTime),
(int)ns2ms(mTime)%1000,
mWaitStatus,
mParam);
}
/******* helpers for the service_ops callbacks defined below *********/
void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
const char *keyValuePairs,
int delayMs)
{
mAudioCommandThread->parametersCommand(ioHandle, keyValuePairs,
delayMs);
}
int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
float volume,
audio_io_handle_t output,
int delayMs)
{
return (int)mAudioCommandThread->volumeCommand(stream, volume,
output, delayMs);
}
int AudioPolicyService::startTone(audio_policy_tone_t tone,
audio_stream_type_t stream)
{
if (tone != AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION)
ALOGE("startTone: illegal tone requested (%d)", tone);
if (stream != AUDIO_STREAM_VOICE_CALL)
ALOGE("startTone: illegal stream (%d) requested for tone %d", stream,
tone);
mTonePlaybackThread->startToneCommand(ToneGenerator::TONE_SUP_CALL_WAITING,
AUDIO_STREAM_VOICE_CALL);
return 0;
}
int AudioPolicyService::stopTone()
{
mTonePlaybackThread->stopToneCommand();
return 0;
}
int AudioPolicyService::setVoiceVolume(float volume, int delayMs)
{
return (int)mAudioCommandThread->voiceVolumeCommand(volume, delayMs);
}
// ----------------------------------------------------------------------------
// Audio pre-processing configuration
// ----------------------------------------------------------------------------
/*static*/ const char * const AudioPolicyService::kInputSourceNames[AUDIO_SOURCE_CNT -1] = {
MIC_SRC_TAG,
VOICE_UL_SRC_TAG,
VOICE_DL_SRC_TAG,
VOICE_CALL_SRC_TAG,
CAMCORDER_SRC_TAG,
VOICE_REC_SRC_TAG,
VOICE_COMM_SRC_TAG
};
// returns the audio_source_t enum corresponding to the input source name or
// AUDIO_SOURCE_CNT is no match found
audio_source_t AudioPolicyService::inputSourceNameToEnum(const char *name)
{
int i;
for (i = AUDIO_SOURCE_MIC; i < AUDIO_SOURCE_CNT; i++) {
if (strcmp(name, kInputSourceNames[i - AUDIO_SOURCE_MIC]) == 0) {
ALOGV("inputSourceNameToEnum found source %s %d", name, i);
break;
}
}
return (audio_source_t)i;
}
size_t AudioPolicyService::growParamSize(char *param,
size_t size,
size_t *curSize,
size_t *totSize)
{
// *curSize is at least sizeof(effect_param_t) + 2 * sizeof(int)
size_t pos = ((*curSize - 1 ) / size + 1) * size;
if (pos + size > *totSize) {
while (pos + size > *totSize) {
*totSize += ((*totSize + 7) / 8) * 4;
}
param = (char *)realloc(param, *totSize);
}
*curSize = pos + size;
return pos;
}
size_t AudioPolicyService::readParamValue(cnode *node,
char *param,
size_t *curSize,
size_t *totSize)
{
if (strncmp(node->name, SHORT_TAG, sizeof(SHORT_TAG) + 1) == 0) {
size_t pos = growParamSize(param, sizeof(short), curSize, totSize);
*(short *)((char *)param + pos) = (short)atoi(node->value);
ALOGV("readParamValue() reading short %d", *(short *)((char *)param + pos));
return sizeof(short);
} else if (strncmp(node->name, INT_TAG, sizeof(INT_TAG) + 1) == 0) {
size_t pos = growParamSize(param, sizeof(int), curSize, totSize);
*(int *)((char *)param + pos) = atoi(node->value);
ALOGV("readParamValue() reading int %d", *(int *)((char *)param + pos));
return sizeof(int);
} else if (strncmp(node->name, FLOAT_TAG, sizeof(FLOAT_TAG) + 1) == 0) {
size_t pos = growParamSize(param, sizeof(float), curSize, totSize);
*(float *)((char *)param + pos) = (float)atof(node->value);
ALOGV("readParamValue() reading float %f",*(float *)((char *)param + pos));
return sizeof(float);
} else if (strncmp(node->name, BOOL_TAG, sizeof(BOOL_TAG) + 1) == 0) {
size_t pos = growParamSize(param, sizeof(bool), curSize, totSize);
if (strncmp(node->value, "false", strlen("false") + 1) == 0) {
*(bool *)((char *)param + pos) = false;
} else {
*(bool *)((char *)param + pos) = true;
}
ALOGV("readParamValue() reading bool %s",*(bool *)((char *)param + pos) ? "true" : "false");
return sizeof(bool);
} else if (strncmp(node->name, STRING_TAG, sizeof(STRING_TAG) + 1) == 0) {
size_t len = strnlen(node->value, EFFECT_STRING_LEN_MAX);
if (*curSize + len + 1 > *totSize) {
*totSize = *curSize + len + 1;
param = (char *)realloc(param, *totSize);
}
strncpy(param + *curSize, node->value, len);
*curSize += len;
param[*curSize] = '\0';
ALOGV("readParamValue() reading string %s", param + *curSize - len);
return len;
}
ALOGW("readParamValue() unknown param type %s", node->name);
return 0;
}
effect_param_t *AudioPolicyService::loadEffectParameter(cnode *root)
{
cnode *param;
cnode *value;
size_t curSize = sizeof(effect_param_t);
size_t totSize = sizeof(effect_param_t) + 2 * sizeof(int);
effect_param_t *fx_param = (effect_param_t *)malloc(totSize);
param = config_find(root, PARAM_TAG);
value = config_find(root, VALUE_TAG);
if (param == NULL && value == NULL) {
// try to parse simple parameter form {int int}
param = root->first_child;
if (param != NULL) {
// Note: that a pair of random strings is read as 0 0
int *ptr = (int *)fx_param->data;
int *ptr2 = (int *)((char *)param + sizeof(effect_param_t));
ALOGW("loadEffectParameter() ptr %p ptr2 %p", ptr, ptr2);
*ptr++ = atoi(param->name);
*ptr = atoi(param->value);
fx_param->psize = sizeof(int);
fx_param->vsize = sizeof(int);
return fx_param;
}
}
if (param == NULL || value == NULL) {
ALOGW("loadEffectParameter() invalid parameter description %s", root->name);
goto error;
}
fx_param->psize = 0;
param = param->first_child;
while (param) {
ALOGV("loadEffectParameter() reading param of type %s", param->name);
size_t size = readParamValue(param, (char *)fx_param, &curSize, &totSize);
if (size == 0) {
goto error;
}
fx_param->psize += size;
param = param->next;
}
// align start of value field on 32 bit boundary
curSize = ((curSize - 1 ) / sizeof(int) + 1) * sizeof(int);
fx_param->vsize = 0;
value = value->first_child;
while (value) {
ALOGV("loadEffectParameter() reading value of type %s", value->name);
size_t size = readParamValue(value, (char *)fx_param, &curSize, &totSize);
if (size == 0) {
goto error;
}
fx_param->vsize += size;
value = value->next;
}
return fx_param;
error:
delete fx_param;
return NULL;
}
void AudioPolicyService::loadEffectParameters(cnode *root, Vector <effect_param_t *>& params)
{
cnode *node = root->first_child;
while (node) {
ALOGV("loadEffectParameters() loading param %s", node->name);
effect_param_t *param = loadEffectParameter(node);
if (param == NULL) {
node = node->next;
continue;
}
params.add(param);
node = node->next;
}
}
AudioPolicyService::InputSourceDesc *AudioPolicyService::loadInputSource(
cnode *root,
const Vector <EffectDesc *>& effects)
{
cnode *node = root->first_child;
if (node == NULL) {
ALOGW("loadInputSource() empty element %s", root->name);
return NULL;
}
InputSourceDesc *source = new InputSourceDesc();
while (node) {
size_t i;
for (i = 0; i < effects.size(); i++) {
if (strncmp(effects[i]->mName, node->name, EFFECT_STRING_LEN_MAX) == 0) {
ALOGV("loadInputSource() found effect %s in list", node->name);
break;
}
}
if (i == effects.size()) {
ALOGV("loadInputSource() effect %s not in list", node->name);
node = node->next;
continue;
}
EffectDesc *effect = new EffectDesc(*effects[i]); // deep copy
loadEffectParameters(node, effect->mParams);
ALOGV("loadInputSource() adding effect %s uuid %08x", effect->mName, effect->mUuid.timeLow);
source->mEffects.add(effect);
node = node->next;
}
if (source->mEffects.size() == 0) {
ALOGW("loadInputSource() no valid effects found in source %s", root->name);
delete source;
return NULL;
}
return source;
}
status_t AudioPolicyService::loadInputSources(cnode *root, const Vector <EffectDesc *>& effects)
{
cnode *node = config_find(root, PREPROCESSING_TAG);
if (node == NULL) {
return -ENOENT;
}
node = node->first_child;
while (node) {
audio_source_t source = inputSourceNameToEnum(node->name);
if (source == AUDIO_SOURCE_CNT) {
ALOGW("loadInputSources() invalid input source %s", node->name);
node = node->next;
continue;
}
ALOGV("loadInputSources() loading input source %s", node->name);
InputSourceDesc *desc = loadInputSource(node, effects);
if (desc == NULL) {
node = node->next;
continue;
}
mInputSources.add(source, desc);
node = node->next;
}
return NO_ERROR;
}
AudioPolicyService::EffectDesc *AudioPolicyService::loadEffect(cnode *root)
{
cnode *node = config_find(root, UUID_TAG);
if (node == NULL) {
return NULL;
}
effect_uuid_t uuid;
if (AudioEffect::stringToGuid(node->value, &uuid) != NO_ERROR) {
ALOGW("loadEffect() invalid uuid %s", node->value);
return NULL;
}
return new EffectDesc(root->name, uuid);
}
status_t AudioPolicyService::loadEffects(cnode *root, Vector <EffectDesc *>& effects)
{
cnode *node = config_find(root, EFFECTS_TAG);
if (node == NULL) {
return -ENOENT;
}
node = node->first_child;
while (node) {
ALOGV("loadEffects() loading effect %s", node->name);
EffectDesc *effect = loadEffect(node);
if (effect == NULL) {
node = node->next;
continue;
}
effects.add(effect);
node = node->next;
}
return NO_ERROR;
}
status_t AudioPolicyService::loadPreProcessorConfig(const char *path)
{
cnode *root;
char *data;
data = (char *)load_file(path, NULL);
if (data == NULL) {
return -ENODEV;
}
root = config_node("", "");
config_load(root, data);
Vector <EffectDesc *> effects;
loadEffects(root, effects);
loadInputSources(root, effects);
config_free(root);
free(root);
free(data);
return NO_ERROR;
}
/* implementation of the interface to the policy manager */
extern "C" {
static audio_module_handle_t aps_load_hw_module(void *service,
const char *name)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0) {
ALOGW("%s: could not get AudioFlinger", __func__);
return 0;
}
return af->loadHwModule(name);
}
// deprecated: replaced by aps_open_output_on_module()
static audio_io_handle_t aps_open_output(void *service,
audio_devices_t *pDevices,
uint32_t *pSamplingRate,
audio_format_t *pFormat,
audio_channel_mask_t *pChannelMask,
uint32_t *pLatencyMs,
audio_output_flags_t flags)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0) {
ALOGW("%s: could not get AudioFlinger", __func__);
return 0;
}
return af->openOutput((audio_module_handle_t)0, pDevices, pSamplingRate, pFormat, pChannelMask,
pLatencyMs, flags);
}
static audio_io_handle_t aps_open_output_on_module(void *service,
audio_module_handle_t module,
audio_devices_t *pDevices,
uint32_t *pSamplingRate,
audio_format_t *pFormat,
audio_channel_mask_t *pChannelMask,
uint32_t *pLatencyMs,
audio_output_flags_t flags)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0) {
ALOGW("%s: could not get AudioFlinger", __func__);
return 0;
}
return af->openOutput(module, pDevices, pSamplingRate, pFormat, pChannelMask,
pLatencyMs, flags);
}
static audio_io_handle_t aps_open_dup_output(void *service,
audio_io_handle_t output1,
audio_io_handle_t output2)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0) {
ALOGW("%s: could not get AudioFlinger", __func__);
return 0;
}
return af->openDuplicateOutput(output1, output2);
}
static int aps_close_output(void *service, audio_io_handle_t output)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0)
return PERMISSION_DENIED;
return af->closeOutput(output);
}
static int aps_suspend_output(void *service, audio_io_handle_t output)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0) {
ALOGW("%s: could not get AudioFlinger", __func__);
return PERMISSION_DENIED;
}
return af->suspendOutput(output);
}
static int aps_restore_output(void *service, audio_io_handle_t output)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0) {
ALOGW("%s: could not get AudioFlinger", __func__);
return PERMISSION_DENIED;
}
return af->restoreOutput(output);
}
// deprecated: replaced by aps_open_input_on_module(), and acoustics parameter is ignored
static audio_io_handle_t aps_open_input(void *service,
audio_devices_t *pDevices,
uint32_t *pSamplingRate,
audio_format_t *pFormat,
audio_channel_mask_t *pChannelMask,
audio_in_acoustics_t acoustics)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0) {
ALOGW("%s: could not get AudioFlinger", __func__);
return 0;
}
return af->openInput((audio_module_handle_t)0, pDevices, pSamplingRate, pFormat, pChannelMask);
}
static audio_io_handle_t aps_open_input_on_module(void *service,
audio_module_handle_t module,
audio_devices_t *pDevices,
uint32_t *pSamplingRate,
audio_format_t *pFormat,
audio_channel_mask_t *pChannelMask)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0) {
ALOGW("%s: could not get AudioFlinger", __func__);
return 0;
}
return af->openInput(module, pDevices, pSamplingRate, pFormat, pChannelMask);
}
static int aps_close_input(void *service, audio_io_handle_t input)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0)
return PERMISSION_DENIED;
return af->closeInput(input);
}
static int aps_set_stream_output(void *service, audio_stream_type_t stream,
audio_io_handle_t output)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0)
return PERMISSION_DENIED;
return af->setStreamOutput(stream, output);
}
static int aps_move_effects(void *service, int session,
audio_io_handle_t src_output,
audio_io_handle_t dst_output)
{
sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
if (af == 0)
return PERMISSION_DENIED;
return af->moveEffects(session, src_output, dst_output);
}
static char * aps_get_parameters(void *service, audio_io_handle_t io_handle,
const char *keys)
{
String8 result = AudioSystem::getParameters(io_handle, String8(keys));
return strdup(result.string());
}
static void aps_set_parameters(void *service, audio_io_handle_t io_handle,
const char *kv_pairs, int delay_ms)
{
AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
audioPolicyService->setParameters(io_handle, kv_pairs, delay_ms);
}
static int aps_set_stream_volume(void *service, audio_stream_type_t stream,
float volume, audio_io_handle_t output,
int delay_ms)
{
AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
return audioPolicyService->setStreamVolume(stream, volume, output,
delay_ms);
}
static int aps_start_tone(void *service, audio_policy_tone_t tone,
audio_stream_type_t stream)
{
AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
return audioPolicyService->startTone(tone, stream);
}
static int aps_stop_tone(void *service)
{
AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
return audioPolicyService->stopTone();
}
static int aps_set_voice_volume(void *service, float volume, int delay_ms)
{
AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
return audioPolicyService->setVoiceVolume(volume, delay_ms);
}
}; // extern "C"
namespace {
struct audio_policy_service_ops aps_ops = {
open_output : aps_open_output,
open_duplicate_output : aps_open_dup_output,
close_output : aps_close_output,
suspend_output : aps_suspend_output,
restore_output : aps_restore_output,
open_input : aps_open_input,
close_input : aps_close_input,
set_stream_volume : aps_set_stream_volume,
set_stream_output : aps_set_stream_output,
set_parameters : aps_set_parameters,
get_parameters : aps_get_parameters,
start_tone : aps_start_tone,
stop_tone : aps_stop_tone,
set_voice_volume : aps_set_voice_volume,
move_effects : aps_move_effects,
load_hw_module : aps_load_hw_module,
open_output_on_module : aps_open_output_on_module,
open_input_on_module : aps_open_input_on_module,
};
}; // namespace <unnamed>
}; // namespace android
|
gpl-2.0
|
yngfng/LightYears_craft
|
code/quiet_season.py
|
561
|
#
# 20,000 Light Years Into Space
# This game is licensed under GPL v2, and copyright (C) Jack Whitham 2006.
#
class Quiet_Season:
# The quiet season is... very quiet.
def __init__(self, net):
self.net = net
self.name = "Quiet"
def Per_Frame(self, frame_time):
pass
def Per_Period(self):
pass
def Draw(self, output, update_area):
pass
def Get_Period(self):
return 10
def Get_Extra_Info(self):
return []
def Is_Shaking(self):
return False
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.