code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// --------------------------------------------------------------------- // // Copyright (C) 2004 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // test the PETSc CG solver #include "../tests.h" #include "../testmatrix.h" #include <cmath> #include <fstream> #include <iostream> #include <iomanip> #include <deal.II/base/logstream.h> #include <deal.II/lac/petsc_sparse_matrix.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_solver.h> #include <deal.II/lac/petsc_precondition.h> #include <deal.II/lac/vector_memory.h> #include <typeinfo> template<typename SolverType, typename MatrixType, typename VectorType, class PRECONDITION> void check_solve(SolverType &solver, const SolverControl &solver_control, const MatrixType &A, VectorType &u, VectorType &f, const PRECONDITION &P) { deallog << "Solver type: " << typeid(solver).name() << std::endl; u = 0.; f = 1.; try { solver.solve(A,u,f,P); } catch (std::exception &e) { deallog << e.what() << std::endl; abort (); } deallog << "Solver stopped after " << solver_control.last_step() << " iterations" << std::endl; } int main(int argc, char **argv) { std::ofstream logfile("output"); deallog.attach(logfile); deallog << std::setprecision(4); deallog.threshold_double(1.e-10); Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1); { SolverControl control(100, 1.e-3); const unsigned int size = 32; unsigned int dim = (size-1)*(size-1); deallog << "Size " << size << " Unknowns " << dim << std::endl; // Make matrix FDMatrix testproblem(size, size); PETScWrappers::SparseMatrix A(dim, dim, 5); testproblem.five_point(A); PETScWrappers::Vector f(dim); PETScWrappers::Vector u(dim); f = 1.; A.compress (VectorOperation::insert); PETScWrappers::SolverCG solver(control); PETScWrappers::PreconditionSOR preconditioner(A); check_solve (solver, control, A,u,f, preconditioner); } }
pesser/dealii
tests/petsc/solver_03_precondition_sor.cc
C++
lgpl-2.1
2,597
package org.herac.tuxguitar.gui.util; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.player.base.MidiRepeatController; import org.herac.tuxguitar.song.managers.TGSongManager; import org.herac.tuxguitar.song.models.TGMeasureHeader; public class MidiTickUtil { public static long getStart(long tick){ long startPoint = getStartPoint(); long start = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); MidiRepeatController controller = new MidiRepeatController(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ start += length; length = header.getLength(); //verifico si es el compas correcto if(tick >= start && tick < (start + length )){ return header.getStart() + (tick - start); } } } return ( tick < startPoint ? startPoint : start ); } public static long getTick(long start){ long startPoint = getStartPoint(); long tick = startPoint; long length = 0; TGSongManager manager = TuxGuitar.instance().getSongManager(); MidiRepeatController controller = new MidiRepeatController(manager.getSong(), getSHeader() , getEHeader() ); while(!controller.finished()){ TGMeasureHeader header = manager.getSong().getMeasureHeader(controller.getIndex()); controller.process(); if(controller.shouldPlay()){ tick += length; length = header.getLength(); //verifico si es el compas correcto if(start >= header.getStart() && start < (header.getStart() + length )){ return tick; } } } return ( start < startPoint ? startPoint : tick ); } private static long getStartPoint(){ TuxGuitar.instance().getPlayer().updateLoop( false ); return TuxGuitar.instance().getPlayer().getLoopSPosition(); } public static int getSHeader() { return TuxGuitar.instance().getPlayer().getLoopSHeader(); } public static int getEHeader() { return TuxGuitar.instance().getPlayer().getLoopEHeader(); } }
elkafoury/tux
src/org/herac/tuxguitar/gui/util/MidiTickUtil.java
Java
lgpl-2.1
2,150
<?php /** * @package tikiwiki */ // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: categorize.php 44444 2013-01-05 21:24:24Z changi67 $ require_once('tiki-setup.php'); $access = TikiLib::lib('access'); $access->check_script($_SERVER["SCRIPT_NAME"], basename(__FILE__)); $smarty = TikiLib::lib('smarty'); global $prefs; $catobjperms = Perms::get(array( 'type' => $cat_type, 'object' => $cat_objid )); if ($prefs['feature_categories'] == 'y' && $catobjperms->modify_object_categories ) { $categlib = TikiLib::lib('categ'); if (isset($_REQUEST['import']) and isset($_REQUEST['categories'])) { $_REQUEST["cat_categories"] = explode(',', $_REQUEST['categories']); $_REQUEST["cat_categorize"] = 'on'; } if ( !isset($_REQUEST["cat_categorize"]) || $_REQUEST["cat_categorize"] != 'on' ) { $_REQUEST['cat_categories'] = NULL; } $categlib->update_object_categories(isset($_REQUEST['cat_categories'])?$_REQUEST['cat_categories']:'', $cat_objid, $cat_type, $cat_desc, $cat_name, $cat_href, $_REQUEST['cat_managed']); }
reneejustrenee/tikiwikitest
categorize.php
PHP
lgpl-2.1
1,238
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.narayana.txframework.api.exception; /** * @deprecated The TXFramework API will be removed. The org.jboss.narayana.compensations API should be used instead. * The new API is superior for these reasons: * <p/> * i) offers a higher level API; * ii) The API very closely matches that of JTA, making it easier for developers to learn, * iii) It works for non-distributed transactions as well as distributed transactions. * iv) It is CDI based so only needs a CDI container to run, rather than a full Java EE server. * <p/> */ @Deprecated public class TXFrameworkException extends Exception { public TXFrameworkException(String message) { super(message); } public TXFrameworkException(String message, Throwable cause) { super(message, cause); } }
gytis/narayana
txframework/src/main/java/org/jboss/narayana/txframework/api/exception/TXFrameworkException.java
Java
lgpl-2.1
1,829
var classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser = [ [ "Deserialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a5e8aa7ae1372033da215d02b79947b20.html#a5e8aa7ae1372033da215d02b79947b20", null ], [ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a4aec60f5df74f482b576f4e0dad0d5f6.html#a4aec60f5df74f482b576f4e0dad0d5f6", null ], [ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a2362ae784859054bf5b9281dafeb37cd.html#a2362ae784859054bf5b9281dafeb37cd", null ], [ "ValueType", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_af5d06e2fe995f816c840a8ceefd22991.html#af5d06e2fe995f816c840a8ceefd22991", null ] ];
Chinchilla-Software-Com/CQRS
wiki/docs/2.4/html/classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser.js
JavaScript
lgpl-2.1
693
/* * JBoss, Home of Professional Open Source * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 // // Arjuna Technologies Ltd., // Newcastle upon Tyne, // Tyne and Wear, // UK. // package org.jboss.jbossts.qa.RawResources02Clients2; /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client085.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $ */ /* * Try to get around the differences between Ansi CPP and * K&R cpp with concatenation. */ /* * Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved. * * HP Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Client085.java,v 1.3 2003/07/07 13:43:32 jcoleman Exp $ */ import org.jboss.jbossts.qa.RawResources02.*; import org.jboss.jbossts.qa.Utils.OAInterface; import org.jboss.jbossts.qa.Utils.ORBInterface; import org.jboss.jbossts.qa.Utils.OTS; import org.jboss.jbossts.qa.Utils.ServerIORStore; import org.omg.CORBA.TRANSACTION_ROLLEDBACK; public class Client085 { public static void main(String[] args) { try { ORBInterface.initORB(args, null); OAInterface.initOA(); String serviceIOR1 = ServerIORStore.loadIOR(args[args.length - 2]); Service service1 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR1)); String serviceIOR2 = ServerIORStore.loadIOR(args[args.length - 1]); Service service2 = ServiceHelper.narrow(ORBInterface.orb().string_to_object(serviceIOR2)); ResourceBehavior[] resourceBehaviors1 = new ResourceBehavior[1]; resourceBehaviors1[0] = new ResourceBehavior(); resourceBehaviors1[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteRollback; resourceBehaviors1[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn; resourceBehaviors1[0].commit_behavior = CommitBehavior.CommitBehaviorReturn; resourceBehaviors1[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn; ResourceBehavior[] resourceBehaviors2 = new ResourceBehavior[1]; resourceBehaviors2[0] = new ResourceBehavior(); resourceBehaviors2[0].prepare_behavior = PrepareBehavior.PrepareBehaviorReturnVoteReadOnly; resourceBehaviors2[0].rollback_behavior = RollbackBehavior.RollbackBehaviorReturn; resourceBehaviors2[0].commit_behavior = CommitBehavior.CommitBehaviorReturn; resourceBehaviors2[0].commitonephase_behavior = CommitOnePhaseBehavior.CommitOnePhaseBehaviorReturn; boolean correct = true; OTS.current().begin(); service1.oper(resourceBehaviors1, OTS.current().get_control()); service2.oper(resourceBehaviors2, OTS.current().get_control()); try { OTS.current().commit(true); System.err.println("Commit succeeded when it shouldn't"); correct = false; } catch (TRANSACTION_ROLLEDBACK transactionRolledback) { } correct = correct && service1.is_correct() && service2.is_correct(); if (!correct) { System.err.println("service1.is_correct() or service2.is_correct() returned false"); } ResourceTrace resourceTrace1 = service1.get_resource_trace(0); ResourceTrace resourceTrace2 = service2.get_resource_trace(0); correct = correct && (resourceTrace1 == ResourceTrace.ResourceTracePrepareRollback); correct = correct && ((resourceTrace2 == ResourceTrace.ResourceTracePrepare) || (resourceTrace2 == ResourceTrace.ResourceTraceRollback)); if (correct) { System.out.println("Passed"); } else { System.out.println("Failed"); } } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); System.out.println("Failed"); } try { OAInterface.shutdownOA(); ORBInterface.shutdownORB(); } catch (Exception exception) { System.err.println("Client085.main: " + exception); exception.printStackTrace(System.err); } } }
gytis/narayana
qa/tests/src/org/jboss/jbossts/qa/RawResources02Clients2/Client085.java
Java
lgpl-2.1
4,881
package com.pi4j.io.gpio; /* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: Java Library (Core) * FILENAME : GpioPinPwm.java * * This file is part of the Pi4J project. More information about * this project can be found here: http://www.pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2015 Pi4J * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ /** * Gpio input pin interface. This interface is extension of {@link GpioPin} interface * with reading pwm values. * * @author Robert Savage (<a * href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) */ @SuppressWarnings("unused") public interface GpioPinPwm extends GpioPin { int getPwm(); }
curvejumper/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/GpioPinPwm.java
Java
lgpl-3.0
1,511
/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a full listing * of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ /* * Copyright (C) 2002, * * Arjuna Technologies Limited, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ */ package com.arjuna.wsas.tests; import com.arjuna.mw.wsas.context.Context; import com.arjuna.mw.wsas.UserActivityFactory; import com.arjuna.mw.wsas.common.GlobalId; import com.arjuna.mw.wsas.activity.Outcome; import com.arjuna.mw.wsas.activity.HLS; import com.arjuna.mw.wsas.completionstatus.CompletionStatus; import com.arjuna.mw.wsas.exceptions.*; import java.util.*; /** * @author Mark Little (mark.little@arjuna.com) * @version $Id: DemoHLS.java,v 1.2 2005/05/19 12:13:19 nmcl Exp $ * @since 1.0. */ public class DemoHLS implements HLS { private Stack<GlobalId> _id; public DemoHLS() { _id = new Stack<GlobalId>(); } /** * An activity has begun and is active on the current thread. */ public void begun () throws SystemException { try { GlobalId activityId = UserActivityFactory.userActivity().activityId(); _id.push(activityId); System.out.println("DemoHLS.begun "+activityId); } catch (Exception ex) { ex.printStackTrace(); } } /** * The current activity is completing with the specified completion status. * * @return The result of terminating the relationship of this HLS and * the current activity. */ public Outcome complete (CompletionStatus cs) throws SystemException { try { System.out.println("DemoHLS.complete ( "+cs+" ) " + UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * The activity has been suspended. How does the HLS know which activity * has been suspended? It must remember what its notion of current is. */ public void suspended () throws SystemException { System.out.println("DemoHLS.suspended"); } /** * The activity has been resumed on the current thread. */ public void resumed () throws SystemException { System.out.println("DemoHLS.resumed"); } /** * The activity has completed and is no longer active on the current * thread. */ public void completed () throws SystemException { try { System.out.println("DemoHLS.completed "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } if (!_id.isEmpty()) { _id.pop(); } } /** * The HLS name. */ public String identity () throws SystemException { return "DemoHLS"; } /** * The activity service maintains a priority ordered list of HLS * implementations. If an HLS wishes to be ordered based on priority * then it can return a non-negative value: the higher the value, * the higher the priority and hence the earlier in the list of HLSes * it will appear (and be used in). * * @return a positive value for the priority for this HLS, or zero/negative * if the order is not important. */ public int priority () throws SystemException { return 0; } /** * Return the context augmentation for this HLS, if any on the current * activity. * * @return a context object or null if no augmentation is necessary. */ public Context context () throws SystemException { if (_id.isEmpty()) { throw new SystemException("request for context when inactive"); } try { System.out.println("DemoHLS.context "+ UserActivityFactory.userActivity().activityId()); } catch (Exception ex) { ex.printStackTrace(); } return new DemoSOAPContextImple(identity() + "_" + _id.size()); } }
nmcl/scratch
graalvm/transactions/fork/narayana/XTS/localjunit/unit/src/test/java/com/arjuna/wsas/tests/DemoHLS.java
Java
apache-2.0
4,846
//// [privateIdentifierChain.1.ts] class A { a?: A #b?: A; getA(): A { return new A(); } constructor() { this?.#b; // Error this?.a.#b; // Error this?.getA().#b; // Error } } //// [privateIdentifierChain.1.js] "use strict"; class A { constructor() { this?.#b; // Error this?.a.#b; // Error this?.getA().#b; // Error } #b; getA() { return new A(); } }
Microsoft/TypeScript
tests/baselines/reference/privateIdentifierChain.1.js
JavaScript
apache-2.0
498
// @allowjs: true // @checkjs: true // @noemit: true // @strict: true // @filename: thisPropertyAssignmentComputed.js this["a" + "b"] = 0
Microsoft/TypeScript
tests/cases/conformance/salsa/thisPropertyAssignmentComputed.ts
TypeScript
apache-2.0
138
/* * 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. */ package org.apache.kylin.metadata.tool; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.common.util.HiveClient; import org.apache.kylin.metadata.MetadataConstants; import org.apache.kylin.metadata.MetadataManager; import org.apache.kylin.metadata.model.ColumnDesc; import org.apache.kylin.metadata.model.TableDesc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; /** * Management class to sync hive table metadata with command See main method for * how to use the class * * @author jianliu */ public class HiveSourceTableLoader { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(HiveSourceTableLoader.class); public static final String OUTPUT_SURFIX = "json"; public static final String TABLE_FOLDER_NAME = "table"; public static final String TABLE_EXD_FOLDER_NAME = "table_exd"; public static Set<String> reloadHiveTables(String[] hiveTables, KylinConfig config) throws IOException { Map<String, Set<String>> db2tables = Maps.newHashMap(); for (String table : hiveTables) { String[] parts = HadoopUtil.parseHiveTableName(table); Set<String> set = db2tables.get(parts[0]); if (set == null) { set = Sets.newHashSet(); db2tables.put(parts[0], set); } set.add(parts[1]); } // extract from hive Set<String> loadedTables = Sets.newHashSet(); for (String database : db2tables.keySet()) { List<String> loaded = extractHiveTables(database, db2tables.get(database), config); loadedTables.addAll(loaded); } return loadedTables; } private static List<String> extractHiveTables(String database, Set<String> tables, KylinConfig config) throws IOException { List<String> loadedTables = Lists.newArrayList(); MetadataManager metaMgr = MetadataManager.getInstance(KylinConfig.getInstanceFromEnv()); for (String tableName : tables) { Table table = null; HiveClient hiveClient = new HiveClient(); List<FieldSchema> partitionFields = null; List<FieldSchema> fields = null; try { table = hiveClient.getHiveTable(database, tableName); partitionFields = table.getPartitionKeys(); fields = hiveClient.getHiveTableFields(database, tableName); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } if (fields != null && partitionFields != null && partitionFields.size() > 0) { fields.addAll(partitionFields); } long tableSize = hiveClient.getFileSizeForTable(table); long tableFileNum = hiveClient.getFileNumberForTable(table); TableDesc tableDesc = metaMgr.getTableDesc(database + "." + tableName); if (tableDesc == null) { tableDesc = new TableDesc(); tableDesc.setDatabase(database.toUpperCase()); tableDesc.setName(tableName.toUpperCase()); tableDesc.setUuid(UUID.randomUUID().toString()); tableDesc.setLastModified(0); } int columnNumber = fields.size(); List<ColumnDesc> columns = new ArrayList<ColumnDesc>(columnNumber); for (int i = 0; i < columnNumber; i++) { FieldSchema field = fields.get(i); ColumnDesc cdesc = new ColumnDesc(); cdesc.setName(field.getName().toUpperCase()); cdesc.setDatatype(field.getType()); cdesc.setId(String.valueOf(i + 1)); columns.add(cdesc); } tableDesc.setColumns(columns.toArray(new ColumnDesc[columnNumber])); StringBuffer partitionColumnString = new StringBuffer(); for (int i = 0, n = partitionFields.size(); i < n; i++) { if (i > 0) partitionColumnString.append(", "); partitionColumnString.append(partitionFields.get(i).getName().toUpperCase()); } Map<String, String> map = metaMgr.getTableDescExd(tableDesc.getIdentity()); if (map == null) { map = Maps.newHashMap(); } map.put(MetadataConstants.TABLE_EXD_TABLENAME, table.getTableName()); map.put(MetadataConstants.TABLE_EXD_LOCATION, table.getSd().getLocation()); map.put(MetadataConstants.TABLE_EXD_IF, table.getSd().getInputFormat()); map.put(MetadataConstants.TABLE_EXD_OF, table.getSd().getOutputFormat()); map.put(MetadataConstants.TABLE_EXD_OWNER, table.getOwner()); map.put(MetadataConstants.TABLE_EXD_LAT, String.valueOf(table.getLastAccessTime())); map.put(MetadataConstants.TABLE_EXD_PC, partitionColumnString.toString()); map.put(MetadataConstants.TABLE_EXD_TFS, String.valueOf(tableSize)); map.put(MetadataConstants.TABLE_EXD_TNF, String.valueOf(tableFileNum)); map.put(MetadataConstants.TABLE_EXD_PARTITIONED, Boolean.valueOf(partitionFields != null && partitionFields.size() > 0).toString()); metaMgr.saveSourceTable(tableDesc); metaMgr.saveTableExd(tableDesc.getIdentity(), map); loadedTables.add(tableDesc.getIdentity()); } return loadedTables; } }
nvoron23/Kylin
metadata/src/main/java/org/apache/kylin/metadata/tool/HiveSourceTableLoader.java
Java
apache-2.0
6,633
/******************************************************************************* * Copyright 2011 Netflix * * 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 com.netflix.astyanax.thrift.model; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.common.collect.Maps; import com.netflix.astyanax.Serializer; import com.netflix.astyanax.model.AbstractColumnList; import com.netflix.astyanax.model.Column; public class ThriftCounterColumnListImpl<C> extends AbstractColumnList<C> { private final List<org.apache.cassandra.thrift.CounterColumn> columns; private Map<C, org.apache.cassandra.thrift.CounterColumn> lookup; private final Serializer<C> colSer; public ThriftCounterColumnListImpl(List<org.apache.cassandra.thrift.CounterColumn> columns, Serializer<C> colSer) { this.columns = columns; this.colSer = colSer; } @Override public Iterator<Column<C>> iterator() { class IteratorImpl implements Iterator<Column<C>> { Iterator<org.apache.cassandra.thrift.CounterColumn> base; public IteratorImpl(Iterator<org.apache.cassandra.thrift.CounterColumn> base) { this.base = base; } @Override public boolean hasNext() { return base.hasNext(); } @Override public Column<C> next() { org.apache.cassandra.thrift.CounterColumn c = base.next(); return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public void remove() { throw new UnsupportedOperationException("Iterator is immutable"); } } return new IteratorImpl(columns.iterator()); } @Override public Column<C> getColumnByName(C columnName) { constructMap(); org.apache.cassandra.thrift.CounterColumn c = lookup.get(columnName); if (c == null) { return null; } return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public Column<C> getColumnByIndex(int idx) { org.apache.cassandra.thrift.CounterColumn c = columns.get(idx); return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c); } @Override public <C2> Column<C2> getSuperColumn(C columnName, Serializer<C2> colSer) { throw new UnsupportedOperationException("Call getCounter"); } @Override public <C2> Column<C2> getSuperColumn(int idx, Serializer<C2> colSer) { throw new UnsupportedOperationException("Call getCounter"); } @Override public boolean isEmpty() { return columns.isEmpty(); } @Override public int size() { return columns.size(); } @Override public boolean isSuperColumn() { return false; } @Override public Collection<C> getColumnNames() { constructMap(); return lookup.keySet(); } private void constructMap() { if (lookup == null) { lookup = Maps.newHashMap(); for (org.apache.cassandra.thrift.CounterColumn column : columns) { lookup.put(colSer.fromBytes(column.getName()), column); } } } }
0x6e6562/astyanax
src/main/java/com/netflix/astyanax/thrift/model/ThriftCounterColumnListImpl.java
Java
apache-2.0
3,953
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure.Commands.CloudService.Development; using Microsoft.WindowsAzure.Commands.Common.Test.Mocks; using Microsoft.WindowsAzure.Commands.Test.Utilities.CloudService; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Microsoft.WindowsAzure.Commands.Utilities.CloudService; using Xunit; namespace Microsoft.WindowsAzure.Commands.Test.CloudService.Development.Tests.Cmdlet { public class GetAzureServiceProjectRuntimesTests : TestBase { private const string serviceName = "AzureService"; MockCommandRuntime mockCommandRuntime; private GetAzureServiceProjectRoleRuntimeCommand cmdlet; public GetAzureServiceProjectRuntimesTests() { cmdlet = new GetAzureServiceProjectRoleRuntimeCommand(); mockCommandRuntime = new MockCommandRuntime(); cmdlet.CommandRuntime = mockCommandRuntime; } /// <summary> /// Verify that the correct runtimes are returned in the correct format from a given runtime manifest /// </summary> [Fact] public void TestGetRuntimes() { using (FileSystemHelper files = new FileSystemHelper(this)) { string manifest = RuntimePackageHelper.GetTestManifest(files); CloudRuntimeCollection runtimes; CloudRuntimeCollection.CreateCloudRuntimeCollection(out runtimes, manifest); cmdlet.GetAzureRuntimesProcess(string.Empty, manifest); List<CloudRuntimePackage> actual = mockCommandRuntime.OutputPipeline[0] as List<CloudRuntimePackage>; Assert.Equal<int>(runtimes.Count, actual.Count); Assert.True(runtimes.All<CloudRuntimePackage>(p => actual.Any<CloudRuntimePackage>(p2 => p2.PackageUri.Equals(p.PackageUri)))); } } } }
amarzavery/azure-powershell
src/ServiceManagement/Services/Commands.Test/CloudService/Development/GetAzureServiceProjectRuntimesTest.cs
C#
apache-2.0
2,685
/* * 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. */ /* * $Id: $ */ package org.apache.xml.serializer.dom3; import org.w3c.dom.DOMError; import org.w3c.dom.DOMLocator; /** * Implementation of the DOM Level 3 DOMError interface. * * <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ERROR-Interfaces-DOMError'>DOMError Interface definition from Document Object Model (DOM) Level 3 Core Specification</a>. * * @xsl.usage internal */ public final class DOMErrorImpl implements DOMError { /** private data members */ // The DOMError Severity private short fSeverity = DOMError.SEVERITY_WARNING; // The Error message private String fMessage = null; // A String indicating which related data is expected in relatedData. private String fType; // The platform related exception private Exception fException = null; // private Object fRelatedData; // The location of the exception private DOMLocatorImpl fLocation = new DOMLocatorImpl(); // // Constructors // /** * Default constructor. */ DOMErrorImpl () { } /** * @param severity * @param message * @param type */ public DOMErrorImpl(short severity, String message, String type) { fSeverity = severity; fMessage = message; fType = type; } /** * @param severity * @param message * @param type * @param exception */ public DOMErrorImpl(short severity, String message, String type, Exception exception) { fSeverity = severity; fMessage = message; fType = type; fException = exception; } /** * @param severity * @param message * @param type * @param exception * @param relatedData * @param location */ public DOMErrorImpl(short severity, String message, String type, Exception exception, Object relatedData, DOMLocatorImpl location) { fSeverity = severity; fMessage = message; fType = type; fException = exception; fRelatedData = relatedData; fLocation = location; } /** * The severity of the error, either <code>SEVERITY_WARNING</code>, * <code>SEVERITY_ERROR</code>, or <code>SEVERITY_FATAL_ERROR</code>. * * @return A short containing the DOMError severity */ public short getSeverity() { return fSeverity; } /** * The DOMError message string. * * @return String */ public String getMessage() { return fMessage; } /** * The location of the DOMError. * * @return A DOMLocator object containing the DOMError location. */ public DOMLocator getLocation() { return fLocation; } /** * The related platform dependent exception if any. * * @return A java.lang.Exception */ public Object getRelatedException(){ return fException; } /** * Returns a String indicating which related data is expected in relatedData. * * @return A String */ public String getType(){ return fType; } /** * The related DOMError.type dependent data if any. * * @return java.lang.Object */ public Object getRelatedData(){ return fRelatedData; } public void reset(){ fSeverity = DOMError.SEVERITY_WARNING; fException = null; fMessage = null; fType = null; fRelatedData = null; fLocation = null; } }// class DOMErrorImpl
mirego/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/serializer/dom3/DOMErrorImpl.java
Java
apache-2.0
4,503
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dfareporting.model; /** * Click-through URL * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the DCM/DFA Reporting And Trafficking API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class CreativeClickThroughUrl extends com.google.api.client.json.GenericJson { /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String computedClickThroughUrl; /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String customClickThroughUrl; /** * ID of the landing page for the click-through URL. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long landingPageId; /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * @return value or {@code null} for none */ public java.lang.String getComputedClickThroughUrl() { return computedClickThroughUrl; } /** * Read-only convenience field representing the actual URL that will be used for this click- * through. The URL is computed as follows: - If landingPageId is specified then that landing * page's URL is assigned to this field. - Otherwise, the customClickThroughUrl is assigned to * this field. * @param computedClickThroughUrl computedClickThroughUrl or {@code null} for none */ public CreativeClickThroughUrl setComputedClickThroughUrl(java.lang.String computedClickThroughUrl) { this.computedClickThroughUrl = computedClickThroughUrl; return this; } /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * @return value or {@code null} for none */ public java.lang.String getCustomClickThroughUrl() { return customClickThroughUrl; } /** * Custom click-through URL. Applicable if the landingPageId field is left unset. * @param customClickThroughUrl customClickThroughUrl or {@code null} for none */ public CreativeClickThroughUrl setCustomClickThroughUrl(java.lang.String customClickThroughUrl) { this.customClickThroughUrl = customClickThroughUrl; return this; } /** * ID of the landing page for the click-through URL. * @return value or {@code null} for none */ public java.lang.Long getLandingPageId() { return landingPageId; } /** * ID of the landing page for the click-through URL. * @param landingPageId landingPageId or {@code null} for none */ public CreativeClickThroughUrl setLandingPageId(java.lang.Long landingPageId) { this.landingPageId = landingPageId; return this; } @Override public CreativeClickThroughUrl set(String fieldName, Object value) { return (CreativeClickThroughUrl) super.set(fieldName, value); } @Override public CreativeClickThroughUrl clone() { return (CreativeClickThroughUrl) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-dfareporting/v3.4/1.29.2/com/google/api/services/dfareporting/model/CreativeClickThroughUrl.java
Java
apache-2.0
4,569
// @declaration: true // @noImplicitThis: true // https://github.com/microsoft/TypeScript/issues/29902 function createObj() { return { func1() { return this; }, func2() { return this; }, func3() { return this; } }; } function createObjNoCrash() { return { func1() { return this; }, func2() { return this; }, func3() { return this; }, func4() { return this; }, func5() { return this; }, func6() { return this; }, func7() { return this; }, func8() { return this; }, func9() { return this; } }; }
Microsoft/TypeScript
tests/cases/compiler/noImplicitThisBigThis.ts
TypeScript
apache-2.0
899
package strategy import ( "reflect" "strings" "testing" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation" kapi "k8s.io/kubernetes/pkg/api" buildapi "github.com/openshift/origin/pkg/build/api" _ "github.com/openshift/origin/pkg/build/api/install" ) func TestDockerCreateBuildPod(t *testing.T) { strategy := DockerBuildStrategy{ Image: "docker-test-image", Codec: kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion), } build := mockDockerBuild() actual, err := strategy.CreateBuildPod(build) if err != nil { t.Errorf("Unexpected error: %v", err) } if expected, actual := buildapi.GetBuildPodName(build), actual.ObjectMeta.Name; expected != actual { t.Errorf("Expected %s, but got %s!", expected, actual) } if !reflect.DeepEqual(map[string]string{buildapi.BuildLabel: buildapi.LabelValue(build.Name)}, actual.Labels) { t.Errorf("Pod Labels does not match Build Labels!") } if !reflect.DeepEqual(nodeSelector, actual.Spec.NodeSelector) { t.Errorf("Pod NodeSelector does not match Build NodeSelector. Expected: %v, got: %v", nodeSelector, actual.Spec.NodeSelector) } container := actual.Spec.Containers[0] if container.Name != "docker-build" { t.Errorf("Expected docker-build, but got %s!", container.Name) } if container.Image != strategy.Image { t.Errorf("Expected %s image, got %s!", container.Image, strategy.Image) } if container.ImagePullPolicy != kapi.PullIfNotPresent { t.Errorf("Expected %v, got %v", kapi.PullIfNotPresent, container.ImagePullPolicy) } if actual.Spec.RestartPolicy != kapi.RestartPolicyNever { t.Errorf("Expected never, got %#v", actual.Spec.RestartPolicy) } if len(container.Env) != 10 { var keys []string for _, env := range container.Env { keys = append(keys, env.Name) } t.Fatalf("Expected 10 elements in Env table, got %d:\n%s", len(container.Env), strings.Join(keys, ", ")) } if len(container.VolumeMounts) != 4 { t.Fatalf("Expected 4 volumes in container, got %d", len(container.VolumeMounts)) } if *actual.Spec.ActiveDeadlineSeconds != 60 { t.Errorf("Expected ActiveDeadlineSeconds 60, got %d", *actual.Spec.ActiveDeadlineSeconds) } for i, expected := range []string{dockerSocketPath, DockerPushSecretMountPath, DockerPullSecretMountPath, sourceSecretMountPath} { if container.VolumeMounts[i].MountPath != expected { t.Fatalf("Expected %s in VolumeMount[%d], got %s", expected, i, container.VolumeMounts[i].MountPath) } } if len(actual.Spec.Volumes) != 4 { t.Fatalf("Expected 4 volumes in Build pod, got %d", len(actual.Spec.Volumes)) } if !kapi.Semantic.DeepEqual(container.Resources, build.Spec.Resources) { t.Fatalf("Expected actual=expected, %v != %v", container.Resources, build.Spec.Resources) } found := false foundIllegal := false for _, v := range container.Env { if v.Name == "BUILD_LOGLEVEL" && v.Value == "bar" { found = true } if v.Name == "ILLEGAL" { foundIllegal = true } } if !found { t.Fatalf("Expected variable BUILD_LOGLEVEL be defined for the container") } if foundIllegal { t.Fatalf("Found illegal environment variable 'ILLEGAL' defined on container") } buildJSON, _ := runtime.Encode(kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion), build) errorCases := map[int][]string{ 0: {"BUILD", string(buildJSON)}, } for index, exp := range errorCases { if e := container.Env[index]; e.Name != exp[0] || e.Value != exp[1] { t.Errorf("Expected %s:%s, got %s:%s!\n", exp[0], exp[1], e.Name, e.Value) } } } func TestDockerBuildLongName(t *testing.T) { strategy := DockerBuildStrategy{ Image: "docker-test-image", Codec: kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion), } build := mockDockerBuild() build.Name = strings.Repeat("a", validation.DNS1123LabelMaxLength*2) pod, err := strategy.CreateBuildPod(build) if err != nil { t.Fatalf("unexpected: %v", err) } if pod.Labels[buildapi.BuildLabel] != build.Name[:validation.DNS1123LabelMaxLength] { t.Errorf("Unexpected build label value: %s", pod.Labels[buildapi.BuildLabel]) } } func mockDockerBuild() *buildapi.Build { timeout := int64(60) return &buildapi.Build{ ObjectMeta: metav1.ObjectMeta{ Name: "dockerBuild", Labels: map[string]string{ "name": "dockerBuild", }, }, Spec: buildapi.BuildSpec{ CommonSpec: buildapi.CommonSpec{ Revision: &buildapi.SourceRevision{ Git: &buildapi.GitSourceRevision{}, }, Source: buildapi.BuildSource{ Git: &buildapi.GitBuildSource{ URI: "http://my.build.com/the/dockerbuild/Dockerfile", Ref: "master", }, ContextDir: "my/test/dir", SourceSecret: &kapi.LocalObjectReference{Name: "secretFoo"}, }, Strategy: buildapi.BuildStrategy{ DockerStrategy: &buildapi.DockerBuildStrategy{ PullSecret: &kapi.LocalObjectReference{Name: "bar"}, Env: []kapi.EnvVar{ {Name: "ILLEGAL", Value: "foo"}, {Name: "BUILD_LOGLEVEL", Value: "bar"}, }, }, }, Output: buildapi.BuildOutput{ To: &kapi.ObjectReference{ Kind: "DockerImage", Name: "docker-registry/repository/dockerBuild", }, PushSecret: &kapi.LocalObjectReference{Name: "foo"}, }, Resources: kapi.ResourceRequirements{ Limits: kapi.ResourceList{ kapi.ResourceName(kapi.ResourceCPU): resource.MustParse("10"), kapi.ResourceName(kapi.ResourceMemory): resource.MustParse("10G"), }, }, CompletionDeadlineSeconds: &timeout, NodeSelector: nodeSelector, }, }, Status: buildapi.BuildStatus{ Phase: buildapi.BuildPhaseNew, }, } }
stevekuznetsov/origin
pkg/build/controller/strategy/docker_test.go
GO
apache-2.0
5,708
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2012, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file Implementation of the post processing step to calculate * tangents and bitangents for all imported meshes */ #include "AssimpPCH.h" // internal headers #include "CalcTangentsProcess.h" #include "ProcessHelper.h" #include "TinyFormatter.h" using namespace Assimp; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer CalcTangentsProcess::CalcTangentsProcess() : configMaxAngle( AI_DEG_TO_RAD(45.f) ) , configSourceUV( 0 ) { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Destructor, private as well CalcTangentsProcess::~CalcTangentsProcess() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Returns whether the processing step is present in the given flag field. bool CalcTangentsProcess::IsActive( unsigned int pFlags) const { return (pFlags & aiProcess_CalcTangentSpace) != 0; } // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. void CalcTangentsProcess::SetupProperties(const Importer* pImp) { ai_assert( NULL != pImp ); // get the current value of the property configMaxAngle = pImp->GetPropertyFloat(AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE,45.f); configMaxAngle = std::max(std::min(configMaxAngle,45.0f),0.0f); configMaxAngle = AI_DEG_TO_RAD(configMaxAngle); configSourceUV = pImp->GetPropertyInteger(AI_CONFIG_PP_CT_TEXTURE_CHANNEL_INDEX,0); } // ------------------------------------------------------------------------------------------------ // Executes the post processing step on the given imported data. void CalcTangentsProcess::Execute( aiScene* pScene) { ai_assert( NULL != pScene ); DefaultLogger::get()->debug("CalcTangentsProcess begin"); bool bHas = false; for ( unsigned int a = 0; a < pScene->mNumMeshes; a++ ) { if(ProcessMesh( pScene->mMeshes[a],a))bHas = true; } if ( bHas ) { DefaultLogger::get()->info("CalcTangentsProcess finished. Tangents have been calculated"); } else { DefaultLogger::get()->debug("CalcTangentsProcess finished"); } } // ------------------------------------------------------------------------------------------------ // Calculates tangents and bitangents for the given mesh bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) { // we assume that the mesh is still in the verbose vertex format where each face has its own set // of vertices and no vertices are shared between faces. Sadly I don't know any quick test to // assert() it here. //assert( must be verbose, dammit); if (pMesh->mTangents) // thisimplies that mBitangents is also there return false; // If the mesh consists of lines and/or points but not of // triangles or higher-order polygons the normal vectors // are undefined. if (!(pMesh->mPrimitiveTypes & (aiPrimitiveType_TRIANGLE | aiPrimitiveType_POLYGON))) { DefaultLogger::get()->info("Tangents are undefined for line and point meshes"); return false; } // what we can check, though, is if the mesh has normals and texture coordinates. That's a requirement if( pMesh->mNormals == NULL) { DefaultLogger::get()->error("Failed to compute tangents; need normals"); return false; } if( configSourceUV >= AI_MAX_NUMBER_OF_TEXTURECOORDS || !pMesh->mTextureCoords[configSourceUV] ) { DefaultLogger::get()->error((Formatter::format("Failed to compute tangents; need UV data in channel"),configSourceUV)); return false; } const float angleEpsilon = 0.9999f; std::vector<bool> vertexDone( pMesh->mNumVertices, false); const float qnan = get_qnan(); // create space for the tangents and bitangents pMesh->mTangents = new aiVector3D[pMesh->mNumVertices]; pMesh->mBitangents = new aiVector3D[pMesh->mNumVertices]; const aiVector3D* meshPos = pMesh->mVertices; const aiVector3D* meshNorm = pMesh->mNormals; const aiVector3D* meshTex = pMesh->mTextureCoords[configSourceUV]; aiVector3D* meshTang = pMesh->mTangents; aiVector3D* meshBitang = pMesh->mBitangents; // calculate the tangent and bitangent for every face for( unsigned int a = 0; a < pMesh->mNumFaces; a++) { const aiFace& face = pMesh->mFaces[a]; if (face.mNumIndices < 3) { // There are less than three indices, thus the tangent vector // is not defined. We are finished with these vertices now, // their tangent vectors are set to qnan. for (unsigned int i = 0; i < face.mNumIndices;++i) { register unsigned int idx = face.mIndices[i]; vertexDone [idx] = true; meshTang [idx] = aiVector3D(qnan); meshBitang [idx] = aiVector3D(qnan); } continue; } // triangle or polygon... we always use only the first three indices. A polygon // is supposed to be planar anyways.... // FIXME: (thom) create correct calculation for multi-vertex polygons maybe? const unsigned int p0 = face.mIndices[0], p1 = face.mIndices[1], p2 = face.mIndices[2]; // position differences p1->p2 and p1->p3 aiVector3D v = meshPos[p1] - meshPos[p0], w = meshPos[p2] - meshPos[p0]; // texture offset p1->p2 and p1->p3 float sx = meshTex[p1].x - meshTex[p0].x, sy = meshTex[p1].y - meshTex[p0].y; float tx = meshTex[p2].x - meshTex[p0].x, ty = meshTex[p2].y - meshTex[p0].y; float dirCorrection = (tx * sy - ty * sx) < 0.0f ? -1.0f : 1.0f; // when t1, t2, t3 in same position in UV space, just use default UV direction. if ( 0 == sx && 0 ==sy && 0 == tx && 0 == ty ) { sx = 0.0; sy = 1.0; tx = 1.0; ty = 0.0; } // tangent points in the direction where to positive X axis of the texture coord's would point in model space // bitangent's points along the positive Y axis of the texture coord's, respectively aiVector3D tangent, bitangent; tangent.x = (w.x * sy - v.x * ty) * dirCorrection; tangent.y = (w.y * sy - v.y * ty) * dirCorrection; tangent.z = (w.z * sy - v.z * ty) * dirCorrection; bitangent.x = (w.x * sx - v.x * tx) * dirCorrection; bitangent.y = (w.y * sx - v.y * tx) * dirCorrection; bitangent.z = (w.z * sx - v.z * tx) * dirCorrection; // store for every vertex of that face for( unsigned int b = 0; b < face.mNumIndices; ++b ) { unsigned int p = face.mIndices[b]; // project tangent and bitangent into the plane formed by the vertex' normal aiVector3D localTangent = tangent - meshNorm[p] * (tangent * meshNorm[p]); aiVector3D localBitangent = bitangent - meshNorm[p] * (bitangent * meshNorm[p]); localTangent.Normalize(); localBitangent.Normalize(); // reconstruct tangent/bitangent according to normal and bitangent/tangent when it's infinite or NaN. bool invalid_tangent = is_special_float(localTangent.x) || is_special_float(localTangent.y) || is_special_float(localTangent.z); bool invalid_bitangent = is_special_float(localBitangent.x) || is_special_float(localBitangent.y) || is_special_float(localBitangent.z); if (invalid_tangent != invalid_bitangent) { if (invalid_tangent) { localTangent = meshNorm[p] ^ localBitangent; localTangent.Normalize(); } else { localBitangent = localTangent ^ meshNorm[p]; localBitangent.Normalize(); } } // and write it into the mesh. meshTang[ p ] = localTangent; meshBitang[ p ] = localBitangent; } } // create a helper to quickly find locally close vertices among the vertex array // FIX: check whether we can reuse the SpatialSort of a previous step SpatialSort* vertexFinder = NULL; SpatialSort _vertexFinder; float posEpsilon; if (shared) { std::vector<std::pair<SpatialSort,float> >* avf; shared->GetProperty(AI_SPP_SPATIAL_SORT,avf); if (avf) { std::pair<SpatialSort,float>& blubb = avf->operator [] (meshIndex); vertexFinder = &blubb.first; posEpsilon = blubb.second;; } } if (!vertexFinder) { _vertexFinder.Fill(pMesh->mVertices, pMesh->mNumVertices, sizeof( aiVector3D)); vertexFinder = &_vertexFinder; posEpsilon = ComputePositionEpsilon(pMesh); } std::vector<unsigned int> verticesFound; const float fLimit = cosf(configMaxAngle); std::vector<unsigned int> closeVertices; // in the second pass we now smooth out all tangents and bitangents at the same local position // if they are not too far off. for( unsigned int a = 0; a < pMesh->mNumVertices; a++) { if( vertexDone[a]) continue; const aiVector3D& origPos = pMesh->mVertices[a]; const aiVector3D& origNorm = pMesh->mNormals[a]; const aiVector3D& origTang = pMesh->mTangents[a]; const aiVector3D& origBitang = pMesh->mBitangents[a]; closeVertices.clear(); // find all vertices close to that position vertexFinder->FindPositions( origPos, posEpsilon, verticesFound); closeVertices.reserve (verticesFound.size()+5); closeVertices.push_back( a); // look among them for other vertices sharing the same normal and a close-enough tangent/bitangent for( unsigned int b = 0; b < verticesFound.size(); b++) { unsigned int idx = verticesFound[b]; if( vertexDone[idx]) continue; if( meshNorm[idx] * origNorm < angleEpsilon) continue; if( meshTang[idx] * origTang < fLimit) continue; if( meshBitang[idx] * origBitang < fLimit) continue; // it's similar enough -> add it to the smoothing group closeVertices.push_back( idx); vertexDone[idx] = true; } // smooth the tangents and bitangents of all vertices that were found to be close enough aiVector3D smoothTangent( 0, 0, 0), smoothBitangent( 0, 0, 0); for( unsigned int b = 0; b < closeVertices.size(); ++b) { smoothTangent += meshTang[ closeVertices[b] ]; smoothBitangent += meshBitang[ closeVertices[b] ]; } smoothTangent.Normalize(); smoothBitangent.Normalize(); // and write it back into all affected tangents for( unsigned int b = 0; b < closeVertices.size(); ++b) { meshTang[ closeVertices[b] ] = smoothTangent; meshBitang[ closeVertices[b] ] = smoothBitangent; } } return true; }
gsi-upm/SmartSim
smartbody/src/assimp-3.1.1/code/CalcTangentsProcess.cpp
C++
apache-2.0
12,469
<?php /** * @xmlNamespace http://schema.intuit.com/finance/v3 * @xmlType string * @xmlName IPPIdType * @var IPPIdType * @xmlDefinition Product: ALL Description: Allows for strong-typing of Ids and qualifying the domain origin of the Id. The valid values for the domain are defined in the idDomainEnum. */ class IPPIdType { /** * Initializes this object, optionally with pre-defined property values * * Initializes this object and it's property members, using the dictionary * of key/value pairs passed as an optional argument. * * @param dictionary $keyValInitializers key/value pairs to be populated into object's properties * @param boolean $verbose specifies whether object should echo warnings */ public function __construct($keyValInitializers=array(), $verbose=FALSE) { foreach($keyValInitializers as $initPropName => $initPropVal) { if (property_exists('IPPIdType',$initPropName)) { $this->{$initPropName} = $initPropVal; } else { if ($verbose) echo "Property does not exist ($initPropName) in class (".get_class($this).")"; } } } /** * @xmlType value * @var string */ public $value; } // end class IPPIdType
hlu2/QuickBooks_Demo
src/Data/IPPIdType.php
PHP
apache-2.0
1,546
/// <reference path='fourslash.ts' /> //@Filename: file.tsx //// declare module JSX { //// interface Element { } //// interface IntrinsicElements { //// } //// interface ElementAttributesProperty { props } //// } //// class MyClass { //// props: { //// [|[|{| "contextRangeIndex": 0 |}name|]?: string;|] //// size?: number; //// } //// //// //// var x = <MyClass [|[|{| "contextRangeIndex": 2 |}name|]='hello'|]/>; verify.rangesWithSameTextAreRenameLocations("name");
Microsoft/TypeScript
tests/cases/fourslash/tsxRename3.ts
TypeScript
apache-2.0
515
/* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.neural.pattern; import java.util.ArrayList; import java.util.List; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ml.MLMethod; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.networks.layers.BasicLayer; import org.encog.neural.networks.layers.Layer; /** * Used to create feedforward neural networks. A feedforward network has an * input and output layers separated by zero or more hidden layers. The * feedforward neural network is one of the most common neural network patterns. * * @author jheaton * */ public class FeedForwardPattern implements NeuralNetworkPattern { /** * The number of input neurons. */ private int inputNeurons; /** * The number of output neurons. */ private int outputNeurons; /** * The activation function. */ private ActivationFunction activationHidden; /** * The activation function. */ private ActivationFunction activationOutput; /** * The number of hidden neurons. */ private final List<Integer> hidden = new ArrayList<Integer>(); /** * Add a hidden layer, with the specified number of neurons. * * @param count * The number of neurons to add. */ public void addHiddenLayer(final int count) { this.hidden.add(count); } /** * Clear out any hidden neurons. */ public void clear() { this.hidden.clear(); } /** * Generate the feedforward neural network. * * @return The feedforward neural network. */ public MLMethod generate() { if( this.activationOutput==null ) this.activationOutput = this.activationHidden; final Layer input = new BasicLayer(null, true, this.inputNeurons); final BasicNetwork result = new BasicNetwork(); result.addLayer(input); for (final Integer count : this.hidden) { final Layer hidden = new BasicLayer(this.activationHidden, true, count); result.addLayer(hidden); } final Layer output = new BasicLayer(this.activationOutput, false, this.outputNeurons); result.addLayer(output); result.getStructure().finalizeStructure(); result.reset(); return result; } /** * Set the activation function to use on each of the layers. * * @param activation * The activation function. */ public void setActivationFunction(final ActivationFunction activation) { this.activationHidden = activation; } /** * Set the number of input neurons. * * @param count * Neuron count. */ public void setInputNeurons(final int count) { this.inputNeurons = count; } /** * Set the number of output neurons. * * @param count * Neuron count. */ public void setOutputNeurons(final int count) { this.outputNeurons = count; } /** * @return the activationOutput */ public ActivationFunction getActivationOutput() { return activationOutput; } /** * @param activationOutput the activationOutput to set */ public void setActivationOutput(ActivationFunction activationOutput) { this.activationOutput = activationOutput; } }
Crespo911/encog-java-core
src/main/java/org/encog/neural/pattern/FeedForwardPattern.java
Java
apache-2.0
3,936
// Copyright 2014 The Bazel Authors. All rights reserved. // // 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 net.starlark.java.syntax; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; /** Syntax node for a for loop statement, {@code for vars in iterable: ...}. */ public final class ForStatement extends Statement { private final int forOffset; private final Expression vars; private final Expression iterable; private final ImmutableList<Statement> body; // non-empty if well formed /** Constructs a for loop statement. */ ForStatement( FileLocations locs, int forOffset, Expression vars, Expression iterable, ImmutableList<Statement> body) { super(locs); this.forOffset = forOffset; this.vars = Preconditions.checkNotNull(vars); this.iterable = Preconditions.checkNotNull(iterable); this.body = body; } /** * Returns variables assigned by each iteration. May be a compound target such as {@code (a[b], * c.d)}. */ public Expression getVars() { return vars; } /** Returns the iterable value. */ // TODO(adonovan): rename to getIterable. public Expression getCollection() { return iterable; } /** Returns the statements of the loop body. Non-empty if parsing succeeded. */ public ImmutableList<Statement> getBody() { return body; } @Override public int getStartOffset() { return forOffset; } @Override public int getEndOffset() { return body.isEmpty() ? iterable.getEndOffset() // wrong, but tree is ill formed : body.get(body.size() - 1).getEndOffset(); } @Override public String toString() { return "for " + vars + " in " + iterable + ": ...\n"; } @Override public void accept(NodeVisitor visitor) { visitor.visit(this); } @Override public Kind kind() { return Kind.FOR; } }
twitter-forks/bazel
src/main/java/net/starlark/java/syntax/ForStatement.java
Java
apache-2.0
2,418
package de.j4velin.pedometer.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class ColorPreview extends View { private Paint paint = new Paint(); private int color; public ColorPreview(Context context) { super(context); } public ColorPreview(Context context, AttributeSet attrs) { super(context, attrs); } public ColorPreview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setColor(final int c) { color = c; invalidate(); } @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); paint.setColor(color); paint.setStyle(Paint.Style.FILL); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2, paint); paint.setColor(Color.BLACK); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2 - 1, paint); } }
hgl888/Pedometer
src/main/java/de/j4velin/pedometer/util/ColorPreview.java
Java
apache-2.0
1,251
/* * Copyright (C) 2009-2017 Lightbend Inc. <https://www.lightbend.com> */ package javaguide.xml; import org.w3c.dom.Document; import play.libs.XPath; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; public class JavaXmlRequests extends Controller { //#xml-hello public Result sayHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello //#xml-hello-bodyparser @BodyParser.Of(BodyParser.Xml.class) public Result sayHelloBP() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("Missing parameter [name]"); } else { return ok("Hello " + name); } } } //#xml-hello-bodyparser //#xml-reply @BodyParser.Of(BodyParser.Xml.class) public Result replyHello() { Document dom = request().body().asXml(); if (dom == null) { return badRequest("Expecting Xml data"); } else { String name = XPath.selectText("//name", dom); if (name == null) { return badRequest("<message \"status\"=\"KO\">Missing parameter [name]</message>").as("application/xml"); } else { return ok("<message \"status\"=\"OK\">Hello " + name + "</message>").as("application/xml"); } } } //#xml-reply }
wsargent/playframework
documentation/manual/working/javaGuide/main/xml/code/javaguide/xml/JavaXmlRequests.java
Java
apache-2.0
1,900
/* * 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. */ package org.apache.druid.indexer; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.io.IOUtils; import org.apache.druid.common.utils.UUIDUtils; import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.IOE; import org.apache.druid.java.util.common.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.MRJobConfig; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class HdfsClasspathSetupTest { private static MiniDFSCluster miniCluster; private static File hdfsTmpDir; private static Configuration conf; private static String dummyJarString = "This is a test jar file."; private File dummyJarFile; private Path finalClasspath; private Path intermediatePath; @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @BeforeClass public static void setupStatic() throws IOException { hdfsTmpDir = File.createTempFile("hdfsClasspathSetupTest", "dir"); if (!hdfsTmpDir.delete()) { throw new IOE("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath()); } conf = new Configuration(true); conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath()); miniCluster = new MiniDFSCluster.Builder(conf).build(); } @Before public void setUp() throws IOException { // intermedatePath and finalClasspath are relative to hdfsTmpDir directory. intermediatePath = new Path(StringUtils.format("/tmp/classpath/%s", UUIDUtils.generateUuid())); finalClasspath = new Path(StringUtils.format("/tmp/intermediate/%s", UUIDUtils.generateUuid())); dummyJarFile = tempFolder.newFile("dummy-test.jar"); Files.copy( new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(), StandardCopyOption.REPLACE_EXISTING ); } @AfterClass public static void tearDownStatic() throws IOException { if (miniCluster != null) { miniCluster.shutdown(true); } FileUtils.deleteDirectory(hdfsTmpDir); } @After public void tearDown() throws IOException { dummyJarFile.delete(); Assert.assertFalse(dummyJarFile.exists()); miniCluster.getFileSystem().delete(finalClasspath, true); Assert.assertFalse(miniCluster.getFileSystem().exists(finalClasspath)); miniCluster.getFileSystem().delete(intermediatePath, true); Assert.assertFalse(miniCluster.getFileSystem().exists(intermediatePath)); } @Test public void testAddSnapshotJarToClasspath() throws IOException { Job job = Job.getInstance(conf, "test-job"); DistributedFileSystem fs = miniCluster.getFileSystem(); Path intermediatePath = new Path("/tmp/classpath"); JobHelper.addSnapshotJarToClassPath(dummyJarFile, intermediatePath, fs, job); Path expectedJarPath = new Path(intermediatePath, dummyJarFile.getName()); // check file gets uploaded to HDFS Assert.assertTrue(fs.exists(expectedJarPath)); // check file gets added to the classpath Assert.assertEquals(expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES)); Assert.assertEquals(dummyJarString, StringUtils.fromUtf8(IOUtils.toByteArray(fs.open(expectedJarPath)))); } @Test public void testAddNonSnapshotJarToClasspath() throws IOException { Job job = Job.getInstance(conf, "test-job"); DistributedFileSystem fs = miniCluster.getFileSystem(); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePath, fs, job); Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); // check file gets uploaded to final HDFS path Assert.assertTrue(fs.exists(expectedJarPath)); // check that the intermediate file gets deleted Assert.assertFalse(fs.exists(new Path(intermediatePath, dummyJarFile.getName()))); // check file gets added to the classpath Assert.assertEquals(expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES)); Assert.assertEquals(dummyJarString, StringUtils.fromUtf8(IOUtils.toByteArray(fs.open(expectedJarPath)))); } @Test public void testIsSnapshot() { Assert.assertTrue(JobHelper.isSnapshot(new File("test-SNAPSHOT.jar"))); Assert.assertTrue(JobHelper.isSnapshot(new File("test-SNAPSHOT-selfcontained.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("test.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("test-selfcontained.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("iAmNotSNAPSHOT.jar"))); Assert.assertFalse(JobHelper.isSnapshot(new File("iAmNotSNAPSHOT-selfcontained.jar"))); } @Test public void testConcurrentUpload() throws IOException, InterruptedException, ExecutionException, TimeoutException { final int concurrency = 10; ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(concurrency)); // barrier ensures that all jobs try to add files to classpath at same time. final CyclicBarrier barrier = new CyclicBarrier(concurrency); final DistributedFileSystem fs = miniCluster.getFileSystem(); final Path expectedJarPath = new Path(finalClasspath, dummyJarFile.getName()); List<ListenableFuture<Boolean>> futures = new ArrayList<>(); for (int i = 0; i < concurrency; i++) { futures.add( pool.submit( new Callable() { @Override public Boolean call() throws Exception { int id = barrier.await(); Job job = Job.getInstance(conf, "test-job-" + id); Path intermediatePathForJob = new Path(intermediatePath, "job-" + id); JobHelper.addJarToClassPath(dummyJarFile, finalClasspath, intermediatePathForJob, fs, job); // check file gets uploaded to final HDFS path Assert.assertTrue(fs.exists(expectedJarPath)); // check that the intermediate file is not present Assert.assertFalse(fs.exists(new Path(intermediatePathForJob, dummyJarFile.getName()))); // check file gets added to the classpath Assert.assertEquals( expectedJarPath.toString(), job.getConfiguration().get(MRJobConfig.CLASSPATH_FILES) ); return true; } } ) ); } Futures.allAsList(futures).get(30, TimeUnit.SECONDS); pool.shutdownNow(); } }
pjain1/druid
indexing-hadoop/src/test/java/org/apache/druid/indexer/HdfsClasspathSetupTest.java
Java
apache-2.0
8,361
from click_plugins import with_plugins from pkg_resources import iter_entry_points import click @with_plugins(iter_entry_points('girder.cli_plugins')) @click.group(help='Girder: data management platform for the web.', context_settings=dict(help_option_names=['-h', '--help'])) @click.version_option(message='%(version)s') def main(): pass
manthey/girder
girder/cli/__init__.py
Python
apache-2.0
358
/* * 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. */ package org.apache.twill.internal; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.apache.twill.internal.state.Message; import org.apache.twill.internal.state.MessageCodec; import org.apache.twill.zookeeper.ZKClient; import org.apache.twill.zookeeper.ZKOperations; import org.apache.zookeeper.CreateMode; /** * Helper class to send messages to remote instances using Apache Zookeeper watch mechanism. */ public final class ZKMessages { /** * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node. * * @param zkClient The ZooKeeper client for interacting with ZooKeeper. * @param messagePathPrefix ZooKeeper path prefix for the message node. * @param message The {@link Message} object for the content of the message node. * @param completionResult Object to set to the result future when the message is processed. * @param <V> Type of the completion result. * @return A {@link ListenableFuture} that will be completed when the message is consumed, which indicated * by deletion of the node. If there is exception during the process, it will be reflected * to the future returned. */ public static <V> ListenableFuture<V> sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message, final V completionResult) { SettableFuture<V> result = SettableFuture.create(); sendMessage(zkClient, messagePathPrefix, message, result, completionResult); return result; } /** * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node. * * @param zkClient The ZooKeeper client for interacting with ZooKeeper. * @param messagePathPrefix ZooKeeper path prefix for the message node. * @param message The {@link Message} object for the content of the message node. * @param completion A {@link SettableFuture} to reflect the result of message process completion. * @param completionResult Object to set to the result future when the message is processed. * @param <V> Type of the completion result. */ public static <V> void sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message, final SettableFuture<V> completion, final V completionResult) { // Creates a message and watch for its deletion for completion. Futures.addCallback(zkClient.create(messagePathPrefix, MessageCodec.encode(message), CreateMode.PERSISTENT_SEQUENTIAL), new FutureCallback<String>() { @Override public void onSuccess(String path) { Futures.addCallback(ZKOperations.watchDeleted(zkClient, path), new FutureCallback<String>() { @Override public void onSuccess(String result) { completion.set(completionResult); } @Override public void onFailure(Throwable t) { completion.setException(t); } }); } @Override public void onFailure(Throwable t) { completion.setException(t); } }); } private ZKMessages() { } }
cdapio/twill
twill-core/src/main/java/org/apache/twill/internal/ZKMessages.java
Java
apache-2.0
4,170
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.javascript.jscomp.CheckLevel; /** * Sets the level for a particular DiagnosticGroup. * @author nicksantos@google.com (Nick Santos) */ public class DiagnosticGroupWarningsGuard extends WarningsGuard { private final DiagnosticGroup group; private final CheckLevel level; public DiagnosticGroupWarningsGuard( DiagnosticGroup group, CheckLevel level) { this.group = group; this.level = level; } @Override public CheckLevel level(JSError error) { return group.matches(error) ? level : null; } @Override public boolean disables(DiagnosticGroup otherGroup) { return !level.isOn() && group.isSubGroup(otherGroup); } @Override public boolean enables(DiagnosticGroup otherGroup) { if (level.isOn()) { for (DiagnosticType type : otherGroup.getTypes()) { if (group.matches(type)) { return true; } } } return false; } }
johan/closure-compiler
src/com/google/javascript/jscomp/DiagnosticGroupWarningsGuard.java
Java
apache-2.0
1,568
/* * 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. */ package org.apache.flink.streaming.kafka.test.base; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; /** * The util class for kafka example. */ public class KafkaExampleUtil { public static StreamExecutionEnvironment prepareExecutionEnv(ParameterTool parameterTool) throws Exception { if (parameterTool.getNumberOfParameters() < 5) { System.out.println("Missing parameters!\n" + "Usage: Kafka --input-topic <topic> --output-topic <topic> " + "--bootstrap.servers <kafka brokers> " + "--group.id <some id>"); throw new Exception("Missing parameters!\n" + "Usage: Kafka --input-topic <topic> --output-topic <topic> " + "--bootstrap.servers <kafka brokers> " + "--group.id <some id>"); } StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setRestartStrategy(RestartStrategies.fixedDelayRestart(4, 10000)); env.enableCheckpointing(5000); // create a checkpoint every 5 seconds env.getConfig().setGlobalJobParameters(parameterTool); // make parameters available in the web interface env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); return env; } }
GJL/flink
flink-end-to-end-tests/flink-streaming-kafka-test-base/src/main/java/org/apache/flink/streaming/kafka/test/base/KafkaExampleUtil.java
Java
apache-2.0
2,183
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.content.model; /** * Model definition for OrdersSetLineItemMetadataResponse. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class OrdersSetLineItemMetadataResponse extends com.google.api.client.json.GenericJson { /** * The status of the execution. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String executionStatus; /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * The status of the execution. * @return value or {@code null} for none */ public java.lang.String getExecutionStatus() { return executionStatus; } /** * The status of the execution. * @param executionStatus executionStatus or {@code null} for none */ public OrdersSetLineItemMetadataResponse setExecutionStatus(java.lang.String executionStatus) { this.executionStatus = executionStatus; return this; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @param kind kind or {@code null} for none */ public OrdersSetLineItemMetadataResponse setKind(java.lang.String kind) { this.kind = kind; return this; } @Override public OrdersSetLineItemMetadataResponse set(String fieldName, Object value) { return (OrdersSetLineItemMetadataResponse) super.set(fieldName, value); } @Override public OrdersSetLineItemMetadataResponse clone() { return (OrdersSetLineItemMetadataResponse) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-content/v2/1.29.2/com/google/api/services/content/model/OrdersSetLineItemMetadataResponse.java
Java
apache-2.0
3,052
/* Uncaught exception * Output: EH_UNCAUGHT_EXCEPTION */ function throwsException() { throw new Error(); } function doSomething() { try { throwsException(); } catch (e) { } } function doSomethingElse() { throwsException(); } doSomething(); doSomethingElse();
qhanam/Pangor
js/test/input/error_handling/eh_methods_old.js
JavaScript
apache-2.0
272
/** * Copyright 2010-2015 the original author or authors. * * 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.mybatis.spring; import static java.lang.reflect.Proxy.newProxyInstance; import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable; import static org.mybatis.spring.SqlSessionUtils.closeSqlSession; import static org.mybatis.spring.SqlSessionUtils.getSqlSession; import static org.mybatis.spring.SqlSessionUtils.isSqlSessionTransactional; import static org.springframework.util.Assert.notNull; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.Connection; import java.util.List; import java.util.Map; import org.apache.ibatis.cursor.Cursor; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.executor.BatchResult; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.dao.support.PersistenceExceptionTranslator; /** * Thread safe, Spring managed, {@code SqlSession} that works with Spring * transaction management to ensure that that the actual SqlSession used is the * one associated with the current Spring transaction. In addition, it manages * the session life-cycle, including closing, committing or rolling back the * session as necessary based on the Spring transaction configuration. * <p> * The template needs a SqlSessionFactory to create SqlSessions, passed as a * constructor argument. It also can be constructed indicating the executor type * to be used, if not, the default executor type, defined in the session factory * will be used. * <p> * This template converts MyBatis PersistenceExceptions into unchecked * DataAccessExceptions, using, by default, a {@code MyBatisExceptionTranslator}. * <p> * Because SqlSessionTemplate is thread safe, a single instance can be shared * by all DAOs; there should also be a small memory savings by doing this. This * pattern can be used in Spring configuration files as follows: * * <pre class="code"> * {@code * <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg ref="sqlSessionFactory" /> * </bean> * } * </pre> * * @author Putthibong Boonbong * @author Hunter Presnall * @author Eduardo Macarron * * @see SqlSessionFactory * @see MyBatisExceptionTranslator * @version $Id$ */ public class SqlSessionTemplate implements SqlSession, DisposableBean { private final SqlSessionFactory sqlSessionFactory; private final ExecutorType executorType; private final SqlSession sqlSessionProxy; private final PersistenceExceptionTranslator exceptionTranslator; /** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument. * * @param sqlSessionFactory */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType()); } /** * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory} * provided as an argument and the given {@code ExecutorType} * {@code ExecutorType} cannot be changed once the {@code SqlSessionTemplate} * is constructed. * * @param sqlSessionFactory * @param executorType */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) { this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator( sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true)); } /** * Constructs a Spring managed {@code SqlSession} with the given * {@code SqlSessionFactory} and {@code ExecutorType}. * A custom {@code SQLExceptionTranslator} can be provided as an * argument so any {@code PersistenceException} thrown by MyBatis * can be custom translated to a {@code RuntimeException} * The {@code SQLExceptionTranslator} can also be null and thus no * exception translation will be done and MyBatis exceptions will be * thrown * * @param sqlSessionFactory * @param executorType * @param exceptionTranslator */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required"); notNull(executorType, "Property 'executorType' is required"); this.sqlSessionFactory = sqlSessionFactory; this.executorType = executorType; this.exceptionTranslator = exceptionTranslator; this.sqlSessionProxy = (SqlSession) newProxyInstance( SqlSessionFactory.class.getClassLoader(), new Class[] { SqlSession.class }, new SqlSessionInterceptor()); } public SqlSessionFactory getSqlSessionFactory() { return this.sqlSessionFactory; } public ExecutorType getExecutorType() { return this.executorType; } public PersistenceExceptionTranslator getPersistenceExceptionTranslator() { return this.exceptionTranslator; } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement) { return this.sqlSessionProxy.<T> selectOne(statement); } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement, Object parameter) { return this.sqlSessionProxy.<T> selectOne(statement, parameter); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement) { return this.sqlSessionProxy.selectCursor(statement); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter) { return this.sqlSessionProxy.selectCursor(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.selectCursor(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement) { return this.sqlSessionProxy.<E> selectList(statement); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter) { return this.sqlSessionProxy.<E> selectList(statement, parameter); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public void select(String statement, ResultHandler handler) { this.sqlSessionProxy.select(statement, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, rowBounds, handler); } /** * {@inheritDoc} */ @Override public int insert(String statement) { return this.sqlSessionProxy.insert(statement); } /** * {@inheritDoc} */ @Override public int insert(String statement, Object parameter) { return this.sqlSessionProxy.insert(statement, parameter); } /** * {@inheritDoc} */ @Override public int update(String statement) { return this.sqlSessionProxy.update(statement); } /** * {@inheritDoc} */ @Override public int update(String statement, Object parameter) { return this.sqlSessionProxy.update(statement, parameter); } /** * {@inheritDoc} */ @Override public int delete(String statement) { return this.sqlSessionProxy.delete(statement); } /** * {@inheritDoc} */ @Override public int delete(String statement, Object parameter) { return this.sqlSessionProxy.delete(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> T getMapper(Class<T> type) { return getConfiguration().getMapper(type, this); } /** * {@inheritDoc} */ @Override public void commit() { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void commit(boolean force) { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback() { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback(boolean force) { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void close() { throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void clearCache() { this.sqlSessionProxy.clearCache(); } /** * {@inheritDoc} * */ @Override public Configuration getConfiguration() { return this.sqlSessionFactory.getConfiguration(); } /** * {@inheritDoc} */ @Override public Connection getConnection() { return this.sqlSessionProxy.getConnection(); } /** * {@inheritDoc} * * @since 1.0.2 * */ @Override public List<BatchResult> flushStatements() { return this.sqlSessionProxy.flushStatements(); } /** * Allow gently dispose bean: * <pre> * {@code * * <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg index="0" ref="sqlSessionFactory" /> * </bean> * } *</pre> * * The implementation of {@link DisposableBean} forces spring context to use {@link DisposableBean#destroy()} method instead of {@link SqlSessionTemplate#close()} to shutdown gently. * * @see SqlSessionTemplate#close() * @see org.springframework.beans.factory.support.DisposableBeanAdapter#inferDestroyMethodIfNecessary * @see org.springframework.beans.factory.support.DisposableBeanAdapter#CLOSE_METHOD_NAME */ @Override public void destroy() throws Exception { //This method forces spring disposer to avoid call of SqlSessionTemplate.close() which gives UnsupportedOperationException } /** * Proxy needed to route MyBatis method calls to the proper SqlSession got * from Spring's Transaction Manager * It also unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to * pass a {@code PersistenceException} to the {@code PersistenceExceptionTranslator}. */ private class SqlSessionInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { SqlSession sqlSession = getSqlSession( SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator); try { Object result = method.invoke(sqlSession, args); if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) { // force commit even on non-dirty sessions because some databases require // a commit/rollback before calling close() sqlSession.commit(true); } return result; } catch (Throwable t) { Throwable unwrapped = unwrapThrowable(t); if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) { // release the connection to avoid a deadlock if the translator is no loaded. See issue #22 closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); sqlSession = null; Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped); if (translated != null) { unwrapped = translated; } } throw unwrapped; } finally { if (sqlSession != null) { closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); } } } } }
jiangchaoting/spring
src/main/java/org/mybatis/spring/SqlSessionTemplate.java
Java
apache-2.0
13,876
abstract class AbstractClass { constructor(str: string, other: AbstractClass) { this.method(parseInt(str)); let val = this.prop.toLowerCase(); if (!str) { this.prop = "Hello World"; } this.cb(str); // OK, reference is inside function const innerFunction = () => { return this.prop; } // OK, references are to another instance other.cb(other.prop); } abstract prop: string; abstract cb: (s: string) => void; abstract method(num: number): void; other = this.prop; fn = () => this.prop; method2() { this.prop = this.prop + "!"; } } abstract class DerivedAbstractClass extends AbstractClass { cb = (s: string) => {}; constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { super(str, other); // there is no implementation of 'prop' in any base class this.cb(this.prop.toLowerCase()); this.method(1); // OK, references are to another instance other.cb(other.prop); yetAnother.cb(yetAnother.prop); } } class Implementation extends DerivedAbstractClass { prop = ""; cb = (s: string) => {}; constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { super(str, other, yetAnother); this.cb(this.prop); } method(n: number) { this.cb(this.prop + n); } } class User { constructor(a: AbstractClass) { a.prop; a.cb("hi"); a.method(12); a.method2(); } }
weswigham/TypeScript
tests/cases/compiler/abstractPropertyInConstructor.ts
TypeScript
apache-2.0
1,679
#!/usr/bin/env python3 class UniqueIndexViolationCheck: unique_indexes_query = """ select table_oid, index_name, table_name, array_agg(attname) as column_names from pg_attribute, ( select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index from pg_index, pg_class index_class, pg_class table_class where pg_index.indisunique='t' and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog') and index_class.relkind = 'i' and index_class.oid = pg_index.indexrelid and table_class.oid = pg_index.indrelid ) as unique_catalog_index_columns where attnum = column_index and attrelid = table_oid group by table_oid, index_name, table_name; """ def __init__(self): self.violated_segments_query = """ select distinct(gp_segment_id) from ( (select gp_segment_id, %s from gp_dist_random('%s') where (%s) is not null group by gp_segment_id, %s having count(*) > 1) union (select gp_segment_id, %s from %s where (%s) is not null group by gp_segment_id, %s having count(*) > 1) ) as violations """ def runCheck(self, db_connection): unique_indexes = db_connection.query(self.unique_indexes_query).getresult() violations = [] for (table_oid, index_name, table_name, column_names) in unique_indexes: column_names = ",".join(column_names) sql = self.get_violated_segments_query(table_name, column_names) violated_segments = db_connection.query(sql).getresult() if violated_segments: violations.append(dict(table_oid=table_oid, table_name=table_name, index_name=index_name, column_names=column_names, violated_segments=[row[0] for row in violated_segments])) return violations def get_violated_segments_query(self, table_name, column_names): return self.violated_segments_query % ( column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names )
50wu/gpdb
gpMgmt/bin/gpcheckcat_modules/unique_index_violation_check.py
Python
apache-2.0
2,547
/** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ "use strict"; var EventConstants = require("./EventConstants"); var EventPluginHub = require("./EventPluginHub"); var EventPluginRegistry = require("./EventPluginRegistry"); var ReactEventEmitterMixin = require("./ReactEventEmitterMixin"); var ViewportMetrics = require("./ViewportMetrics"); var isEventSupported = require("./isEventSupported"); var merge = require("./merge"); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topBlur: 'blur', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTextInput: 'textInput', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = merge(ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function(ReactEventListener) { ReactEventListener.setHandleTopLevel( ReactBrowserEventEmitter.handleTopLevel ); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled() ); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function(registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry. registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0, l = dependencies.length; i < l; i++) { var dependency = dependencies[i]; if (!( isListening.hasOwnProperty(dependency) && isListening[dependency] )) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'wheel', mountAt ); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'mousewheel', mountAt ); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt ); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topScroll, 'scroll', mountAt ); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE ); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topFocus, 'focus', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topBlur, 'blur', mountAt ); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topFocus, 'focusin', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topBlur, 'focusout', mountAt ); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( dependency, topEventMapping[dependency], mountAt ); } isListening[dependency] = true; } } }, trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelType, handlerBaseName, handle ); }, trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelType, handlerBaseName, handle ); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function(){ if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); module.exports = ReactBrowserEventEmitter;
KnisterPeter/jreact
src/test/resources/react-0.11/node_modules/react/lib/ReactBrowserEventEmitter.js
JavaScript
bsd-2-clause
12,568
<?php /** * Squiz_Sniffs_Classes_ValidClassNameSniff. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @author Marc McIntyre <mmcintyre@squiz.net> * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * Squiz_Sniffs_Classes_ValidClassNameSniff. * * Ensures classes are in camel caps, and the first letter is capitalised * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @author Marc McIntyre <mmcintyre@squiz.net> * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ class Squiz_Sniffs_Classes_ValidClassNameSniff implements PHP_CodeSniffer_Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array( T_CLASS, T_INTERFACE, ); }//end register() /** * Processes this test, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The current file being processed. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if (isset($tokens[$stackPtr]['scope_opener']) === false) { $error = 'Possible parse error: %s missing opening or closing brace'; $data = array($tokens[$stackPtr]['content']); $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $data); return; } // Determine the name of the class or interface. Note that we cannot // simply look for the first T_STRING because a class name // starting with the number will be multiple tokens. $opener = $tokens[$stackPtr]['scope_opener']; $nameStart = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), $opener, true); $nameEnd = $phpcsFile->findNext(T_WHITESPACE, $nameStart, $opener); $name = trim($phpcsFile->getTokensAsString($nameStart, ($nameEnd - $nameStart))); // Check for camel caps format. $valid = PHP_CodeSniffer::isCamelCaps($name, true, true, false); if ($valid === false) { $type = ucfirst($tokens[$stackPtr]['content']); $error = '%s name "%s" is not in camel caps format'; $data = array( $type, $name, ); $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $data); } }//end process() }//end class ?>
scaryml1000/ZendSkeleton
vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/Squiz/Sniffs/Classes/ValidClassNameSniff.php
PHP
bsd-3-clause
3,154
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\helpers; /** * Console helper provides useful methods for command line related tasks such as getting input or formatting and coloring * output. * * @author Carsten Brandt <mail@cebe.cc> * @since 2.0 */ class Console extends BaseConsole { }
nikn/it-asu.ru
vendor/yiisoft/yii2/helpers/Console.php
PHP
bsd-3-clause
432
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ 'use strict'; const {polyfillObjectProperty} = require('../Utilities/PolyfillFunctions'); let navigator = global.navigator; if (navigator === undefined) { global.navigator = navigator = {}; } // see https://github.com/facebook/react-native/issues/10881 polyfillObjectProperty(navigator, 'product', () => 'ReactNative');
pandiaraj44/react-native
Libraries/Core/setUpNavigator.js
JavaScript
bsd-3-clause
545
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/permissions/permission_request_id.h" #include <inttypes.h> #include <stdint.h> #include "base/strings/stringprintf.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" namespace permissions { PermissionRequestID::PermissionRequestID( content::RenderFrameHost* render_frame_host, RequestLocalId request_local_id) : render_process_id_(render_frame_host->GetProcess()->GetID()), render_frame_id_(render_frame_host->GetRoutingID()), request_local_id_(request_local_id) {} PermissionRequestID::PermissionRequestID(int render_process_id, int render_frame_id, RequestLocalId request_local_id) : render_process_id_(render_process_id), render_frame_id_(render_frame_id), request_local_id_(request_local_id) {} PermissionRequestID::~PermissionRequestID() {} PermissionRequestID::PermissionRequestID(const PermissionRequestID&) = default; PermissionRequestID& PermissionRequestID::operator=( const PermissionRequestID&) = default; bool PermissionRequestID::operator==(const PermissionRequestID& other) const { return render_process_id_ == other.render_process_id_ && render_frame_id_ == other.render_frame_id_ && request_local_id_ == other.request_local_id_; } bool PermissionRequestID::operator!=(const PermissionRequestID& other) const { return !operator==(other); } std::string PermissionRequestID::ToString() const { return base::StringPrintf("%d,%d,%" PRId64, render_process_id_, render_frame_id_, request_local_id_.value()); } } // namespace permissions
scheib/chromium
components/permissions/permission_request_id.cc
C++
bsd-3-clause
1,886
#include <iostream> #include <seqan/file.h> #include <seqan/sequence.h> #include <seqan/score.h> using namespace seqan; template <typename TText, typename TPattern> int computeLocalScore(TText const & subText, TPattern const & pattern) { int localScore = 0; for (unsigned i = 0; i < length(pattern); ++i) if (subText[i] == pattern[i]) ++localScore; return localScore; } template <typename TText, typename TPattern> String<int> computeScore(TText const & text, TPattern const & pattern) { String<int> score; resize(score, length(text) - length(pattern) + 1, 0); for (unsigned i = 0; i < length(text) - length(pattern) + 1; ++i) score[i] = computeLocalScore(infix(text, i, i + length(pattern)), pattern); return score; } void print(String<int> const & text) { for (unsigned i = 0; i < length(text); ++i) std::cout << text[i] << " "; std::cout << std::endl; } int main() { String<char> text = "This is an awesome tutorial to get to know SeqAn!"; String<char> pattern = "tutorial"; String<int> score = computeScore(text, pattern); print(score); return 0; }
bestrauc/seqan
demos/tutorial/a_first_example/solution_4.cpp
C++
bsd-3-clause
1,153
module Stupidedi module Versions module FunctionalGroups module ThirtyForty module SegmentDefs s = Schema e = ElementDefs r = ElementReqs MS1 = s::SegmentDef.build(:MS1, "Equipment, Shipment, or Real Property Location", "To specify the location of a piece of equipment, a shipment, or real property in terms of city and state for the stop location that relates to the AT7 shipment status details.", e::E19 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E156 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E26 .simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1654.simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1655.simple_use(r::Relational, s::RepeatCount.bounded(1)), e::E1280.simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E1280.simple_use(r::Optional, s::RepeatCount.bounded(1)), e::E116 .simple_use(r::Optional, s::RepeatCount.bounded(1)), SyntaxNotes::L.build(1, 2, 3), SyntaxNotes::E.build(1, 4), SyntaxNotes::C.build(2, 1), SyntaxNotes::C.build(3, 1), SyntaxNotes::P.build(4, 5), SyntaxNotes::C.build(6, 4), SyntaxNotes::C.build(7, 4), SyntaxNotes::C.build(8, 1)) end end end end end
justworkshr/stupidedi
lib/stupidedi/versions/functional_groups/003040/segment_defs/MS1.rb
Ruby
bsd-3-clause
1,438
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/convert_web_app.h" #include <cmath> #include <limits> #include <string> #include <vector> #include "base/base64.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/logging.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/stringprintf.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_manifest_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/web_apps.h" #include "crypto/sha2.h" #include "googleurl/src/gurl.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" namespace keys = extension_manifest_keys; using base::Time; namespace { const char kIconsDirName[] = "icons"; // Create the public key for the converted web app. // // Web apps are not signed, but the public key for an extension doubles as // its unique identity, and we need one of those. A web app's unique identity // is its manifest URL, so we hash that to create a public key. There will be // no corresponding private key, which means that these extensions cannot be // auto-updated using ExtensionUpdater. But Chrome does notice updates to the // manifest and regenerates these extensions. std::string GenerateKey(const GURL& manifest_url) { char raw[crypto::kSHA256Length] = {0}; std::string key; crypto::SHA256HashString(manifest_url.spec().c_str(), raw, crypto::kSHA256Length); base::Base64Encode(std::string(raw, crypto::kSHA256Length), &key); return key; } } // Generates a version for the converted app using the current date. This isn't // really needed, but it seems like useful information. std::string ConvertTimeToExtensionVersion(const Time& create_time) { Time::Exploded create_time_exploded; create_time.UTCExplode(&create_time_exploded); double micros = static_cast<double>( (create_time_exploded.millisecond * Time::kMicrosecondsPerMillisecond) + (create_time_exploded.second * Time::kMicrosecondsPerSecond) + (create_time_exploded.minute * Time::kMicrosecondsPerMinute) + (create_time_exploded.hour * Time::kMicrosecondsPerHour)); double day_fraction = micros / Time::kMicrosecondsPerDay; double stamp = day_fraction * std::numeric_limits<uint16>::max(); // Ghetto-round, since VC++ doesn't have round(). stamp = stamp >= (floor(stamp) + 0.5) ? (stamp + 1) : stamp; return base::StringPrintf("%i.%i.%i.%i", create_time_exploded.year, create_time_exploded.month, create_time_exploded.day_of_month, static_cast<uint16>(stamp)); } scoped_refptr<Extension> ConvertWebAppToExtension( const WebApplicationInfo& web_app, const Time& create_time) { FilePath user_data_temp_dir = extension_file_util::GetUserDataTempDir(); if (user_data_temp_dir.empty()) { LOG(ERROR) << "Could not get path to profile temporary directory."; return NULL; } ScopedTempDir temp_dir; if (!temp_dir.CreateUniqueTempDirUnderPath(user_data_temp_dir)) { LOG(ERROR) << "Could not create temporary directory."; return NULL; } // Create the manifest scoped_ptr<DictionaryValue> root(new DictionaryValue); if (!web_app.is_bookmark_app) root->SetString(keys::kPublicKey, GenerateKey(web_app.manifest_url)); else root->SetString(keys::kPublicKey, GenerateKey(web_app.app_url)); root->SetString(keys::kName, UTF16ToUTF8(web_app.title)); root->SetString(keys::kVersion, ConvertTimeToExtensionVersion(create_time)); root->SetString(keys::kDescription, UTF16ToUTF8(web_app.description)); root->SetString(keys::kLaunchWebURL, web_app.app_url.spec()); if (!web_app.launch_container.empty()) root->SetString(keys::kLaunchContainer, web_app.launch_container); // Add the icons. DictionaryValue* icons = new DictionaryValue(); root->Set(keys::kIcons, icons); for (size_t i = 0; i < web_app.icons.size(); ++i) { std::string size = StringPrintf("%i", web_app.icons[i].width); std::string icon_path = StringPrintf("%s/%s.png", kIconsDirName, size.c_str()); icons->SetString(size, icon_path); } // Add the permissions. ListValue* permissions = new ListValue(); root->Set(keys::kPermissions, permissions); for (size_t i = 0; i < web_app.permissions.size(); ++i) { permissions->Append(Value::CreateStringValue(web_app.permissions[i])); } // Add the URLs. ListValue* urls = new ListValue(); root->Set(keys::kWebURLs, urls); for (size_t i = 0; i < web_app.urls.size(); ++i) { urls->Append(Value::CreateStringValue(web_app.urls[i].spec())); } // Write the manifest. FilePath manifest_path = temp_dir.path().Append( Extension::kManifestFilename); JSONFileValueSerializer serializer(manifest_path); if (!serializer.Serialize(*root)) { LOG(ERROR) << "Could not serialize manifest."; return NULL; } // Write the icon files. FilePath icons_dir = temp_dir.path().AppendASCII(kIconsDirName); if (!file_util::CreateDirectory(icons_dir)) { LOG(ERROR) << "Could not create icons directory."; return NULL; } for (size_t i = 0; i < web_app.icons.size(); ++i) { // Skip unfetched bitmaps. if (web_app.icons[i].data.config() == SkBitmap::kNo_Config) continue; FilePath icon_file = icons_dir.AppendASCII( StringPrintf("%i.png", web_app.icons[i].width)); std::vector<unsigned char> image_data; if (!gfx::PNGCodec::EncodeBGRASkBitmap(web_app.icons[i].data, false, &image_data)) { LOG(ERROR) << "Could not create icon file."; return NULL; } const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(icon_file, image_data_ptr, image_data.size())) { LOG(ERROR) << "Could not write icon file."; return NULL; } } // Finally, create the extension object to represent the unpacked directory. std::string error; int extension_flags = Extension::STRICT_ERROR_CHECKS; if (web_app.is_bookmark_app) extension_flags |= Extension::FROM_BOOKMARK; scoped_refptr<Extension> extension = Extension::Create( temp_dir.path(), Extension::INTERNAL, *root, extension_flags, &error); if (!extension) { LOG(ERROR) << error; return NULL; } temp_dir.Take(); // The caller takes ownership of the directory. return extension; }
robclark/chromium
chrome/browser/extensions/convert_web_app.cc
C++
bsd-3-clause
6,936
#if 0 // Disabled until updated to use current API. // Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "tools/fiddle/examples.h" // HASH=a75bbdb8bb866b125c4c1dd5e967d470 REG_FIDDLE(Paint_setTextScaleX, 256, 256, true, 0) { void draw(SkCanvas* canvas) { SkPaint paint; paint.setTextScaleX(0.f / 0.f); SkDebugf("text scale %s-a-number\n", SkScalarIsNaN(paint.getTextScaleX()) ? "not" : "is"); } } // END FIDDLE #endif // Disabled until updated to use current API.
youtube/cobalt
third_party/skia_next/third_party/skia/docs/examples/Paint_setTextScaleX.cpp
C++
bsd-3-clause
566
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/file_system_provider/operations/execute_action.h" #include <algorithm> #include <string> #include "chrome/common/extensions/api/file_system_provider.h" #include "chrome/common/extensions/api/file_system_provider_internal.h" namespace ash { namespace file_system_provider { namespace operations { ExecuteAction::ExecuteAction(extensions::EventRouter* event_router, const ProvidedFileSystemInfo& file_system_info, const std::vector<base::FilePath>& entry_paths, const std::string& action_id, storage::AsyncFileUtil::StatusCallback callback) : Operation(event_router, file_system_info), entry_paths_(entry_paths), action_id_(action_id), callback_(std::move(callback)) {} ExecuteAction::~ExecuteAction() { } bool ExecuteAction::Execute(int request_id) { using extensions::api::file_system_provider::ExecuteActionRequestedOptions; ExecuteActionRequestedOptions options; options.file_system_id = file_system_info_.file_system_id(); options.request_id = request_id; for (const auto& entry_path : entry_paths_) options.entry_paths.push_back(entry_path.AsUTF8Unsafe()); options.action_id = action_id_; return SendEvent( request_id, extensions::events::FILE_SYSTEM_PROVIDER_ON_EXECUTE_ACTION_REQUESTED, extensions::api::file_system_provider::OnExecuteActionRequested:: kEventName, extensions::api::file_system_provider::OnExecuteActionRequested::Create( options)); } void ExecuteAction::OnSuccess(int /* request_id */, std::unique_ptr<RequestValue> result, bool has_more) { DCHECK(callback_); std::move(callback_).Run(base::File::FILE_OK); } void ExecuteAction::OnError(int /* request_id */, std::unique_ptr<RequestValue> /* result */, base::File::Error error) { DCHECK(callback_); std::move(callback_).Run(error); } } // namespace operations } // namespace file_system_provider } // namespace ash
ric2b/Vivaldi-browser
chromium/chrome/browser/ash/file_system_provider/operations/execute_action.cc
C++
bsd-3-clause
2,321
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.browserservices.ui.splashscreen.trustedwebactivity; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static androidx.browser.trusted.TrustedWebActivityIntentBuilder.EXTRA_SPLASH_SCREEN_PARAMS; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.browser.customtabs.TrustedWebUtils; import androidx.browser.trusted.TrustedWebActivityIntentBuilder; import androidx.browser.trusted.splashscreens.SplashScreenParamKey; import org.chromium.base.IntentUtils; import org.chromium.chrome.browser.browserservices.intents.BrowserServicesIntentDataProvider; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashController; import org.chromium.chrome.browser.browserservices.ui.splashscreen.SplashDelegate; import org.chromium.chrome.browser.customtabs.TranslucentCustomTabActivity; import org.chromium.chrome.browser.tab.Tab; import org.chromium.ui.base.ActivityWindowAndroid; import org.chromium.ui.util.ColorUtils; import javax.inject.Inject; /** * Orchestrates the flow of showing and removing splash screens for apps based on Trusted Web * Activities. * * The flow is as follows: * - TWA client app verifies conditions for showing splash screen. If the checks pass, it shows the * splash screen immediately. * - The client passes the URI to a file with the splash image to * {@link androidx.browser.customtabs.CustomTabsService}. The image is decoded and put into * {@link SplashImageHolder}. * - The client then launches a TWA, at which point the Bitmap is already available. * - ChromeLauncherActivity calls {@link #handleIntent}, which starts * {@link TranslucentCustomTabActivity} - a CustomTabActivity with translucent style. The * translucency is necessary in order to avoid a flash that might be seen when starting the activity * before the splash screen is attached. * - {@link TranslucentCustomTabActivity} creates an instance of {@link TwaSplashController} which * immediately displays the splash screen in an ImageView on top of the rest of view hierarchy. * - It also immediately removes the translucency. See comment in {@link SplashController} for more * details. * - It waits for the page to load, and removes the splash image once first paint (or a failure) * occurs. * * Lifecycle: this class is resolved only once when CustomTabActivity is launched, and is * gc-ed when it finishes its job. * If these lifecycle assumptions change, consider whether @ActivityScope needs to be added. */ public class TwaSplashController implements SplashDelegate { // TODO(pshmakov): move this to AndroidX. private static final String KEY_SHOWN_IN_CLIENT = "androidx.browser.trusted.KEY_SPLASH_SCREEN_SHOWN_IN_CLIENT"; private final SplashController mSplashController; private final Activity mActivity; private final SplashImageHolder mSplashImageCache; private final BrowserServicesIntentDataProvider mIntentDataProvider; @Inject public TwaSplashController(SplashController splashController, Activity activity, ActivityWindowAndroid activityWindowAndroid, SplashImageHolder splashImageCache, BrowserServicesIntentDataProvider intentDataProvider) { mSplashController = splashController; mActivity = activity; mSplashImageCache = splashImageCache; mIntentDataProvider = intentDataProvider; long splashHideAnimationDurationMs = IntentUtils.safeGetInt(getSplashScreenParamsFromIntent(), SplashScreenParamKey.KEY_FADE_OUT_DURATION_MS, 0); mSplashController.setConfig(this, splashHideAnimationDurationMs); } @Override public View buildSplashView() { Bitmap bitmap = mSplashImageCache.takeImage(mIntentDataProvider.getSession()); if (bitmap == null) { return null; } ImageView splashView = new ImageView(mActivity); splashView.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); splashView.setImageBitmap(bitmap); applyCustomizationsToSplashScreenView(splashView); return splashView; } @Override public void onSplashHidden(Tab tab, long startTimestamp, long endTimestamp) {} @Override public boolean shouldWaitForSubsequentPageLoadToHideSplash() { return false; } private void applyCustomizationsToSplashScreenView(ImageView imageView) { Bundle params = getSplashScreenParamsFromIntent(); int backgroundColor = IntentUtils.safeGetInt( params, SplashScreenParamKey.KEY_BACKGROUND_COLOR, Color.WHITE); imageView.setBackgroundColor(ColorUtils.getOpaqueColor(backgroundColor)); int scaleTypeOrdinal = IntentUtils.safeGetInt(params, SplashScreenParamKey.KEY_SCALE_TYPE, -1); ImageView.ScaleType[] scaleTypes = ImageView.ScaleType.values(); ImageView.ScaleType scaleType; if (scaleTypeOrdinal < 0 || scaleTypeOrdinal >= scaleTypes.length) { scaleType = ImageView.ScaleType.CENTER; } else { scaleType = scaleTypes[scaleTypeOrdinal]; } imageView.setScaleType(scaleType); if (scaleType != ImageView.ScaleType.MATRIX) return; float[] matrixValues = IntentUtils.safeGetFloatArray( params, SplashScreenParamKey.KEY_IMAGE_TRANSFORMATION_MATRIX); if (matrixValues == null || matrixValues.length != 9) return; Matrix matrix = new Matrix(); matrix.setValues(matrixValues); imageView.setImageMatrix(matrix); } private Bundle getSplashScreenParamsFromIntent() { return mIntentDataProvider.getIntent().getBundleExtra(EXTRA_SPLASH_SCREEN_PARAMS); } /** * Returns true if the intent corresponds to a TWA with a splash screen. */ public static boolean intentIsForTwaWithSplashScreen(Intent intent) { boolean isTrustedWebActivity = IntentUtils.safeGetBooleanExtra( intent, TrustedWebUtils.EXTRA_LAUNCH_AS_TRUSTED_WEB_ACTIVITY, false); boolean requestsSplashScreen = IntentUtils.safeGetParcelableExtra(intent, EXTRA_SPLASH_SCREEN_PARAMS) != null; return isTrustedWebActivity && requestsSplashScreen; } /** * Handles the intent if it should launch a TWA with splash screen. * @param activity Activity, from which to start the next one. * @param intent Incoming intent. * @return Whether the intent was handled. */ public static boolean handleIntent(Activity activity, Intent intent) { if (!intentIsForTwaWithSplashScreen(intent)) return false; Bundle params = IntentUtils.safeGetBundleExtra( intent, TrustedWebActivityIntentBuilder.EXTRA_SPLASH_SCREEN_PARAMS); boolean shownInClient = IntentUtils.safeGetBoolean(params, KEY_SHOWN_IN_CLIENT, true); // shownInClient is "true" by default for the following reasons: // - For compatibility with older clients which don't use this bundle key. // - Because getting "false" when it should be "true" leads to more severe visual glitches, // than vice versa. if (shownInClient) { // If splash screen was shown in client, we must launch a translucent activity to // ensure smooth transition. intent.setClassName(activity, TranslucentCustomTabActivity.class.getName()); } intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); activity.startActivity(intent); activity.overridePendingTransition(0, 0); return true; } }
ric2b/Vivaldi-browser
chromium/chrome/android/java/src/org/chromium/chrome/browser/browserservices/ui/splashscreen/trustedwebactivity/TwaSplashController.java
Java
bsd-3-clause
8,032
using System; using System.Collections.Generic; namespace SharpCompress { internal class LazyReadOnlyCollection<T> : ICollection<T> { private readonly List<T> backing = new List<T>(); private readonly IEnumerator<T> source; private bool fullyLoaded; public LazyReadOnlyCollection(IEnumerable<T> source) { this.source = source.GetEnumerator(); } private class LazyLoader : IEnumerator<T> { private readonly LazyReadOnlyCollection<T> lazyReadOnlyCollection; private bool disposed; private int index = -1; internal LazyLoader(LazyReadOnlyCollection<T> lazyReadOnlyCollection) { this.lazyReadOnlyCollection = lazyReadOnlyCollection; } #region IEnumerator<T> Members public T Current { get { return lazyReadOnlyCollection.backing[index]; } } #endregion #region IDisposable Members public void Dispose() { if (!disposed) { disposed = true; } } #endregion #region IEnumerator Members object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { if (index + 1 < lazyReadOnlyCollection.backing.Count) { index++; return true; } if (!lazyReadOnlyCollection.fullyLoaded && lazyReadOnlyCollection.source.MoveNext()) { lazyReadOnlyCollection.backing.Add(lazyReadOnlyCollection.source.Current); index++; return true; } lazyReadOnlyCollection.fullyLoaded = true; return false; } public void Reset() { throw new NotSupportedException(); } #endregion } internal void EnsureFullyLoaded() { if (!fullyLoaded) { this.ForEach(x => { }); fullyLoaded = true; } } internal IEnumerable<T> GetLoaded() { return backing; } #region ICollection<T> Members public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(T item) { EnsureFullyLoaded(); return backing.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { EnsureFullyLoaded(); backing.CopyTo(array, arrayIndex); } public int Count { get { EnsureFullyLoaded(); return backing.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(T item) { throw new NotSupportedException(); } #endregion #region IEnumerable<T> Members //TODO check for concurrent access public IEnumerator<T> GetEnumerator() { return new LazyLoader(this); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
catester/sharpcompress
SharpCompress/LazyReadOnlyCollection.cs
C#
mit
3,931
VERSION = (1, 3, 0, 'alpha', 1) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: if VERSION[3] != 'final': version = '%s %s %s' % (version, VERSION[3], VERSION[4]) from django.utils.version import get_svn_revision svn_rev = get_svn_revision() if svn_rev != u'SVN-unknown': version = "%s %s" % (version, svn_rev) return version
hunch/hunch-gift-app
django/__init__.py
Python
mit
565
package com.greenlemonmobile.app.ebook.books.parser; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; public interface ZipWrapper { ZipEntry getEntry(String entryName); InputStream getInputStream(ZipEntry entry) throws IOException; Enumeration<? extends ZipEntry> entries(); void close() throws IOException; }
xiaopengs/iBooks
src/com/greenlemonmobile/app/ebook/books/parser/ZipWrapper.java
Java
mit
433
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace AutoTest.TestRunners.XUnit.Tests.TestResource { public class Class2 { [Fact] public void Anothger_passing_test() { Assert.Equal(1, 1); } } }
acken/AutoTest.Net
src/AutoTest.TestRunner/Plugins/AutoTest.TestRunners.XUnit.Tests.TestResource/Class2.cs
C#
mit
310
version https://git-lfs.github.com/spec/v1 oid sha256:ff6a5c1204e476c89870c6f14e75db666fa26de9359f9d8c372ef779b55c8875 size 2736
yogeshsaroya/new-cdnjs
ajax/libs/dojo/1.8.9/cldr/nls/cs/buddhist.js.uncompressed.js
JavaScript
mit
129
function example(name, deps) { console.log('This is where fpscounter plugin code would execute in the node process.'); } module.exports = example;
BenjaminTsai/openrov-cockpit
src/plugins/fpscounter/index.js
JavaScript
mit
148
<?php namespace Concrete\Controller\Element\Express\Search; use Concrete\Core\Controller\ElementController; use Concrete\Core\Entity\Express\Entity; use Concrete\Core\Entity\Search\Query; use Concrete\Core\File\Search\SearchProvider; use Concrete\Core\Foundation\Serializer\JsonSerializer; class Search extends ElementController { /** * This is where the header search bar in the page should point. This search bar allows keyword searching in * different contexts. * * @var string */ protected $headerSearchAction; /** * @var Entity */ protected $entity; /** * @var Query */ protected $query; public function getElement() { return 'express/search/search'; } /** * @param Query $query */ public function setQuery(Query $query = null): void { $this->query = $query; } /** * @param string $headerSearchAction */ public function setHeaderSearchAction(string $headerSearchAction): void { $this->headerSearchAction = $headerSearchAction; } /** * @param Entity $entity */ public function setEntity(Entity $entity): void { $this->entity = $entity; } public function view() { $this->set('entity', $this->entity); $this->set('form', $this->app->make('helper/form')); $this->set('token', $this->app->make('token')); if (isset($this->headerSearchAction)) { $this->set('headerSearchAction', $this->headerSearchAction); } else { $this->set( 'headerSearchAction', $this->app->make('url')->to('/dashboard/express/entries/', 'view', $this->entity->getId()) ); } if (isset($this->query)) { $this->set('query', $this->app->make(JsonSerializer::class)->serialize($this->query, 'json')); } } }
haeflimi/concrete5
concrete/controllers/element/express/search/search.php
PHP
mit
1,932
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\ApiBundle\Command; /** @experimental */ interface ChannelCodeAwareInterface extends CommandAwareDataTransformerInterface { public function getChannelCode(): ?string; public function setChannelCode(?string $channelCode): void; }
loic425/Sylius
src/Sylius/Bundle/ApiBundle/Command/ChannelCodeAwareInterface.php
PHP
mit
508
package net import ( "io" ) const ( bufferSize = 4 * 1024 ) // ReaderToChan dumps all content from a given reader to a chan by constantly reading it until EOF. func ReaderToChan(stream chan<- []byte, reader io.Reader) error { for { buffer := make([]byte, bufferSize) nBytes, err := reader.Read(buffer) if nBytes > 0 { stream <- buffer[:nBytes] } if err != nil { return err } } } // ChanToWriter dumps all content from a given chan to a writer until the chan is closed. func ChanToWriter(writer io.Writer, stream <-chan []byte) error { for buffer := range stream { _, err := writer.Write(buffer) if err != nil { return err } } return nil }
larryeee/v2ray-core
common/net/transport.go
GO
mit
677
 using System; using System.Collections.Generic; namespace Orleans.Providers.Streams.Common { /// <summary> /// Object pool that roughly ensures only a specified number of the objects are allowed to be allocated. /// When more objects are allocated then is specified, previously allocated objects will be signaled to be purged in order. /// When objects are signaled, they should be returned to the pool. How this is done is an implementation /// detail of the object. /// </summary> /// <typeparam name="T"></typeparam> public class FixedSizeObjectPool<T> : ObjectPool<T> where T : PooledResource<T> { private const int MinObjectCount = 3; // 1MB /// <summary> /// Queue of objects that have been allocated and are currently in use. /// Tracking these is necessary for keeping a fixed size. These are used to reclaim allocated resources /// by signaling purges which should eventually return the resource to the pool. /// Protected for test reasons /// </summary> protected readonly Queue<T> usedObjects = new Queue<T>(); private readonly object locker = new object(); private readonly int maxObjectCount; /// <summary> /// Manages a memory pool of poolSize blocks. /// Whenever we've allocated more blocks than the poolSize, we signal the oldest allocated block to purge /// itself and return to the pool. /// </summary> /// <param name="poolSize"></param> /// <param name="factoryFunc"></param> public FixedSizeObjectPool(int poolSize, Func<T> factoryFunc) : base(factoryFunc, poolSize) { if (poolSize < MinObjectCount) { throw new ArgumentOutOfRangeException("poolSize", "Minimum object count is " + MinObjectCount); } maxObjectCount = poolSize; } /// <summary> /// Allocates a resource from the pool. /// </summary> /// <returns></returns> public override T Allocate() { T obj; lock (locker) { // if we've used all we are allowed, signal object it has been purged and should be returned to the pool if (usedObjects.Count >= maxObjectCount) { usedObjects.Dequeue().SignalPurge(); } obj = base.Allocate(); // track used objects usedObjects.Enqueue(obj); } return obj; } /// <summary> /// Returns a resource to the pool to be reused /// </summary> /// <param name="resource"></param> public override void Free(T resource) { lock (locker) { base.Free(resource); } } } }
shlomiw/orleans
src/OrleansProviders/Streams/Common/PooledCache/FixedSizeObjectPool.cs
C#
mit
2,936
'use strict'; var BigNumber = require('../../type/BigNumber'); var Range = require('../../type/Range'); var Index = require('../../type/Index'); var isNumber = require('../../util/number').isNumber; /** * Attach a transform function to math.index * Adds a property transform containing the transform function. * * This transform creates a one-based index instead of a zero-based index * @param {Object} math */ module.exports = function (math) { var transform = function () { var args = []; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number if (arg instanceof Range) { arg.start--; arg.end -= (arg.step > 0 ? 0 : 2); } else if (isNumber(arg)) { arg--; } else if (arg instanceof BigNumber) { arg = arg.toNumber() - 1; } else { throw new TypeError('Ranges must be a Number or Range'); } args[i] = arg; } var res = new Index(); Index.apply(res, args); return res; }; math.index.transform = transform; return transform; };
MonoHearted/Flowerbless
node_modules/mathjs/lib/expression/transform/index.transform.js
JavaScript
mit
1,170
package com.greenlemonmobile.app.ebook.books.imagezoom.graphics; import android.graphics.Bitmap; /** * Base interface used in the {@link ImageViewTouchBase} view * @author alessandro * */ public interface IBitmapDrawable { Bitmap getBitmap(); }
yy1300326388/iBooks
src/com/greenlemonmobile/app/ebook/books/imagezoom/graphics/IBitmapDrawable.java
Java
mit
253
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #ifndef OPENCV_CORE_ALLOCATOR_STATS_HPP #define OPENCV_CORE_ALLOCATOR_STATS_HPP #include "../cvdef.h" namespace cv { namespace utils { class AllocatorStatisticsInterface { protected: AllocatorStatisticsInterface() {} virtual ~AllocatorStatisticsInterface() {} public: virtual uint64_t getCurrentUsage() const = 0; virtual uint64_t getTotalUsage() const = 0; virtual uint64_t getNumberOfAllocations() const = 0; virtual uint64_t getPeakUsage() const = 0; /** set peak usage = current usage */ virtual void resetPeakUsage() = 0; }; }} // namespace #endif // OPENCV_CORE_ALLOCATOR_STATS_HPP
HuTianQi/QQ
app/src/main/cpp/third_part/opencv/include/opencv2/core/utils/allocator_stats.hpp
C++
mit
821
define("ace/snippets/typescript",["require","exports","module"],function(e,t,n){"use strict";t.snippetText="",t.scope="typescript"}); (function() { window.require(["ace/snippets/typescript"], function(m) { if (typeof module == "object") { module.exports = m; } }); })();
holtkamp/cdnjs
ajax/libs/ace/1.3.2/snippets/typescript.js
JavaScript
mit
431
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.azurespecials.implementation; import com.microsoft.azure.AzureClient; import com.microsoft.azure.AzureServiceClient; import com.microsoft.azure.RestClient; import com.microsoft.rest.credentials.ServiceClientCredentials; import fixtures.azurespecials.ApiVersionDefaults; import fixtures.azurespecials.ApiVersionLocals; import fixtures.azurespecials.AutoRestAzureSpecialParametersTestClient; import fixtures.azurespecials.Headers; import fixtures.azurespecials.Odatas; import fixtures.azurespecials.SkipUrlEncodings; import fixtures.azurespecials.SubscriptionInCredentials; import fixtures.azurespecials.SubscriptionInMethods; import fixtures.azurespecials.XMsClientRequestIds; /** * Initializes a new instance of the AutoRestAzureSpecialParametersTestClientImpl class. */ public final class AutoRestAzureSpecialParametersTestClientImpl extends AzureServiceClient implements AutoRestAzureSpecialParametersTestClient { /** the {@link AzureClient} used for long running operations. */ private AzureClient azureClient; /** * Gets the {@link AzureClient} used for long running operations. * @return the azure client; */ public AzureClient getAzureClient() { return this.azureClient; } /** The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. */ private String subscriptionId; /** * Gets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @return the subscriptionId value. */ public String subscriptionId() { return this.subscriptionId; } /** * Sets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @param subscriptionId the subscriptionId value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** The api version, which appears in the query, the value is always '2015-07-01-preview'. */ private String apiVersion; /** * Gets The api version, which appears in the query, the value is always '2015-07-01-preview'. * * @return the apiVersion value. */ public String apiVersion() { return this.apiVersion; } /** Gets or sets the preferred language for the response. */ private String acceptLanguage; /** * Gets Gets or sets the preferred language for the response. * * @return the acceptLanguage value. */ public String acceptLanguage() { return this.acceptLanguage; } /** * Sets Gets or sets the preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */ private int longRunningOperationRetryTimeout; /** * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the longRunningOperationRetryTimeout value. */ public int longRunningOperationRetryTimeout() { return this.longRunningOperationRetryTimeout; } /** * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; return this; } /** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ private boolean generateClientRequestId; /** * Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @return the generateClientRequestId value. */ public boolean generateClientRequestId() { return this.generateClientRequestId; } /** * Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @param generateClientRequestId the generateClientRequestId value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { this.generateClientRequestId = generateClientRequestId; return this; } /** * The XMsClientRequestIds object to access its operations. */ private XMsClientRequestIds xMsClientRequestIds; /** * Gets the XMsClientRequestIds object to access its operations. * @return the XMsClientRequestIds object. */ public XMsClientRequestIds xMsClientRequestIds() { return this.xMsClientRequestIds; } /** * The SubscriptionInCredentials object to access its operations. */ private SubscriptionInCredentials subscriptionInCredentials; /** * Gets the SubscriptionInCredentials object to access its operations. * @return the SubscriptionInCredentials object. */ public SubscriptionInCredentials subscriptionInCredentials() { return this.subscriptionInCredentials; } /** * The SubscriptionInMethods object to access its operations. */ private SubscriptionInMethods subscriptionInMethods; /** * Gets the SubscriptionInMethods object to access its operations. * @return the SubscriptionInMethods object. */ public SubscriptionInMethods subscriptionInMethods() { return this.subscriptionInMethods; } /** * The ApiVersionDefaults object to access its operations. */ private ApiVersionDefaults apiVersionDefaults; /** * Gets the ApiVersionDefaults object to access its operations. * @return the ApiVersionDefaults object. */ public ApiVersionDefaults apiVersionDefaults() { return this.apiVersionDefaults; } /** * The ApiVersionLocals object to access its operations. */ private ApiVersionLocals apiVersionLocals; /** * Gets the ApiVersionLocals object to access its operations. * @return the ApiVersionLocals object. */ public ApiVersionLocals apiVersionLocals() { return this.apiVersionLocals; } /** * The SkipUrlEncodings object to access its operations. */ private SkipUrlEncodings skipUrlEncodings; /** * Gets the SkipUrlEncodings object to access its operations. * @return the SkipUrlEncodings object. */ public SkipUrlEncodings skipUrlEncodings() { return this.skipUrlEncodings; } /** * The Odatas object to access its operations. */ private Odatas odatas; /** * Gets the Odatas object to access its operations. * @return the Odatas object. */ public Odatas odatas() { return this.odatas; } /** * The Headers object to access its operations. */ private Headers headers; /** * Gets the Headers object to access its operations. * @return the Headers object. */ public Headers headers() { return this.headers; } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param credentials the management credentials for Azure */ public AutoRestAzureSpecialParametersTestClientImpl(ServiceClientCredentials credentials) { this("http://localhost", credentials); } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param baseUrl the base URL of the host * @param credentials the management credentials for Azure */ public AutoRestAzureSpecialParametersTestClientImpl(String baseUrl, ServiceClientCredentials credentials) { this(new RestClient.Builder() .withBaseUrl(baseUrl) .withCredentials(credentials) .build()); } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param restClient the REST client to connect to Azure. */ public AutoRestAzureSpecialParametersTestClientImpl(RestClient restClient) { super(restClient); initialize(); } protected void initialize() { this.apiVersion = "2015-07-01-preview"; this.acceptLanguage = "en-US"; this.longRunningOperationRetryTimeout = 30; this.generateClientRequestId = true; this.xMsClientRequestIds = new XMsClientRequestIdsImpl(restClient().retrofit(), this); this.subscriptionInCredentials = new SubscriptionInCredentialsImpl(restClient().retrofit(), this); this.subscriptionInMethods = new SubscriptionInMethodsImpl(restClient().retrofit(), this); this.apiVersionDefaults = new ApiVersionDefaultsImpl(restClient().retrofit(), this); this.apiVersionLocals = new ApiVersionLocalsImpl(restClient().retrofit(), this); this.skipUrlEncodings = new SkipUrlEncodingsImpl(restClient().retrofit(), this); this.odatas = new OdatasImpl(restClient().retrofit(), this); this.headers = new HeadersImpl(restClient().retrofit(), this); this.azureClient = new AzureClient(this); } /** * Gets the User-Agent header for the client. * * @return the user agent string. */ @Override public String userAgent() { return String.format("Azure-SDK-For-Java/%s (%s)", getClass().getPackage().getImplementationVersion(), "AutoRestAzureSpecialParametersTestClient, 2015-07-01-preview"); } }
yaqiyang/autorest
src/generator/AutoRest.Java.Azure.Tests/src/main/java/fixtures/azurespecials/implementation/AutoRestAzureSpecialParametersTestClientImpl.java
Java
mit
10,599
package org.jabref.benchmarks; import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import org.jabref.Globals; import org.jabref.logic.exporter.BibtexDatabaseWriter; import org.jabref.logic.exporter.SavePreferences; import org.jabref.logic.exporter.StringSaveSession; import org.jabref.logic.formatter.bibtexfields.HtmlToLatexFormatter; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.layout.format.HTMLChars; import org.jabref.logic.layout.format.LatexToUnicodeFormatter; import org.jabref.logic.search.SearchQuery; import org.jabref.model.Defaults; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.database.BibDatabaseModeDetection; import org.jabref.model.entry.BibEntry; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.groups.KeywordGroup; import org.jabref.model.groups.WordKeywordGroup; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.JabRefPreferences; import org.openjdk.jmh.Main; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.RunnerException; @State(Scope.Thread) public class Benchmarks { private String bibtexString; private final BibDatabase database = new BibDatabase(); private String latexConversionString; private String htmlConversionString; @Setup public void init() throws Exception { Globals.prefs = JabRefPreferences.getInstance(); Random randomizer = new Random(); for (int i = 0; i < 1000; i++) { BibEntry entry = new BibEntry(); entry.setCiteKey("id" + i); entry.setField("title", "This is my title " + i); entry.setField("author", "Firstname Lastname and FirstnameA LastnameA and FirstnameB LastnameB" + i); entry.setField("journal", "Journal Title " + i); entry.setField("keyword", "testkeyword"); entry.setField("year", "1" + i); entry.setField("rnd", "2" + randomizer.nextInt()); database.insertEntry(entry); } BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new); StringSaveSession saveSession = databaseWriter.savePartOfDatabase( new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences()); bibtexString = saveSession.getStringValue(); latexConversionString = "{A} \\textbf{bold} approach {\\it to} ${{\\Sigma}}{\\Delta}$ modulator \\textsuperscript{2} \\$"; htmlConversionString = "<b>&Ouml;sterreich</b> &#8211; &amp; characters &#x2aa2; <i>italic</i>"; } @Benchmark public ParserResult parse() throws IOException { BibtexParser parser = new BibtexParser(Globals.prefs.getImportFormatPreferences()); return parser.parse(new StringReader(bibtexString)); } @Benchmark public String write() throws Exception { BibtexDatabaseWriter<StringSaveSession> databaseWriter = new BibtexDatabaseWriter<>(StringSaveSession::new); StringSaveSession saveSession = databaseWriter.savePartOfDatabase( new BibDatabaseContext(database, new MetaData(), new Defaults()), database.getEntries(), new SavePreferences()); return saveSession.getStringValue(); } @Benchmark public List<BibEntry> search() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false); return database.getEntries().stream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public List<BibEntry> parallelSearch() { // FIXME: Reuse SearchWorker here SearchQuery searchQuery = new SearchQuery("Journal Title 500", false, false); return database.getEntries().parallelStream().filter(searchQuery::isMatch).collect(Collectors.toList()); } @Benchmark public BibDatabaseMode inferBibDatabaseMode() { return BibDatabaseModeDetection.inferMode(database); } @Benchmark public String latexToUnicodeConversion() { LatexToUnicodeFormatter f = new LatexToUnicodeFormatter(); return f.format(latexConversionString); } @Benchmark public String latexToHTMLConversion() { HTMLChars f = new HTMLChars(); return f.format(latexConversionString); } @Benchmark public String htmlToLatexConversion() { HtmlToLatexFormatter f = new HtmlToLatexFormatter(); return f.format(htmlConversionString); } @Benchmark public boolean keywordGroupContains() throws ParseException { KeywordGroup group = new WordKeywordGroup("testGroup", GroupHierarchyType.INDEPENDENT, "keyword", "testkeyword", false, ',', false); return group.containsAll(database.getEntries()); } public static void main(String[] args) throws IOException, RunnerException { Main.main(args); } }
shitikanth/jabref
src/jmh/java/org/jabref/benchmarks/Benchmarks.java
Java
mit
5,418
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Order\Model; use Doctrine\Common\Collections\Collection; use Sylius\Component\Resource\Model\SoftDeletableInterface; use Sylius\Component\Resource\Model\TimestampableInterface; use Sylius\Component\Sequence\Model\SequenceSubjectInterface; /** * Order interface. * * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface OrderInterface extends AdjustableInterface, TimestampableInterface, SoftDeletableInterface, SequenceSubjectInterface { const STATE_CART = 'cart'; const STATE_CART_LOCKED = 'cart_locked'; const STATE_PENDING = 'pending'; const STATE_CONFIRMED = 'confirmed'; const STATE_SHIPPED = 'shipped'; const STATE_ABANDONED = 'abandoned'; const STATE_CANCELLED = 'cancelled'; const STATE_RETURNED = 'returned'; /** * Has the order been completed by user and can be handled. * * @return Boolean */ public function isCompleted(); /** * Mark the order as completed. */ public function complete(); /** * Return completion date. * * @return \DateTime */ public function getCompletedAt(); /** * Set completion time. * * @param null|\DateTime $completedAt */ public function setCompletedAt(\DateTime $completedAt = null); /** * Get order items. * * @return Collection|OrderItemInterface[] An array or collection of OrderItemInterface */ public function getItems(); /** * Set items. * * @param Collection|OrderItemInterface[] $items */ public function setItems(Collection $items); /** * Returns number of order items. * * @return integer */ public function countItems(); /** * Adds item to order. * * @param OrderItemInterface $item */ public function addItem(OrderItemInterface $item); /** * Remove item from order. * * @param OrderItemInterface $item */ public function removeItem(OrderItemInterface $item); /** * Has item in order? * * @param OrderItemInterface $item * * @return Boolean */ public function hasItem(OrderItemInterface $item); /** * Get items total. * * @return integer */ public function getItemsTotal(); /** * Calculate items total based on the items * unit prices and quantities. */ public function calculateItemsTotal(); /** * Get order total. * * @return integer */ public function getTotal(); /** * Set total. * * @param integer $total */ public function setTotal($total); /** * Calculate total. * Items total + Adjustments total. */ public function calculateTotal(); /** * Alias of {@link countItems()}. * * @deprecated To be removed in 1.0. Use {@link countItems()} instead. */ public function getTotalItems(); /** * Returns total quantity of items in cart. * * @return integer */ public function getTotalQuantity(); /** * Checks whether the cart is empty or not. * * @return Boolean */ public function isEmpty(); /** * Clears all items in cart. */ public function clearItems(); /** * Get order state. * * @return string */ public function getState(); /** * Set order state. * * @param string $state */ public function setState($state); }
gonzalovilaseca/Sylius
src/Sylius/Component/Order/Model/OrderInterface.php
PHP
mit
3,770
<?php namespace PayPal\Common; class PPReflectionUtil { /** * @var array|ReflectionMethod[] */ private static $propertiesRefl = array(); /** * @var array|string[] */ private static $propertiesType = array(); /** * * @param string $class * @param string $propertyName */ public static function getPropertyClass($class, $propertyName) { if (($annotations = self::propertyAnnotations($class, $propertyName)) && isset($annotations['return'])) { // if (substr($annotations['param'], -2) === '[]') { // $param = substr($annotations['param'], 0, -2); // } $param = $annotations['return']; } if(isset($param)) { $anno = explode(' ', $param); return $anno[0]; } else { return 'string'; } } /** * @param string $class * @param string $propertyName * @throws RuntimeException * @return string */ public static function propertyAnnotations($class, $propertyName) { $class = is_object($class) ? get_class($class) : $class; if (!class_exists('ReflectionProperty')) { throw new \RuntimeException("Property type of " . $class . "::{$propertyName} cannot be resolved"); } if ($annotations =& self::$propertiesType[$class][$propertyName]) { return $annotations; } if (!($refl =& self::$propertiesRefl[$class][$propertyName])) { $getter = method_exists($class, "get" . ucfirst($propertyName)) ? "get". ucfirst($propertyName) : "get". preg_replace("/([_-\s]?([a-z0-9]+))/e", "ucwords('\\2')", $propertyName); $refl = new \ReflectionMethod($class, $getter); self::$propertiesRefl[$class][$propertyName] = $refl; } // todo: smarter regexp if (!preg_match_all('~\@([^\s@\(]+)[\t ]*(?:\(?([^\n@]+)\)?)?~i', $refl->getDocComment(), $annots, PREG_PATTERN_ORDER)) { return NULL; } foreach ($annots[1] as $i => $annot) { $annotations[strtolower($annot)] = empty($annots[2][$i]) ? TRUE : rtrim($annots[2][$i], " \t\n\r)"); } return $annotations; } }
dip712204123/kidskula
vendor/paypal/sdk-core-php/lib/PayPal/Common/PPReflectionUtil.php
PHP
mit
1,972
// #docplaster // #docregion import { Component } from '@angular/core'; import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser'; @Component({ selector: 'app-bypass-security', templateUrl: './bypass-security.component.html', }) export class BypassSecurityComponent { dangerousUrl: string; trustedUrl: SafeUrl; dangerousVideoUrl!: string; videoUrl!: SafeResourceUrl; // #docregion trust-url constructor(private sanitizer: DomSanitizer) { // javascript: URLs are dangerous if attacker controlled. // Angular sanitizes them in data binding, but you can // explicitly tell Angular to trust this value: this.dangerousUrl = 'javascript:alert("Hi there")'; this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl); // #enddocregion trust-url this.updateVideoUrl('PUBnlbjZFAI'); } // #docregion trust-video-url updateVideoUrl(id: string) { // Appending an ID to a YouTube URL is safe. // Always make sure to construct SafeValue objects as // close as possible to the input data so // that it's easier to check if the value is safe. this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id; this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl); } // #enddocregion trust-video-url }
ocombe/angular
aio/content/examples/security/src/app/bypass-security.component.ts
TypeScript
mit
1,340
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("../../utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); /** * @ignore - internal component. */ var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" }), 'Star'); exports.default = _default;
cdnjs/cdnjs
ajax/libs/material-ui/5.0.0-alpha.36/node/internal/svg-icons/Star.js
JavaScript
mit
738
/** * Copyright (c) 2014,2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.smarthome.core.library.items; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.library.CoreItemFactory; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.UnDefType; /** * A DimmerItem can be used as a switch (ON/OFF), but it also accepts percent values * to reflect the dimmed state. * * @author Kai Kreuzer - Initial contribution and API * @author Markus Rathgeb - Support more types for getStateAs * */ @NonNullByDefault public class DimmerItem extends SwitchItem { private static List<Class<? extends State>> acceptedDataTypes = new ArrayList<Class<? extends State>>(); private static List<Class<? extends Command>> acceptedCommandTypes = new ArrayList<Class<? extends Command>>(); static { acceptedDataTypes.add(PercentType.class); acceptedDataTypes.add(OnOffType.class); acceptedDataTypes.add(UnDefType.class); acceptedCommandTypes.add(PercentType.class); acceptedCommandTypes.add(OnOffType.class); acceptedCommandTypes.add(IncreaseDecreaseType.class); acceptedCommandTypes.add(RefreshType.class); } public DimmerItem(String name) { super(CoreItemFactory.DIMMER, name); } /* package */ DimmerItem(String type, String name) { super(type, name); } public void send(PercentType command) { internalSend(command); } @Override public List<Class<? extends State>> getAcceptedDataTypes() { return Collections.unmodifiableList(acceptedDataTypes); } @Override public List<Class<? extends Command>> getAcceptedCommandTypes() { return Collections.unmodifiableList(acceptedCommandTypes); } @Override public void setState(State state) { if (isAcceptedState(acceptedDataTypes, state)) { // try conversion State convertedState = state.as(PercentType.class); if (convertedState != null) { applyState(convertedState); } else { applyState(state); } } else { logSetTypeError(state); } } }
Snickermicker/smarthome
bundles/core/org.eclipse.smarthome.core/src/main/java/org/eclipse/smarthome/core/library/items/DimmerItem.java
Java
epl-1.0
3,066
/* * ome.server.itests.ImmutabilityTest * * Copyright 2006 University of Dundee. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package ome.server.itests; // Java imports // Third-party libraries import org.testng.annotations.Test; // Application-internal dependencies import ome.model.core.Image; import ome.model.meta.Event; import ome.parameters.Filter; import ome.parameters.Parameters; /** * * @author Josh Moore &nbsp;&nbsp;&nbsp;&nbsp; <a * href="mailto:josh.moore@gmx.de">josh.moore@gmx.de</a> * @version 1.0 <small> (<b>Internal version:</b> $Rev$ $Date$) </small> * @since 1.0 */ public class ImmutabilityTest extends AbstractManagedContextTest { @Test public void testCreationEventWillBeSilentlyUnchanged() throws Exception { loginRoot(); Image i = new_Image("immutable creation"); i = iUpdate.saveAndReturnObject(i); Event oldEvent = i.getDetails().getCreationEvent(); Event newEvent = iQuery.findByQuery( "select e from Event e where id != :id", new Parameters( new Filter().page(0, 1)).addId(oldEvent.getId())); i.getDetails().setCreationEvent(newEvent); // This fails because it gets silently copied to our new instance. See: // http://trac.openmicroscopy.org.uk/ome/ticket/346 // i = iUpdate.saveAndReturnObject(i); // assertEquals( i.getDetails().getCreationEvent().getId(), // oldEvent.getId()); // Saving and reacquiring to be sure. iUpdate.saveObject(i); // unfortunately still not working properly i = iQuery.refresh(i); i = iQuery.get(i.getClass(), i.getId()); assertEquals(i.getDetails().getCreationEvent().getId(), oldEvent .getId()); } }
bramalingam/openmicroscopy
components/server/test/ome/server/itests/ImmutabilityTest.java
Java
gpl-2.0
1,831
/**************************************************************************************** * Copyright (c) 2007 Nikolaj Hald Nielsen <nhn@kde.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/>. * ****************************************************************************************/ #include "core/capabilities/ActionsCapability.h" Capabilities::ActionsCapability::ActionsCapability() : Capabilities::Capability() { //nothing to do } Capabilities::ActionsCapability::ActionsCapability( const QList<QAction*> &actions ) : Capabilities::Capability() , m_actions( actions ) { //nothing to do } Capabilities::ActionsCapability::~ActionsCapability() { //nothing to do. } QList<QAction *> Capabilities::ActionsCapability::actions() const { return m_actions; } #include "ActionsCapability.moc"
orangejulius/amarok
src/core/capabilities/ActionsCapability.cpp
C++
gpl-2.0
1,889
/* * Copyright (c) 2018, 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. */ #include "native_thread.cpp" #include "nsk_tools.cpp" #include "jni_tools.cpp" #include "jvmti_tools.cpp" #include "agent_tools.cpp" #include "jvmti_FollowRefObjects.cpp" #include "Injector.cpp" #include "JVMTITools.cpp" #include "SetNativeMethodPrefix002Main.cpp"
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/jvmti/SetNativeMethodPrefix/SetNativeMethodPrefix002/libSetNativeMethodPrefix002Main.cpp
C++
gpl-2.0
1,317
<?php $lan = array ( 'This page can only be called from the commandline' => '这个页面只能够透过指令模式启用', 'Bounce processing error' => '退信处理错误', 'Bounce Processing info' => '退信处理讯息', 'error' => '错误', 'info' => '讯息', 'system message bounced, user marked unconfirmed' => '系统退信产生,使用者标示为未确认', 'Bounced system message' => '系统退信', 'User marked unconfirmed' => '使用者标示为未确认', 'View Bounce' => '浏览退信', 'Cannot create POP3 connection to' => '无法建立 POP3 连线于', 'Cannot open mailbox file' => '无法开启邮件档桉', 'bounces to fetch from the mailbox' => '封退信于信箱', 'Please do not interrupt this process' => '请不要中断这个处理程序', 'bounces to process' => '封退信待处理', 'Processing first' => '处理第一', 'bounces' => '封退信', 'Running in test mode, not deleting messages from mailbox' => '目前在测试模式中,无法从信箱删除信件', 'Processed messages will be deleted from mailbox' => '处理的信件将会从信箱删除', 'Deleting message' => '删除信件中', 'Closing mailbox, and purging messages' => '关闭信箱并且清除信件', 'IMAP is not included in your PHP installation, cannot continue' => '您的 PHP 不支援 IMAP ,无法继续', 'Check out' => '签出', 'Bounce mechanism not properly configured' => '退信机制也许还没设定', 'bounce_protocol not supported' => '不支援 bounce_protocol', 'Identifying consecutive bounces' => '辨识连续性退信', 'Nothing to do' => '没有动作', 'Process Killed by other process' => '处理程序被其他程序中止', 'User' => '使用者', 'has consecutive bounces' => '有连续退信', 'over threshold, user marked unconfirmed' => '超过系统设定,因此标示为未确认', 'Auto Unsubscribed' => '自动取消订阅', 'User auto unsubscribed for' => '使用者自动取消订阅于', 'consecutive bounces' => '连续退信', 'of' => '于', 'users processed' => '个使用者处理完成', 'processing first' => '处理第一封', 'Report:' => '报表:', 'Below are users who have been marked unconfirmed. The number in [' => '下面是未确认的使用者, [] 中的数字是他们的编号, () 中的数字代表他们有多少封退信', 'Processing bounces based on active bounce rules' => '透过启用中的退信规则处理退信', 'Auto Blacklisted' => '自动列为黑名单', 'User auto blacklisted for' => '使用者自动被列为黑名单于', 'bounce rule' => '退信规则', 'system message bounced, but unknown user' => '系统退回信件,但是没有符合的使用者', 'bounces processed by advanced processing' => '封退信经由进阶处理程序处理', 'bounces were not matched by advanced processing rules' => '封退信不符合进阶处理规则', 'Report of advanced bounce processing:' => '进阶退信处理报表:', ); ?>
washingtonstateuniversity/WSU-Lists
www/admin/lan/zh_CN/processbounces.php
PHP
gpl-2.0
3,020
<?php // $Header: /cvsroot/html2ps/box.text.php,v 1.56 2007/05/07 12:15:53 Konstantin Exp $ require_once(HTML2PS_DIR.'box.inline.simple.php'); // TODO: from my POV, it wll be better to pass the font- or CSS-controlling object to the constructor // instead of using globally visible functions in 'show'. define('SYMBOL_NBSP', chr(160)); class TextBox extends SimpleInlineBox { var $words; var $encodings; var $hyphens; var $_widths; var $_word_widths; var $_wrappable; var $wrapped; function TextBox() { $this->SimpleInlineBox(); $this->words = array(); $this->encodings = array(); $this->hyphens = array(); $this->_word_widths = array(); $this->_wrappable = array(); $this->wrapped = null; $this->_widths = array(); $this->font_size = 0; $this->ascender = 0; $this->descender = 0; $this->width = 0; $this->height = 0; } /** * Check if given subword contains soft hyphens and calculate */ function _make_wrappable(&$driver, $base_width, $font_name, $font_size, $subword_index) { $hyphens = $this->hyphens[$subword_index]; $wrappable = array(); foreach ($hyphens as $hyphen) { $subword_wrappable_index = $hyphen; $subword_wrappable_width = $base_width + $driver->stringwidth(substr($this->words[$subword_index], 0, $subword_wrappable_index), $font_name, $this->encodings[$subword_index], $font_size); $subword_full_width = $subword_wrappable_width + $driver->stringwidth('-', $font_name, "iso-8859-1", $font_size); $wrappable[] = array($subword_index, $subword_wrappable_index, $subword_wrappable_width, $subword_full_width); }; return $wrappable; } function get_content() { return join('', array_map(array($this, 'get_content_callback'), $this->words, $this->encodings)); } function get_content_callback($word, $encoding) { $manager_encoding =& ManagerEncoding::get(); return $manager_encoding->toUTF8($word, $encoding); } function get_height() { return $this->height; } function put_height($value) { $this->height = $value; } // Apply 'line-height' CSS property; modifies the default_baseline value // (NOT baseline, as it is calculated - and is overwritten - in the close_line // method of container box // // Note that underline position (or 'descender' in terms of PDFLIB) - // so, simple that space of text box under the baseline - is scaled too // when 'line-height' is applied // function _apply_line_height() { $height = $this->get_height(); $under = $height - $this->default_baseline; $line_height = $this->getCSSProperty(CSS_LINE_HEIGHT); if ($height > 0) { $scale = $line_height->apply($this->ascender + $this->descender) / ($this->ascender + $this->descender); } else { $scale = 0; }; // Calculate the height delta of the text box $delta = $height * ($scale-1); $this->put_height(($this->ascender + $this->descender)*$scale); $this->default_baseline = $this->default_baseline + $delta/2; } function _get_font_name(&$viewport, $subword_index) { if (isset($this->_cache[CACHE_TYPEFACE][$subword_index])) { return $this->_cache[CACHE_TYPEFACE][$subword_index]; }; $font_resolver =& $viewport->get_font_resolver(); $font = $this->getCSSProperty(CSS_FONT); $typeface = $font_resolver->getTypefaceName($font->family, $font->weight, $font->style, $this->encodings[$subword_index]); $this->_cache[CACHE_TYPEFACE][$subword_index] = $typeface; return $typeface; } function add_subword($raw_subword, $encoding, $hyphens) { $text_transform = $this->getCSSProperty(CSS_TEXT_TRANSFORM); switch ($text_transform) { case CSS_TEXT_TRANSFORM_CAPITALIZE: $subword = ucwords($raw_subword); break; case CSS_TEXT_TRANSFORM_UPPERCASE: $subword = strtoupper($raw_subword); break; case CSS_TEXT_TRANSFORM_LOWERCASE: $subword = strtolower($raw_subword); break; case CSS_TEXT_TRANSFORM_NONE: $subword = $raw_subword; break; } $this->words[] = $subword; $this->encodings[] = $encoding; $this->hyphens[] = $hyphens; } function &create($text, $encoding, &$pipeline) { $box =& TextBox::create_empty($pipeline); $box->add_subword($text, $encoding, array()); return $box; } function &create_empty(&$pipeline) { $box =& new TextBox(); $css_state = $pipeline->getCurrentCSSState(); $box->readCSS($css_state); $css_state = $pipeline->getCurrentCSSState(); return $box; } function readCSS(&$state) { parent::readCSS($state); $this->_readCSSLengths($state, array(CSS_TEXT_INDENT, CSS_LETTER_SPACING)); } // Inherited from GenericFormattedBox function get_descender() { return $this->descender; } function get_ascender() { return $this->ascender; } function get_baseline() { return $this->baseline; } function get_min_width_natural(&$context) { return $this->get_full_width(); } function get_min_width(&$context) { return $this->get_full_width(); } function get_max_width(&$context) { return $this->get_full_width(); } // Checks if current inline box should cause a line break inside the parent box // // @param $parent reference to a parent box // @param $content flow context // @return true if line break occurred; false otherwise // function maybe_line_break(&$parent, &$context) { if (!$parent->line_break_allowed()) { return false; }; $last =& $parent->last_in_line(); if ($last) { // Check if last box was a note call box. Punctuation marks // after a note-call box should not be wrapped to new line, // while "plain" words may be wrapped. if ($last->is_note_call() && $this->is_punctuation()) { return false; }; }; // Calculate the x-coordinate of this box right edge $right_x = $this->get_full_width() + $parent->_current_x; $need_break = false; // Check for right-floating boxes // If upper-right corner of this inline box is inside of some float, wrap the line $float = $context->point_in_floats($right_x, $parent->_current_y); if ($float) { $need_break = true; }; // No floats; check if we had run out the right edge of container // TODO: nobr-before, nobr-after if (($right_x > $parent->get_right()+EPSILON)) { // Now check if parent line box contains any other boxes; // if not, we should draw this box unless we have a floating box to the left $first = $parent->get_first(); $ti = $this->getCSSProperty(CSS_TEXT_INDENT); $indent_offset = $ti->calculate($parent); if ($parent->_current_x > $parent->get_left() + $indent_offset + EPSILON) { $need_break = true; }; } // As close-line will not change the current-Y parent coordinate if no // items were in the line box, we need to offset this explicitly in this case // if ($parent->line_box_empty() && $need_break) { $parent->_current_y -= $this->get_height(); }; if ($need_break) { // Check if current box contains soft hyphens and use them, breaking word into parts $size = count($this->_wrappable); if ($size > 0) { $width_delta = $right_x - $parent->get_right(); if (!is_null($float)) { $width_delta = $right_x - $float->get_left_margin(); }; $this->_find_soft_hyphen($parent, $width_delta); }; $parent->close_line($context); // Check if parent inline boxes have left padding/margins and add them to current_x $element = $this->parent; while (!is_null($element) && is_a($element,"GenericInlineBox")) { $parent->_current_x += $element->get_extra_left(); $element = $element->parent; }; }; return $need_break; } function _find_soft_hyphen(&$parent, $width_delta) { /** * Now we search for soft hyphen closest to the right margin */ $size = count($this->_wrappable); for ($i=$size-1; $i>=0; $i--) { $wrappable = $this->_wrappable[$i]; if ($this->get_width() - $wrappable[3] > $width_delta) { $this->save_wrapped($wrappable, $parent, $context); $parent->append_line($this); return; }; }; } function save_wrapped($wrappable, &$parent, &$context) { $this->wrapped = array($wrappable, $parent->_current_x + $this->get_extra_left(), $parent->_current_y - $this->get_extra_top()); } function reflow(&$parent, &$context) { // Check if we need a line break here (possilble several times in a row, if we // have a long word and a floating box intersecting with this word // // To prevent infinite loop, we'll use a limit of 100 sequental line feeds $i=0; do { $i++; } while ($this->maybe_line_break($parent, $context) && $i < 100); // Determine the baseline position and height of the text-box using line-height CSS property $this->_apply_line_height(); // set default baseline $this->baseline = $this->default_baseline; // append current box to parent line box $parent->append_line($this); // Determine coordinates of upper-left _margin_ corner $this->guess_corner($parent); // Offset parent current X coordinate if (!is_null($this->wrapped)) { $parent->_current_x += $this->get_full_width() - $this->wrapped[0][2]; } else { $parent->_current_x += $this->get_full_width(); }; // Extends parents height $parent->extend_height($this->get_bottom()); // Update the value of current collapsed margin; pure text (non-span) // boxes always have zero margin $context->pop_collapsed_margin(); $context->push_collapsed_margin( 0 ); } function getWrappedWidthAndHyphen() { return $this->wrapped[0][3]; } function getWrappedWidth() { return $this->wrapped[0][2]; } function reflow_text(&$driver) { $num_words = count($this->words); /** * Empty text box */ if ($num_words == 0) { return true; }; /** * A simple assumption is made: fonts used for different encodings * have equal ascender/descender values (while they have the same * typeface, style and weight). */ $font_name = $this->_get_font_name($driver, 0); /** * Get font vertical metrics */ $ascender = $driver->font_ascender($font_name, $this->encodings[0]); if (is_null($ascender)) { error_log("TextBox::reflow_text: cannot get font ascender"); return null; }; $descender = $driver->font_descender($font_name, $this->encodings[0]); if (is_null($descender)) { error_log("TextBox::reflow_text: cannot get font descender"); return null; }; /** * Setup box size */ $font = $this->getCSSProperty(CSS_FONT_SIZE); $font_size = $font->getPoints(); // Both ascender and descender should make $font_size // as it is not guaranteed that $ascender + $descender == 1, // we should normalize the result $koeff = $font_size / ($ascender + $descender); $this->ascender = $ascender * $koeff; $this->descender = $descender * $koeff; $this->default_baseline = $this->ascender; $this->height = $this->ascender + $this->descender; /** * Determine box width */ if ($font_size > 0) { $width = 0; for ($i=0; $i<$num_words; $i++) { $font_name = $this->_get_font_name($driver, $i); $current_width = $driver->stringwidth($this->words[$i], $font_name, $this->encodings[$i], $font_size); $this->_word_widths[] = $current_width; // Add information about soft hyphens $this->_wrappable = array_merge($this->_wrappable, $this->_make_wrappable($driver, $width, $font_name, $font_size, $i)); $width += $current_width; }; $this->width = $width; } else { $this->width = 0; }; $letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING); if ($letter_spacing->getPoints() != 0) { $this->_widths = array(); for ($i=0; $i<$num_words; $i++) { $num_chars = strlen($this->words[$i]); for ($j=0; $j<$num_chars; $j++) { $this->_widths[] = $driver->stringwidth($this->words[$i]{$j}, $font_name, $this->encodings[$i], $font_size); }; $this->width += $letter_spacing->getPoints()*$num_chars; }; }; return true; } function show(&$driver) { /** * Check if font-size have been set to 0; in this case we should not draw this box at all */ $font_size = $this->getCSSProperty(CSS_FONT_SIZE); if ($font_size->getPoints() == 0) { return true; } // Check if current text box will be cut-off by the page edge // Get Y coordinate of the top edge of the box $top = $this->get_top_margin(); // Get Y coordinate of the bottom edge of the box $bottom = $this->get_bottom_margin(); $top_inside = $top >= $driver->getPageBottom()-EPSILON; $bottom_inside = $bottom >= $driver->getPageBottom()-EPSILON; if (!$top_inside && !$bottom_inside) { return true; } return $this->_showText($driver); } function _showText(&$driver) { if (!is_null($this->wrapped)) { return $this->_showTextWrapped($driver); } else { return $this->_showTextNormal($driver); }; } function _showTextWrapped(&$driver) { // draw generic box parent::show($driver); $font_size = $this->getCSSProperty(CSS_FONT_SIZE); $decoration = $this->getCSSProperty(CSS_TEXT_DECORATION); // draw text decoration $driver->decoration($decoration['U'], $decoration['O'], $decoration['T']); $letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING); // Output text with the selected font // note that we're using $default_baseline; // the alignment offset - the difference between baseline and default_baseline values // is taken into account inside the get_top/get_bottom functions // $current_char = 0; $left = $this->wrapped[1]; $top = $this->get_top() - $this->default_baseline; $num_words = count($this->words); /** * First part of wrapped word (before hyphen) */ for ($i=0; $i<$this->wrapped[0][0]; $i++) { // Activate font $status = $driver->setfont($this->_get_font_name($driver, $i), $this->encodings[$i], $font_size->getPoints()); if (is_null($status)) { error_log("TextBox::show: setfont call failed"); return null; }; $driver->show_xy($this->words[$i], $left, $this->wrapped[2] - $this->default_baseline); $left += $this->_word_widths[$i]; }; $index = $this->wrapped[0][0]; $status = $driver->setfont($this->_get_font_name($driver, $index), $this->encodings[$index], $font_size->getPoints()); if (is_null($status)) { error_log("TextBox::show: setfont call failed"); return null; }; $driver->show_xy(substr($this->words[$index],0,$this->wrapped[0][1])."-", $left, $this->wrapped[2] - $this->default_baseline); /** * Second part of wrapped word (after hyphen) */ $left = $this->get_left(); $top = $this->get_top(); $driver->show_xy(substr($this->words[$index],$this->wrapped[0][1]), $left, $top - $this->default_baseline); $size = count($this->words); for ($i = $this->wrapped[0][0]+1; $i<$size; $i++) { // Activate font $status = $driver->setfont($this->_get_font_name($driver, $i), $this->encodings[$i], $font_size->getPoints()); if (is_null($status)) { error_log("TextBox::show: setfont call failed"); return null; }; $driver->show_xy($this->words[$i], $left, $top - $this->default_baseline); $left += $this->_word_widths[$i]; }; return true; } function _showTextNormal(&$driver) { // draw generic box parent::show($driver); $font_size = $this->getCSSProperty(CSS_FONT_SIZE); $decoration = $this->getCSSProperty(CSS_TEXT_DECORATION); // draw text decoration $driver->decoration($decoration['U'], $decoration['O'], $decoration['T']); $letter_spacing = $this->getCSSProperty(CSS_LETTER_SPACING); if ($letter_spacing->getPoints() == 0) { // Output text with the selected font // note that we're using $default_baseline; // the alignment offset - the difference between baseline and default_baseline values // is taken into account inside the get_top/get_bottom functions // $size = count($this->words); $left = $this->get_left(); for ($i=0; $i<$size; $i++) { // Activate font $status = $driver->setfont($this->_get_font_name($driver, $i), $this->encodings[$i], $font_size->getPoints()); if (is_null($status)) { error_log("TextBox::show: setfont call failed"); return null; }; $driver->show_xy($this->words[$i], $left, $this->get_top() - $this->default_baseline); $left += $this->_word_widths[$i]; }; } else { $current_char = 0; $left = $this->get_left(); $top = $this->get_top() - $this->default_baseline; $num_words = count($this->words); for ($i=0; $i<$num_words; $i++) { $num_chars = strlen($this->words[$i]); for ($j=0; $j<$num_chars; $j++) { $status = $driver->setfont($this->_get_font_name($driver, $i), $this->encodings[$i], $font_size->getPoints()); $driver->show_xy($this->words[$i]{$j}, $left, $top); $left += $this->_widths[$current_char] + $letter_spacing->getPoints(); $current_char++; }; }; }; return true; } function show_fixed(&$driver) { $font_size = $this->getCSSProperty(CSS_FONT_SIZE); // Check if font-size have been set to 0; in this case we should not draw this box at all if ($font_size->getPoints() == 0) { return true; } return $this->_showText($driver); } function offset($dx, $dy) { parent::offset($dx, $dy); // Note that horizonal offset should be called explicitly from text-align routines // otherwise wrapped part will be offset twice (as offset is called both for // wrapped and non-wrapped parts). if (!is_null($this->wrapped)) { $this->offset_wrapped($dx, $dy); }; } function offset_wrapped($dx, $dy) { $this->wrapped[1] += $dx; $this->wrapped[2] += $dy; } function reflow_whitespace(&$linebox_started, &$previous_whitespace) { $linebox_started = true; $previous_whitespace = false; return; } function is_null() { return false; } } ?>
maent45/PersianFeast
simpleinvoices/library/pdf/box.text.php
PHP
gpl-2.0
20,574
/* Copyright (C) 2009 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 */ using System; using System.Text.RegularExpressions; using System.Windows.Forms; namespace WikiFunctions { /// <summary> /// Factory class for making instances of IArticleComparer /// </summary> public static class ArticleComparerFactory { /// <summary> /// /// </summary> /// <param name="comparator">The test string</param> /// <param name="isCaseSensitive">Whether the comparison should be case sensitive</param> /// <param name="isRegex">Whether to employ regular expression matching when comparing the test string</param> /// <param name="isSingleLine">Whether to apply the regular expression Single Line option</param> /// <param name="isMultiLine">Whether to apply the regular expression Multi Line option</param> /// <returns>An instance of IArticleComparer which can carry out the specified comparison</returns> public static IArticleComparer Create(string comparator, bool isCaseSensitive, bool isRegex, bool isSingleLine, bool isMultiLine) { if (comparator == null) throw new ArgumentNullException("comparator"); if (isRegex) { try { RegexOptions opts = RegexOptions.None; if (!isCaseSensitive) opts |= RegexOptions.IgnoreCase; if (isSingleLine) opts |= RegexOptions.Singleline; if (isMultiLine) opts |= RegexOptions.Multiline; return comparator.Contains("%%") ? (IArticleComparer)new DynamicRegexArticleComparer(comparator, opts) : new RegexArticleComparer(new Regex(comparator, opts | RegexOptions.Compiled)); } catch (ArgumentException ex) { //TODO: handle things like "bad regex" here // For now, tell the user then let normal exception handling process it as well MessageBox.Show(ex.Message, "Bad Regex"); throw; } } if (comparator.Contains("%%")) return isCaseSensitive ? (IArticleComparer)new CaseSensitiveArticleComparerWithKeywords(comparator) : new CaseInsensitiveArticleComparerWithKeywords(comparator); return isCaseSensitive ? (IArticleComparer)new CaseSensitiveArticleComparer(comparator) : new CaseInsensitiveArticleComparer(comparator); } } /// <summary> /// Class for scanning an article for content /// </summary> public interface IArticleComparer { /// <summary> /// Compares the article text against the criteria provided /// </summary> /// <param name="article">An article to check</param> /// <returns>Whether the article's text matches the criteria</returns> bool Matches(Article article); } }
svn2github/autowikibrowser
tags/REL_5_3_1/WikiFunctions/Article/Comparers/ArticleComparerFactory.cs
C#
gpl-2.0
3,930
<?php /** * Tabs GK5 - main PHP file * @package Joomla! * @Copyright (C) 2009-2012 Gavick.com * @ All rights reserved * @ Joomla! is Free Software * @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html * @ version $Revision: GK5 1.0 $ **/ defined('JPATH_BASE') or die; jimport('joomla.form.formfield'); class JFormFieldAbout extends JFormField { protected $type = 'About'; protected function getInput() { return '<div id="gk_about_us">' . JText::_('MOD_TABS_ABOUT_US_CONTENT') . '</div>'; } } // EOF
volodymyrdmytriv/levin-25-2
modules/mod_tabs_gk5/admin/elements/about.php
PHP
gpl-2.0
529
/* * uiComponents.CustomLabel * *------------------------------------------------------------------------------ * Copyright (C) 2006-2008 University of Dundee. All rights reserved. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.agents.editor.uiComponents; //Java imports import javax.swing.Icon; import javax.swing.JLabel; //Third-party libraries //Application-internal dependencies /** * A Custom Label, which should be used by the UI instead of using * JLabel. Sets the font to CUSTOM FONT. * * This font is also used by many other Custom UI components in this * package, making it easy to change the font in many components in * one place (here!). * * @author William Moore &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:will@lifesci.dundee.ac.uk">will@lifesci.dundee.ac.uk</a> * @version 3.0 * <small> * (<b>Internal version:</b> $Revision: $Date: $) * </small> * @since OME3.0 */ public class CustomLabel extends JLabel { private int fontSize; /** * Simply delegates to JLabel superclass. */ public CustomLabel() { super(); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(Icon image) { super(image); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(String text) { super(text); setFont(); } /** * Simply delegates to JLabel superclass. */ public CustomLabel(String text, int fontSize) { super(text); this.fontSize = fontSize; setFont(); } private void setFont() { if (fontSize == 0) setFont(new CustomFont()); else { setFont(CustomFont.getFontBySize(fontSize)); } } }
jballanc/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/agents/editor/uiComponents/CustomLabel.java
Java
gpl-2.0
2,450
<?php /** * PEAR_Command_Common base class * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2006 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Common.php 6775 2007-05-22 12:39:39Z andrew.hill@openads.org $ * @link http://pear.php.net/package/PEAR * @since File available since Release 0.1 */ /** * base class */ require_once 'PEAR.php'; /** * PEAR commands base class * * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2006 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: 1.5.4 * @link http://pear.php.net/package/PEAR * @since Class available since Release 0.1 */ class PEAR_Command_Common extends PEAR { // {{{ properties /** * PEAR_Config object used to pass user system and configuration * on when executing commands * * @var PEAR_Config */ var $config; /** * @var PEAR_Registry * @access protected */ var $_registry; /** * User Interface object, for all interaction with the user. * @var object */ var $ui; var $_deps_rel_trans = array( 'lt' => '<', 'le' => '<=', 'eq' => '=', 'ne' => '!=', 'gt' => '>', 'ge' => '>=', 'has' => '==' ); var $_deps_type_trans = array( 'pkg' => 'package', 'ext' => 'extension', 'php' => 'PHP', 'prog' => 'external program', 'ldlib' => 'external library for linking', 'rtlib' => 'external runtime library', 'os' => 'operating system', 'websrv' => 'web server', 'sapi' => 'SAPI backend' ); // }}} // {{{ constructor /** * PEAR_Command_Common constructor. * * @access public */ function PEAR_Command_Common(&$ui, &$config) { parent::PEAR(); $this->config = &$config; $this->ui = &$ui; } // }}} // {{{ getCommands() /** * Return a list of all the commands defined by this class. * @return array list of commands * @access public */ function getCommands() { $ret = array(); foreach (array_keys($this->commands) as $command) { $ret[$command] = $this->commands[$command]['summary']; } return $ret; } // }}} // {{{ getShortcuts() /** * Return a list of all the command shortcuts defined by this class. * @return array shortcut => command * @access public */ function getShortcuts() { $ret = array(); foreach (array_keys($this->commands) as $command) { if (isset($this->commands[$command]['shortcut'])) { $ret[$this->commands[$command]['shortcut']] = $command; } } return $ret; } // }}} // {{{ getOptions() function getOptions($command) { $shortcuts = $this->getShortcuts(); if (isset($shortcuts[$command])) { $command = $shortcuts[$command]; } if (isset($this->commands[$command]) && isset($this->commands[$command]['options'])) { return $this->commands[$command]['options']; } else { return null; } } // }}} // {{{ getGetoptArgs() function getGetoptArgs($command, &$short_args, &$long_args) { $short_args = ""; $long_args = array(); if (empty($this->commands[$command]) || empty($this->commands[$command]['options'])) { return; } reset($this->commands[$command]['options']); while (list($option, $info) = each($this->commands[$command]['options'])) { $larg = $sarg = ''; if (isset($info['arg'])) { if ($info['arg']{0} == '(') { $larg = '=='; $sarg = '::'; $arg = substr($info['arg'], 1, -1); } else { $larg = '='; $sarg = ':'; $arg = $info['arg']; } } if (isset($info['shortopt'])) { $short_args .= $info['shortopt'] . $sarg; } $long_args[] = $option . $larg; } } // }}} // {{{ getHelp() /** * Returns the help message for the given command * * @param string $command The command * @return mixed A fail string if the command does not have help or * a two elements array containing [0]=>help string, * [1]=> help string for the accepted cmd args */ function getHelp($command) { $config = &PEAR_Config::singleton(); if (!isset($this->commands[$command])) { return "No such command \"$command\""; } $help = null; if (isset($this->commands[$command]['doc'])) { $help = $this->commands[$command]['doc']; } if (empty($help)) { // XXX (cox) Fallback to summary if there is no doc (show both?) if (!isset($this->commands[$command]['summary'])) { return "No help for command \"$command\""; } $help = $this->commands[$command]['summary']; } if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) { foreach($matches[0] as $k => $v) { $help = preg_replace("/$v/", $config->get($matches[1][$k]), $help); } } return array($help, $this->getHelpArgs($command)); } // }}} // {{{ getHelpArgs() /** * Returns the help for the accepted arguments of a command * * @param string $command * @return string The help string */ function getHelpArgs($command) { if (isset($this->commands[$command]['options']) && count($this->commands[$command]['options'])) { $help = "Options:\n"; foreach ($this->commands[$command]['options'] as $k => $v) { if (isset($v['arg'])) { if ($v['arg'][0] == '(') { $arg = substr($v['arg'], 1, -1); $sapp = " [$arg]"; $lapp = "[=$arg]"; } else { $sapp = " $v[arg]"; $lapp = "=$v[arg]"; } } else { $sapp = $lapp = ""; } if (isset($v['shortopt'])) { $s = $v['shortopt']; $help .= " -$s$sapp, --$k$lapp\n"; } else { $help .= " --$k$lapp\n"; } $p = " "; $doc = rtrim(str_replace("\n", "\n$p", $v['doc'])); $help .= " $doc\n"; } return $help; } return null; } // }}} // {{{ run() function run($command, $options, $params) { if (empty($this->commands[$command]['function'])) { // look for shortcuts foreach (array_keys($this->commands) as $cmd) { if (isset($this->commands[$cmd]['shortcut']) && $this->commands[$cmd]['shortcut'] == $command) { if (empty($this->commands[$cmd]['function'])) { return $this->raiseError("unknown command `$command'"); } else { $func = $this->commands[$cmd]['function']; } $command = $cmd; break; } } } else { $func = $this->commands[$command]['function']; } return $this->$func($command, $options, $params); } // }}} } ?>
soeffing/openx_test
lib/pear/PEAR/Command/Common.php
PHP
gpl-2.0
8,908
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_XmlConnect * @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Xmlconnect Form field renderer interface * * @category Mage * @package Mage_XmlConnect * @author Magento Core Team <core@magentocommerce.com> */ interface Mage_XmlConnect_Model_Simplexml_Form_Element_Renderer_Interface { public function render(Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract $element); }
keegan2149/magento
sites/default/app/code/core/Mage/XmlConnect/Model/Simplexml/Form/Element/Renderer/Interface.php
PHP
gpl-2.0
1,306
package org.zarroboogs.weibo.hot.bean.hotweibo; import org.json.*; public class TopicStruct { private String topicTitle; private String topicUrl; public TopicStruct () { } public TopicStruct (JSONObject json) { this.topicTitle = json.optString("topic_title"); this.topicUrl = json.optString("topic_url"); } public String getTopicTitle() { return this.topicTitle; } public void setTopicTitle(String topicTitle) { this.topicTitle = topicTitle; } public String getTopicUrl() { return this.topicUrl; } public void setTopicUrl(String topicUrl) { this.topicUrl = topicUrl; } }
JohnTsaiAndroid/iBeebo
app/src/main/java/org/zarroboogs/weibo/hot/bean/hotweibo/TopicStruct.java
Java
gpl-3.0
718
/* Copyright (C) 2010,2012,2016 The ESPResSo project Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010 Max-Planck-Institute for Polymer Research, Theory Group This file is part of ESPResSo. ESPResSo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ESPResSo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file lees_edwards.h Data and methods for Lees-Edwards periodic boundary conditions. The gist of LE-PBCs is to impose shear flow by constantly moving the PBC wrap such that: $x_{unfolded} == x_{folded} + x_{img} \times L + (y_{img} * \gamma * t)$, and $vx_{unfolded} = vx_{folded} + (y_{img} * \gamma)$. */ #ifndef LEES_EDWARDS_H #define LEES_EDWARDS_H #include "config.hpp" extern double lees_edwards_offset, lees_edwards_rate; extern int lees_edwards_count; #ifdef LEES_EDWARDS void lees_edwards_step_boundaries(); #endif //LEES_EDWARDS #endif //LEES_EDWARDS_H
Smiljanic/espresso
src/core/lees_edwards.hpp
C++
gpl-3.0
1,440
<?php /** * @file * @ingroup SpecialPage */ /** * @todo document * @ingroup SpecialPage */ class ProtectedPagesForm { protected $IdLevel = 'level'; protected $IdType = 'type'; public function showList( $msg = '' ) { global $wgOut, $wgRequest; if( $msg != "" ) { $wgOut->setSubtitle( $msg ); } // Purge expired entries on one in every 10 queries if( !mt_rand( 0, 10 ) ) { Title::purgeExpiredRestrictions(); } $type = $wgRequest->getVal( $this->IdType ); $level = $wgRequest->getVal( $this->IdLevel ); $sizetype = $wgRequest->getVal( 'sizetype' ); $size = $wgRequest->getIntOrNull( 'size' ); $NS = $wgRequest->getIntOrNull( 'namespace' ); $indefOnly = $wgRequest->getBool( 'indefonly' ) ? 1 : 0; $cascadeOnly = $wgRequest->getBool('cascadeonly') ? 1 : 0; $pager = new ProtectedPagesPager( $this, array(), $type, $level, $NS, $sizetype, $size, $indefOnly, $cascadeOnly ); $wgOut->addHTML( $this->showOptions( $NS, $type, $level, $sizetype, $size, $indefOnly, $cascadeOnly ) ); if( $pager->getNumRows() ) { $s = $pager->getNavigationBar(); $s .= "<ul>" . $pager->getBody() . "</ul>"; $s .= $pager->getNavigationBar(); } else { $s = '<p>' . wfMsgHtml( 'protectedpagesempty' ) . '</p>'; } $wgOut->addHTML( $s ); } /** * Callback function to output a restriction * @param $row object Protected title * @return string Formatted <li> element */ public function formatRow( $row ) { global $wgUser, $wgLang, $wgContLang; wfProfileIn( __METHOD__ ); static $skin=null; if( is_null( $skin ) ) $skin = $wgUser->getSkin(); $title = Title::makeTitleSafe( $row->page_namespace, $row->page_title ); $link = $skin->link( $title ); $description_items = array (); $protType = wfMsgHtml( 'restriction-level-' . $row->pr_level ); $description_items[] = $protType; if( $row->pr_cascade ) { $description_items[] = wfMsg( 'protect-summary-cascade' ); } $expiry_description = ''; $stxt = ''; if( $row->pr_expiry != 'infinity' && strlen($row->pr_expiry) ) { $expiry = Block::decodeExpiry( $row->pr_expiry ); $expiry_description = wfMsg( 'protect-expiring' , $wgLang->timeanddate( $expiry ) , $wgLang->date( $expiry ) , $wgLang->time( $expiry ) ); $description_items[] = htmlspecialchars($expiry_description); } if(!is_null($size = $row->page_len)) { $stxt = $wgContLang->getDirMark() . ' ' . $skin->formatRevisionSize( $size ); } # Show a link to the change protection form for allowed users otherwise a link to the protection log if( $wgUser->isAllowed( 'protect' ) ) { $changeProtection = ' (' . $skin->linkKnown( $title, wfMsgHtml( 'protect_change' ), array(), array( 'action' => 'unprotect' ) ) . ')'; } else { $ltitle = SpecialPage::getTitleFor( 'Log' ); $changeProtection = ' (' . $skin->linkKnown( $ltitle, wfMsgHtml( 'protectlogpage' ), array(), array( 'type' => 'protect', 'page' => $title->getPrefixedText() ) ) . ')'; } wfProfileOut( __METHOD__ ); return Html::rawElement( 'li', array(), wfSpecialList( $link . $stxt, $wgLang->commaList( $description_items ) ) . $changeProtection ) . "\n"; } /** * @param $namespace int * @param $type string * @param $level string * @param $minsize int * @param $indefOnly bool * @param $cascadeOnly bool * @return string Input form * @private */ protected function showOptions( $namespace, $type='edit', $level, $sizetype, $size, $indefOnly, $cascadeOnly ) { global $wgScript; $title = SpecialPage::getTitleFor( 'Protectedpages' ); return Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript ) ) . Xml::openElement( 'fieldset' ) . Xml::element( 'legend', array(), wfMsg( 'protectedpages' ) ) . Xml::hidden( 'title', $title->getPrefixedDBkey() ) . "\n" . $this->getNamespaceMenu( $namespace ) . "&nbsp;\n" . $this->getTypeMenu( $type ) . "&nbsp;\n" . $this->getLevelMenu( $level ) . "&nbsp;\n" . "<br /><span style='white-space: nowrap'>" . $this->getExpiryCheck( $indefOnly ) . "&nbsp;\n" . $this->getCascadeCheck( $cascadeOnly ) . "&nbsp;\n" . "</span><br /><span style='white-space: nowrap'>" . $this->getSizeLimit( $sizetype, $size ) . "&nbsp;\n" . "</span>" . "&nbsp;" . Xml::submitButton( wfMsg( 'allpagessubmit' ) ) . "\n" . Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' ); } /** * Prepare the namespace filter drop-down; standard namespace * selector, sans the MediaWiki namespace * * @param mixed $namespace Pre-select namespace * @return string */ protected function getNamespaceMenu( $namespace = null ) { return "<span style='white-space: nowrap'>" . Xml::label( wfMsg( 'namespace' ), 'namespace' ) . '&nbsp;' . Xml::namespaceSelector( $namespace, '' ) . "</span>"; } /** * @return string Formatted HTML */ protected function getExpiryCheck( $indefOnly ) { return Xml::checkLabel( wfMsg('protectedpages-indef'), 'indefonly', 'indefonly', $indefOnly ) . "\n"; } /** * @return string Formatted HTML */ protected function getCascadeCheck( $cascadeOnly ) { return Xml::checkLabel( wfMsg('protectedpages-cascade'), 'cascadeonly', 'cascadeonly', $cascadeOnly ) . "\n"; } /** * @return string Formatted HTML */ protected function getSizeLimit( $sizetype, $size ) { $max = $sizetype === 'max'; return Xml::radioLabel( wfMsg('minimum-size'), 'sizetype', 'min', 'wpmin', !$max ) . '&nbsp;' . Xml::radioLabel( wfMsg('maximum-size'), 'sizetype', 'max', 'wpmax', $max ) . '&nbsp;' . Xml::input( 'size', 9, $size, array( 'id' => 'wpsize' ) ) . '&nbsp;' . Xml::label( wfMsg('pagesize'), 'wpsize' ); } /** * Creates the input label of the restriction type * @param $pr_type string Protection type * @return string Formatted HTML */ protected function getTypeMenu( $pr_type ) { global $wgRestrictionTypes; $m = array(); // Temporary array $options = array(); // First pass to load the log names foreach( $wgRestrictionTypes as $type ) { $text = wfMsg("restriction-$type"); $m[$text] = $type; } // Third pass generates sorted XHTML content foreach( $m as $text => $type ) { $selected = ($type == $pr_type ); $options[] = Xml::option( $text, $type, $selected ) . "\n"; } return "<span style='white-space: nowrap'>" . Xml::label( wfMsg('restriction-type') , $this->IdType ) . '&nbsp;' . Xml::tags( 'select', array( 'id' => $this->IdType, 'name' => $this->IdType ), implode( "\n", $options ) ) . "</span>"; } /** * Creates the input label of the restriction level * @param $pr_level string Protection level * @return string Formatted HTML */ protected function getLevelMenu( $pr_level ) { global $wgRestrictionLevels; $m = array( wfMsg('restriction-level-all') => 0 ); // Temporary array $options = array(); // First pass to load the log names foreach( $wgRestrictionLevels as $type ) { // Messages used can be 'restriction-level-sysop' and 'restriction-level-autoconfirmed' if( $type !='' && $type !='*') { $text = wfMsg("restriction-level-$type"); $m[$text] = $type; } } // Third pass generates sorted XHTML content foreach( $m as $text => $type ) { $selected = ($type == $pr_level ); $options[] = Xml::option( $text, $type, $selected ); } return "<span style='white-space: nowrap'>" . Xml::label( wfMsg( 'restriction-level' ) , $this->IdLevel ) . ' ' . Xml::tags( 'select', array( 'id' => $this->IdLevel, 'name' => $this->IdLevel ), implode( "\n", $options ) ) . "</span>"; } } /** * @todo document * @ingroup Pager */ class ProtectedPagesPager extends AlphabeticPager { public $mForm, $mConds; private $type, $level, $namespace, $sizetype, $size, $indefonly; function __construct( $form, $conds = array(), $type, $level, $namespace, $sizetype='', $size=0, $indefonly = false, $cascadeonly = false ) { $this->mForm = $form; $this->mConds = $conds; $this->type = ( $type ) ? $type : 'edit'; $this->level = $level; $this->namespace = $namespace; $this->sizetype = $sizetype; $this->size = intval($size); $this->indefonly = (bool)$indefonly; $this->cascadeonly = (bool)$cascadeonly; parent::__construct(); } function getStartBody() { # Do a link batch query $lb = new LinkBatch; while( $row = $this->mResult->fetchObject() ) { $lb->add( $row->page_namespace, $row->page_title ); } $lb->execute(); return ''; } function formatRow( $row ) { return $this->mForm->formatRow( $row ); } function getQueryInfo() { $conds = $this->mConds; $conds[] = '(pr_expiry>' . $this->mDb->addQuotes( $this->mDb->timestamp() ) . 'OR pr_expiry IS NULL)'; $conds[] = 'page_id=pr_page'; $conds[] = 'pr_type=' . $this->mDb->addQuotes( $this->type ); if( $this->sizetype=='min' ) { $conds[] = 'page_len>=' . $this->size; } else if( $this->sizetype=='max' ) { $conds[] = 'page_len<=' . $this->size; } if( $this->indefonly ) { $conds[] = "pr_expiry = 'infinity' OR pr_expiry IS NULL"; } if( $this->cascadeonly ) { $conds[] = "pr_cascade = '1'"; } if( $this->level ) $conds[] = 'pr_level=' . $this->mDb->addQuotes( $this->level ); if( !is_null($this->namespace) ) $conds[] = 'page_namespace=' . $this->mDb->addQuotes( $this->namespace ); return array( 'tables' => array( 'page_restrictions', 'page' ), 'fields' => 'pr_id,page_namespace,page_title,page_len,pr_type,pr_level,pr_expiry,pr_cascade', 'conds' => $conds ); } function getIndexField() { return 'pr_id'; } } /** * Constructor */ function wfSpecialProtectedpages() { $ppForm = new ProtectedPagesForm(); $ppForm->showList(); }
hendrysuwanda/101dev
tools/mediawiki/includes/specials/SpecialProtectedpages.php
PHP
gpl-3.0
9,777
// Copyright 2012 Mark Cavage, Inc. All rights reserved. 'use strict'; ///--- Exports /** * JSONP formatter. like JSON, but with a callback invocation. * * Unicode escapes line and paragraph separators. * * @public * @function formatJSONP * @param {Object} req the request object * @param {Object} res the response object * @param {Object} body response body * @returns {String} */ function formatJSONP(req, res, body) { if (!body) { res.setHeader('Content-Length', 0); return (null); } if (Buffer.isBuffer(body)) { body = body.toString('base64'); } var _cb = req.query.callback || req.query.jsonp; var data; if (_cb) { data = 'typeof ' + _cb + ' === \'function\' && ' + _cb + '(' + JSON.stringify(body) + ');'; } else { data = JSON.stringify(body); } data = data.replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029'); res.setHeader('Content-Length', Buffer.byteLength(data)); return data; } module.exports = formatJSONP;
eduardomrodrigues/atabey
ws-api/node_modules/restify/lib/formatters/jsonp.js
JavaScript
gpl-3.0
1,081
declare module Virtex { interface IOptions { ambientLightColor: number; cameraZ: number; directionalLight1Color: number; directionalLight1Intensity: number; directionalLight2Color: number; directionalLight2Intensity: number; doubleSided: boolean; element: string; fadeSpeed: number; far: number; fov: number; maxZoom: number; minZoom: number; near: number; object: string; shading: THREE.Shading; shininess: number; showStats: boolean; zoomSpeed: number; } } interface IVirtex { create: (options: Virtex.IOptions) => Virtex.Viewport; } declare var Detector: any; declare var Stats: any; declare var requestAnimFrame: any; declare module Virtex { class Viewport { options: IOptions; private _$element; private _$viewport; private _$loading; private _$loadingBar; private _$oldie; private _camera; private _lightGroup; private _modelGroup; private _renderer; private _scene; private _stats; private _viewportHalfX; private _viewportHalfY; private _isMouseDown; private _mouseX; private _mouseXOnMouseDown; private _mouseY; private _mouseYOnMouseDown; private _pinchStart; private _targetRotationOnMouseDownX; private _targetRotationOnMouseDownY; private _targetRotationX; private _targetRotationY; private _targetZoom; constructor(options: IOptions); private _init(); private _loadProgress(progress); private _onMouseDown(event); private _onMouseMove(event); private _onMouseUp(event); private _onMouseOut(event); private _onMouseWheel(event); private _onTouchStart(event); private _onTouchMove(event); private _onTouchEnd(event); private _draw(); private _render(); private _getWidth(); private _getHeight(); zoomIn(): void; zoomOut(): void; private _resize(); } }
perryrothjohnson/artifact-database
pawtucket/assets/universalviewer/src/typings/virtex.d.ts
TypeScript
gpl-3.0
2,184
using System.Windows.Forms; using GitUIPluginInterfaces; using ResourceManager; namespace ReleaseNotesGenerator { public class ReleaseNotesGeneratorPlugin : GitPluginBase { public ReleaseNotesGeneratorPlugin() { SetNameAndDescription("Release Notes Generator"); Translate(); } public override bool Execute(GitUIBaseEventArgs gitUiCommands) { using (var form = new ReleaseNotesGeneratorForm(gitUiCommands)) { if (form.ShowDialog(gitUiCommands.OwnerForm) == DialogResult.OK) { return true; } } return false; } } }
ArsenShnurkov/gitextensions
Plugins/ReleaseNotesGenerator/ReleaseNotesGeneratorPlugin.cs
C#
gpl-3.0
718
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__
Architektor/PySnip
venv/lib/python2.7/site-packages/twisted/protocols/wire.py
Python
gpl-3.0
2,659
/** * @file * @copyright 2020 Aleksej Komarov * @license MIT */ // Themes import './styles/main.scss'; import './styles/themes/abductor.scss'; import './styles/themes/cardtable.scss'; import './styles/themes/hackerman.scss'; import './styles/themes/malfunction.scss'; import './styles/themes/neutral.scss'; import './styles/themes/ntos.scss'; import './styles/themes/paper.scss'; import './styles/themes/retro.scss'; import './styles/themes/syndicate.scss'; import './styles/themes/wizard.scss'; import { perf } from 'common/perf'; import { setupHotReloading } from 'tgui-dev-server/link/client'; import { setupHotKeys } from './hotkeys'; import { captureExternalLinks } from './links'; import { createRenderer } from './renderer'; import { configureStore, StoreProvider } from './store'; import { setupGlobalEvents } from './events'; perf.mark('inception', window.performance?.timing?.navigationStart); perf.mark('init'); const store = configureStore(); const renderApp = createRenderer(() => { const { getRoutedComponent } = require('./routes'); const Component = getRoutedComponent(store); return ( <StoreProvider store={store}> <Component /> </StoreProvider> ); }); const setupApp = () => { // Delay setup if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', setupApp); return; } setupGlobalEvents(); setupHotKeys(); captureExternalLinks(); // Subscribe for state updates store.subscribe(renderApp); // Dispatch incoming messages window.update = msg => store.dispatch(Byond.parseJson(msg)); // Process the early update queue while (true) { const msg = window.__updateQueue__.shift(); if (!msg) { break; } window.update(msg); } // Enable hot module reloading if (module.hot) { setupHotReloading(); module.hot.accept([ './components', './debug', './layouts', './routes', ], () => { renderApp(); }); } }; setupApp();
optimumtact/-tg-station
tgui/packages/tgui/index.js
JavaScript
agpl-3.0
1,998
(function() { 'use strict'; Features.$inject = ['urls']; function Features(urls) { var self = this; urls.links().then(function(links) { angular.extend(self, links); }); } /** * Provides info what features are available on server */ angular.module('superdesk.features', ['superdesk.api']) .service('features', Features); })();
vladnicoara/superdesk-client-core
scripts/superdesk/features/features.js
JavaScript
agpl-3.0
355
require File.dirname(__FILE__)+"/env" module Actors # /actors/worker class Worker include Magent::Actor expose :echo def echo(payload) puts payload.inspect end end Magent.register(Worker.new) end if $0 == __FILE__ Magent::Processor.new(Magent.current_actor).run! end
binarycode/shapado
app/actors/worker.rb
Ruby
agpl-3.0
303
# -*- coding: utf-8 -*- # Copyright(C) 2014 Laurent Bachelier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # weboob is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with weboob. If not, see <http://www.gnu.org/licenses/>. import requests.cookies try: import cookielib except ImportError: import http.cookiejar as cookielib __all__ = ['WeboobCookieJar'] class WeboobCookieJar(requests.cookies.RequestsCookieJar): @classmethod def from_cookiejar(klass, cj): """ Create a WeboobCookieJar from another CookieJar instance. """ return requests.cookies.merge_cookies(klass(), cj) def export(self, filename): """ Export all cookies to a file, regardless of expiration, etc. """ cj = requests.cookies.merge_cookies(cookielib.LWPCookieJar(), self) cj.save(filename, ignore_discard=True, ignore_expires=True) def _cookies_from_attrs_set(self, attrs_set, request): for tup in self._normalized_cookie_tuples(attrs_set): cookie = self._cookie_from_cookie_tuple(tup, request) if cookie: yield cookie def make_cookies(self, response, request): """Return sequence of Cookie objects extracted from response object.""" # get cookie-attributes for RFC 2965 and Netscape protocols headers = response.info() rfc2965_hdrs = headers.getheaders("Set-Cookie2") ns_hdrs = headers.getheaders("Set-Cookie") rfc2965 = self._policy.rfc2965 netscape = self._policy.netscape if netscape: for cookie in self._cookies_from_attrs_set(cookielib.parse_ns_headers(ns_hdrs), request): self._process_rfc2109_cookies([cookie]) yield cookie if rfc2965: for cookie in self._cookies_from_attrs_set(cookielib.split_header_words(rfc2965_hdrs), request): yield cookie def copy(self): new_cj = type(self)() new_cj.update(self) return new_cj
Boussadia/weboob
weboob/tools/browser2/cookies.py
Python
agpl-3.0
2,534
<?php /** * @package Core * @subpackage system * @deprecated */ require_once ( __DIR__ . "/kalturaSystemAction.class.php" ); /** * @package Core * @subpackage system * @deprecated */ class executeCommandAction extends kalturaSystemAction { // TODO - read from the entryWrapper private static $allowed_names = array ( "conversionQuality" ); /** * Will anipulate a single entry */ public function execute() { $this->forceSystemAuthentication(); myDbHelper::$use_alternative_con = null; $command = $this->getP ( "command" ); if ( $command == "updateEntry" ) { $id = $this->getP ( "id" ); $entry = entryPeer::retrieveByPK( $id ); if ( $entry ) { $name = $this->getP ( "name" ); $value = $this->getP ( "value" ); $obj_wrapper = objectWrapperBase::getWrapperClass( $entry , 0 ); $updateable_fields = $obj_wrapper->getUpdateableFields( "2" ); if ( ! in_array ( $name , $updateable_fields ) ) die(); if ( $name ) { $setter = "set" . $name; call_user_func( array ( $entry , $setter ) , $value ); $entry->save(); } } } die(); } } ?>
ratliff/server
alpha/apps/kaltura/modules/system/actions/executeCommandAction.class.php
PHP
agpl-3.0
1,152
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.type.comparator; import java.util.Comparator; import lucee.commons.lang.ComparatorUtil; import lucee.runtime.PageContext; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.PageException; import lucee.runtime.op.Caster; /** * Implementation of a Comparator, compares to Softregister Objects */ public final class SortRegisterComparator implements ExceptionComparator { private boolean isAsc; private PageException pageException=null; private boolean ignoreCase; private final Comparator comparator; /** * constructor of the class * @param isAsc is ascending or descending * @param ignoreCase do ignore case */ public SortRegisterComparator(PageContext pc,boolean isAsc, boolean ignoreCase, boolean localeSensitive) { this.isAsc=isAsc; this.ignoreCase=ignoreCase; comparator = ComparatorUtil.toComparator( ignoreCase?ComparatorUtil.SORT_TYPE_TEXT_NO_CASE:ComparatorUtil.SORT_TYPE_TEXT , isAsc, localeSensitive?ThreadLocalPageContext.getLocale(pc):null, null); } /** * @return Returns the expressionException. */ public PageException getPageException() { return pageException; } @Override public int compare(Object oLeft, Object oRight) { try { if(pageException!=null) return 0; else if(isAsc) return compareObjects(oLeft, oRight); else return compareObjects(oRight, oLeft); } catch (PageException e) { pageException=e; return 0; } } private int compareObjects(Object oLeft, Object oRight) throws PageException { String strLeft=Caster.toString(((SortRegister)oLeft).getValue()); String strRight=Caster.toString(((SortRegister)oRight).getValue()); return comparator.compare(strLeft, strRight); } }
lucee/unoffical-Lucee-no-jre
source/java/core/src/lucee/runtime/type/comparator/SortRegisterComparator.java
Java
lgpl-2.1
2,517
/* * Copyright (C) 2008-2014 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * https://github.com/qxmpp-project/qxmpp * * This file is a part of QXmpp library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "QXmppClient.h" #include "QXmppConstants.h" #include "QXmppUtils.h" #include "QXmppVCardIq.h" #include "QXmppVCardManager.h" class QXmppVCardManagerPrivate { public: QXmppVCardIq clientVCard; bool isClientVCardReceived; }; QXmppVCardManager::QXmppVCardManager() : d(new QXmppVCardManagerPrivate) { d->isClientVCardReceived = false; } QXmppVCardManager::~QXmppVCardManager() { delete d; } /// This function requests the server for vCard of the specified jid. /// Once received the signal vCardReceived() is emitted. /// /// \param jid Jid of the specific entry in the roster /// QString QXmppVCardManager::requestVCard(const QString& jid) { QXmppVCardIq request(jid); if(client()->sendPacket(request)) return request.id(); else return QString(); } /// Returns the vCard of the connected client. /// /// \return QXmppVCard /// const QXmppVCardIq& QXmppVCardManager::clientVCard() const { return d->clientVCard; } /// Sets the vCard of the connected client. /// /// \param clientVCard QXmppVCard /// void QXmppVCardManager::setClientVCard(const QXmppVCardIq& clientVCard) { d->clientVCard = clientVCard; d->clientVCard.setTo(""); d->clientVCard.setFrom(""); d->clientVCard.setType(QXmppIq::Set); client()->sendPacket(d->clientVCard); } /// This function requests the server for vCard of the connected user itself. /// Once received the signal clientVCardReceived() is emitted. Received vCard /// can be get using clientVCard(). QString QXmppVCardManager::requestClientVCard() { return requestVCard(); } /// Returns true if vCard of the connected client has been /// received else false. /// /// \return bool /// bool QXmppVCardManager::isClientVCardReceived() const { return d->isClientVCardReceived; } /// \cond QStringList QXmppVCardManager::discoveryFeatures() const { // XEP-0054: vcard-temp return QStringList() << ns_vcard; } bool QXmppVCardManager::handleStanza(const QDomElement &element) { if(element.tagName() == "iq" && QXmppVCardIq::isVCard(element)) { QXmppVCardIq vCardIq; vCardIq.parse(element); if (vCardIq.from().isEmpty()) { d->clientVCard = vCardIq; d->isClientVCardReceived = true; emit clientVCardReceived(); } emit vCardReceived(vCardIq); return true; } return false; } /// \endcond
gamenet/qxmpp
src/client/QXmppVCardManager.cpp
C++
lgpl-2.1
3,127
using Nop.Web.Framework.Mvc; namespace Nop.Admin.Models.Common { public partial class SystemWarningModel : BaseNopModel { public SystemWarningLevel Level { get; set; } public string Text { get; set; } } public enum SystemWarningLevel { Pass, Warning, Fail } }
jornfilho/nopCommerce
source/Presentation/Nop.Web/Administration/Models/Common/SystemWarningModel.cs
C#
apache-2.0
329
/* * 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. */ package org.apache.ode.ql.tree.nodes; public class Equality extends IdentifierToValueCMP { private static final long serialVersionUID = 8151616227509392901L; /** * @param identifier * @param value */ public Equality(Identifier identifier, Value value) { super(identifier, value); } }
Subasinghe/ode
bpel-ql/src/main/java/org/apache/ode/ql/tree/nodes/Equality.java
Java
apache-2.0
1,136
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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 com.intellij.packageDependencies; import com.intellij.analysis.AnalysisScope; import com.intellij.analysis.AnalysisScopeBundle; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class ForwardDependenciesBuilder extends DependenciesBuilder { private final Map<PsiFile, Set<PsiFile>> myDirectDependencies = new HashMap<PsiFile, Set<PsiFile>>(); public ForwardDependenciesBuilder(@NotNull Project project, @NotNull AnalysisScope scope) { super(project, scope); } public ForwardDependenciesBuilder(final Project project, final AnalysisScope scope, final AnalysisScope scopeOfInterest) { super(project, scope, scopeOfInterest); } public ForwardDependenciesBuilder(final Project project, final AnalysisScope scope, final int transitive) { super(project, scope); myTransitive = transitive; } @Override public String getRootNodeNameInUsageView(){ return AnalysisScopeBundle.message("forward.dependencies.usage.view.root.node.text"); } @Override public String getInitialUsagesPosition(){ return AnalysisScopeBundle.message("forward.dependencies.usage.view.initial.text"); } @Override public boolean isBackward(){ return false; } @Override public void analyze() { final PsiManager psiManager = PsiManager.getInstance(getProject()); psiManager.startBatchFilesProcessingMode(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(getProject()).getFileIndex(); try { getScope().accept(new PsiRecursiveElementVisitor() { @Override public void visitFile(final PsiFile file) { visit(file, fileIndex, psiManager, 0); } }); } finally { psiManager.finishBatchFilesProcessingMode(); } } private void visit(final PsiFile file, final ProjectFileIndex fileIndex, final PsiManager psiManager, int depth) { final FileViewProvider viewProvider = file.getViewProvider(); if (viewProvider.getBaseLanguage() != file.getLanguage()) return; if (getScopeOfInterest() != null && !getScopeOfInterest().contains(file)) return; ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); final VirtualFile virtualFile = file.getVirtualFile(); if (indicator != null) { if (indicator.isCanceled()) { throw new ProcessCanceledException(); } indicator.setText(AnalysisScopeBundle.message("package.dependencies.progress.text")); if (virtualFile != null) { indicator.setText2(getRelativeToProjectPath(virtualFile)); } if ( myTotalFileCount > 0) { indicator.setFraction(((double)++ myFileCount) / myTotalFileCount); } } final boolean isInLibrary = virtualFile == null || fileIndex.isInLibrarySource(virtualFile) || fileIndex.isInLibraryClasses(virtualFile); final Set<PsiFile> collectedDeps = new HashSet<PsiFile>(); final HashSet<PsiFile> processed = new HashSet<PsiFile>(); collectedDeps.add(file); do { if (depth++ > getTransitiveBorder()) return; for (PsiFile psiFile : new HashSet<PsiFile>(collectedDeps)) { final VirtualFile vFile = psiFile.getVirtualFile(); if (vFile != null) { if (indicator != null) { indicator.setText2(getRelativeToProjectPath(vFile)); } if (!isInLibrary && (fileIndex.isInLibraryClasses(vFile) || fileIndex.isInLibrarySource(vFile))) { processed.add(psiFile); } } final Set<PsiFile> found = new HashSet<PsiFile>(); if (!processed.contains(psiFile)) { processed.add(psiFile); analyzeFileDependencies(psiFile, new DependencyProcessor() { @Override public void process(PsiElement place, PsiElement dependency) { PsiFile dependencyFile = dependency.getContainingFile(); if (dependencyFile != null) { if (viewProvider == dependencyFile.getViewProvider()) return; if (dependencyFile.isPhysical()) { final VirtualFile virtualFile = dependencyFile.getVirtualFile(); if (virtualFile != null && (fileIndex.isInContent(virtualFile) || fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile))) { found.add(dependencyFile); } } } } }); Set<PsiFile> deps = getDependencies().get(file); if (deps == null) { deps = new HashSet<PsiFile>(); getDependencies().put(file, deps); } deps.addAll(found); getDirectDependencies().put(psiFile, new HashSet<PsiFile>(found)); collectedDeps.addAll(found); psiManager.dropResolveCaches(); InjectedLanguageManager.getInstance(file.getProject()).dropFileCaches(file); } } collectedDeps.removeAll(processed); } while (isTransitive() && !collectedDeps.isEmpty()); } @Override public Map<PsiFile, Set<PsiFile>> getDirectDependencies() { return myDirectDependencies; } }
romankagan/DDBWorkbench
platform/analysis-impl/src/com/intellij/packageDependencies/ForwardDependenciesBuilder.java
Java
apache-2.0
6,335
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.common.util; /** * Simple wrapper class which contains a result and an exception. * This can be useful for example when performing asynchronous operations * which do not immediately return, but could throw an exception. * * @param <R> The result of the operation * @param <E> The exception (if any) thrown during the operation. */ public class ResultWrapper<R, E extends Exception> { private E exception; private R result; public ResultWrapper(R result) { this.result = result; } public ResultWrapper(R result, E exception) { this.result = result; this.exception = exception; } /** Returns null if no exception was thrown */ /** * @return */ public E getException() { return exception; } public R getResult() { return result; } }
ruhan1/pnc
common/src/main/java/org/jboss/pnc/common/util/ResultWrapper.java
Java
apache-2.0
1,569
/* * Copyright 2015 JBoss by Red Hat. * * 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.uberfire.ext.widgets.common.client.colorpicker.dialog; import com.google.gwt.event.shared.EventHandler; public interface DialogClosedHandler extends EventHandler { void dialogClosed(DialogClosedEvent event); }
wmedvede/uberfire-extensions
uberfire-widgets/uberfire-widgets-commons/src/main/java/org/uberfire/ext/widgets/common/client/colorpicker/dialog/DialogClosedHandler.java
Java
apache-2.0
849
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.gmf.esb.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.LogMediatorInputConnector} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class LogMediatorInputConnectorItemProvider extends InputConnectorItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LogMediatorInputConnectorItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This returns LogMediatorInputConnector.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/LogMediatorInputConnector")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { return getString("_UI_LogMediatorInputConnector_type"); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
nwnpallewela/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/LogMediatorInputConnectorItemProvider.java
Java
apache-2.0
2,890
/** * 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. */ package org.apache.hadoop.yarn.server.api.protocolrecords.impl.pb; import org.apache.hadoop.thirdparty.protobuf.TextFormat; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationIdPBImpl; import org.apache.hadoop.yarn.proto.YarnProtos; import org.apache.hadoop.yarn.proto.YarnServerCommonServiceProtos.GetTimelineCollectorContextRequestProtoOrBuilder; import org.apache.hadoop.yarn.proto.YarnServerCommonServiceProtos.GetTimelineCollectorContextRequestProto; import org.apache.hadoop.yarn.server.api.protocolrecords.GetTimelineCollectorContextRequest; public class GetTimelineCollectorContextRequestPBImpl extends GetTimelineCollectorContextRequest { private GetTimelineCollectorContextRequestProto proto = GetTimelineCollectorContextRequestProto.getDefaultInstance(); private GetTimelineCollectorContextRequestProto.Builder builder = null; private boolean viaProto = false; private ApplicationId appId = null; public GetTimelineCollectorContextRequestPBImpl() { builder = GetTimelineCollectorContextRequestProto.newBuilder(); } public GetTimelineCollectorContextRequestPBImpl( GetTimelineCollectorContextRequestProto proto) { this.proto = proto; viaProto = true; } public GetTimelineCollectorContextRequestProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } private void mergeLocalToBuilder() { if (appId != null) { builder.setAppId(convertToProtoFormat(this.appId)); } } private void mergeLocalToProto() { if (viaProto) { maybeInitBuilder(); } mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = GetTimelineCollectorContextRequestProto.newBuilder(proto); } viaProto = false; } @Override public ApplicationId getApplicationId() { if (this.appId != null) { return this.appId; } GetTimelineCollectorContextRequestProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasAppId()) { return null; } this.appId = convertFromProtoFormat(p.getAppId()); return this.appId; } @Override public void setApplicationId(ApplicationId id) { maybeInitBuilder(); if (id == null) { builder.clearAppId(); } this.appId = id; } private ApplicationIdPBImpl convertFromProtoFormat( YarnProtos.ApplicationIdProto p) { return new ApplicationIdPBImpl(p); } private YarnProtos.ApplicationIdProto convertToProtoFormat(ApplicationId t) { return ((ApplicationIdPBImpl)t).getProto(); } }
steveloughran/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/GetTimelineCollectorContextRequestPBImpl.java
Java
apache-2.0
3,988
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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 com.intellij.codeInsight.template.impl; import com.intellij.psi.tree.IElementType; import com.intellij.util.containers.hash.LinkedHashMap; /** * @author Maxim.Mossienko */ public class TemplateImplUtil { public static LinkedHashMap<String, Variable> parseVariables(CharSequence text) { LinkedHashMap<String, Variable> variables = new LinkedHashMap<String, Variable>(); TemplateTextLexer lexer = new TemplateTextLexer(); lexer.start(text); while (true) { IElementType tokenType = lexer.getTokenType(); if (tokenType == null) break; int start = lexer.getTokenStart(); int end = lexer.getTokenEnd(); String token = text.subSequence(start, end).toString(); if (tokenType == TemplateTokenType.VARIABLE) { String name = token.substring(1, token.length() - 1); if (!variables.containsKey(name)) { variables.put(name, new Variable(name, "", "", true)); } } lexer.advance(); } return variables; } public static boolean isValidVariableName(String varName) { return parseVariables("$" + varName + "$").containsKey(varName); } }
kdwink/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateImplUtil.java
Java
apache-2.0
1,752
/* * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. * */ /** * @fileOverview */ /** * Constains the dictionary of language entries. * @namespace */ CKFinder.lang['el'] = { appTitle : 'CKFinder', // MISSING // Common messages and labels. common : { // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING ok : 'OK', // MISSING cancel : 'Cancel', // MISSING confirmationTitle : 'Confirmation', // MISSING messageTitle : 'Information', // MISSING inputTitle : 'Question', // MISSING undo : 'Undo', // MISSING redo : 'Redo', // MISSING skip : 'Skip', // MISSING skipAll : 'Skip all', // MISSING makeDecision : 'What action should be taken?', // MISSING rememberDecision: 'Remember my decision' // MISSING }, dir : 'ltr', // MISSING HelpLang : 'en', LangCode : 'el', // Date Format // d : Day // dd : Day (padding zero) // m : Month // mm : Month (padding zero) // yy : Year (two digits) // yyyy : Year (four digits) // h : Hour (12 hour clock) // hh : Hour (12 hour clock, padding zero) // H : Hour (24 hour clock) // HH : Hour (24 hour clock, padding zero) // M : Minute // MM : Minute (padding zero) // a : Firt char of AM/PM // aa : AM/PM DateTime : 'dd/mm/yyyy HH:MM', DateAmPm : ['ΜΜ', 'ΠΜ'], // Folders FoldersTitle : 'Φάκελοι', FolderLoading : 'Φόρτωση...', FolderNew : 'Παρακαλούμε πληκτρολογήστε την ονομασία του νέου φακέλου: ', FolderRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του φακέλου: ', FolderDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το φάκελο "%1";', FolderRenaming : ' (Μετονομασία...)', FolderDeleting : ' (Διαγραφή...)', // Files FileRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του αρχείου: ', FileRenameExt : 'Είστε σίγουροι ότι θέλετε να αλλάξετε την επέκταση του αρχείου; Μετά από αυτή την ενέργεια το αρχείο μπορεί να μην μπορεί να χρησιμοποιηθεί', FileRenaming : 'Μετονομασία...', FileDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το αρχείο "%1"?', FilesLoading : 'Loading...', // MISSING FilesEmpty : 'Empty folder', // MISSING FilesMoved : 'File %1 moved into %2:%3', // MISSING FilesCopied : 'File %1 copied into %2:%3', // MISSING // Basket BasketFolder : 'Basket', // MISSING BasketClear : 'Clear Basket', // MISSING BasketRemove : 'Remove from basket', // MISSING BasketOpenFolder : 'Open parent folder', // MISSING BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING BasketCopyFilesHere : 'Copy Files from Basket', // MISSING BasketMoveFilesHere : 'Move Files from Basket', // MISSING BasketPasteErrorOther : 'File %s error: %e', // MISSING BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING // Toolbar Buttons (some used elsewhere) Upload : 'Μεταφόρτωση', UploadTip : 'Μεταφόρτωση Νέου Αρχείου', Refresh : 'Ανανέωση', Settings : 'Ρυθμίσεις', Help : 'Βοήθεια', HelpTip : 'Βοήθεια', // Context Menus Select : 'Επιλογή', SelectThumbnail : 'Επιλογή Μικρογραφίας', View : 'Προβολή', Download : 'Λήψη Αρχείου', NewSubFolder : 'Νέος Υποφάκελος', Rename : 'Μετονομασία', Delete : 'Διαγραφή', CopyDragDrop : 'Copy file here', // MISSING MoveDragDrop : 'Move file here', // MISSING // Dialogs RenameDlgTitle : 'Rename', // MISSING NewNameDlgTitle : 'New name', // MISSING FileExistsDlgTitle : 'File already exists', // MISSING SysErrorDlgTitle : 'System error', // MISSING FileOverwrite : 'Overwrite', // MISSING FileAutorename : 'Auto-rename', // MISSING // Generic OkBtn : 'OK', CancelBtn : 'Ακύρωση', CloseBtn : 'Κλείσιμο', // Upload Panel UploadTitle : 'Μεταφόρτωση Νέου Αρχείου', UploadSelectLbl : 'επιλέξτε το αρχείο που θέλετε να μεταφερθεί κάνοντας κλίκ στο κουμπί', UploadProgressLbl : '(Η μεταφόρτωση εκτελείται, παρακαλούμε περιμένετε...)', UploadBtn : 'Μεταφόρτωση Επιλεγμένου Αρχείου', UploadBtnCancel : 'Cancel', // MISSING UploadNoFileMsg : 'Παρακαλούμε επιλέξτε ένα αρχείο από τον υπολογιστή σας', UploadNoFolder : 'Please select folder before uploading.', // MISSING UploadNoPerms : 'File upload not allowed.', // MISSING UploadUnknError : 'Error sending the file.', // MISSING UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING // Settings Panel SetTitle : 'Ρυθμίσεις', SetView : 'Προβολή:', SetViewThumb : 'Μικρογραφίες', SetViewList : 'Λίστα', SetDisplay : 'Εμφάνιση:', SetDisplayName : 'Όνομα Αρχείου', SetDisplayDate : 'Ημερομηνία', SetDisplaySize : 'Μέγεθος Αρχείου', SetSort : 'Ταξινόμηση:', SetSortName : 'βάσει Όνοματος Αρχείου', SetSortDate : 'βάσει Ημερομήνιας', SetSortSize : 'βάσει Μεγέθους', // Status Bar FilesCountEmpty : '<Κενός Φάκελος>', FilesCountOne : '1 αρχείο', FilesCountMany : '%1 αρχεία', // Size and Speed Kb : '%1 kB', KbPerSecond : '%1 kB/s', // Connector Error Messages. ErrorUnknown : 'Η ενέργεια δεν ήταν δυνατόν να εκτελεστεί. (Σφάλμα %1)', Errors : { 10 : 'Λανθασμένη Εντολή.', 11 : 'Το resource type δεν ήταν δυνατόν να προσδιορίστεί.', 12 : 'Το resource type δεν είναι έγκυρο.', 102 : 'Το όνομα αρχείου ή φακέλου δεν είναι έγκυρο.', 103 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω έλλειψης δικαιωμάτων ασφαλείας.', 104 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω περιορισμών του συστήματος αρχείων.', 105 : 'Λανθασμένη Επέκταση Αρχείου.', 109 : 'Λανθασμένη Ενέργεια.', 110 : 'Άγνωστο Λάθος.', 115 : 'Το αρχείο ή φάκελος υπάρχει ήδη.', 116 : 'Ο φάκελος δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.', 117 : 'Το αρχείο δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.', 118 : 'Source and target paths are equal.', // MISSING 201 : 'Ένα αρχείο με την ίδια ονομασία υπάρχει ήδη. Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"', 202 : 'Λανθασμένο Αρχείο', 203 : 'Λανθασμένο Αρχείο. Το μέγεθος του αρχείου είναι πολύ μεγάλο.', 204 : 'Το μεταφορτωμένο αρχείο είναι χαλασμένο.', 205 : 'Δεν υπάρχει προσωρινός φάκελος για να χρησιμοποιηθεί για τις μεταφορτώσεις των αρχείων.', 206 : 'Η μεταφόρτωση ακυρώθηκε για λόγους ασφαλείας. Το αρχείο περιέχει δεδομένα μορφής HTML.', 207 : 'Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"', 300 : 'Moving file(s) failed.', // MISSING 301 : 'Copying file(s) failed.', // MISSING 500 : 'Ο πλοηγός αρχείων έχει απενεργοποιηθεί για λόγους ασφαλείας. Παρακαλούμε επικοινωνήστε με τον διαχειριστή της ιστοσελίδας και ελέγξτε το αρχείο ρυθμίσεων του πλοηγού (CKFinder).', 501 : 'Η υποστήριξη των μικρογραφιών έχει απενεργοποιηθεί.' }, // Other Error Messages. ErrorMsg : { FileEmpty : 'Η ονομασία του αρχείου δεν μπορεί να είναι κενή', FileExists : 'File %s already exists', // MISSING FolderEmpty : 'Η ονομασία του φακέλου δεν μπορεί να είναι κενή', FileInvChar : 'Η ονομασία του αρχείου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |', FolderInvChar : 'Η ονομασία του φακέλου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |', PopupBlockView : 'Δεν ήταν εφικτό να ανοίξει το αρχείο σε νέο παράθυρο. Παρακαλώ, ελέγξτε τις ρυθμίσεις τους πλοηγού σας και απενεργοποιήστε όλους τους popup blockers για αυτή την ιστοσελίδα.' }, // Imageresize plugin Imageresize : { dialogTitle : 'Resize %s', // MISSING sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING resizeSuccess : 'Image resized successfully.', // MISSING thumbnailNew : 'Create new thumbnail', // MISSING thumbnailSmall : 'Small (%s)', // MISSING thumbnailMedium : 'Medium (%s)', // MISSING thumbnailLarge : 'Large (%s)', // MISSING newSize : 'Set new size', // MISSING width : 'Width', // MISSING height : 'Height', // MISSING invalidHeight : 'Invalid height.', // MISSING invalidWidth : 'Invalid width.', // MISSING invalidName : 'Invalid file name.', // MISSING newImage : 'Create new image', // MISSING noExtensionChange : 'The file extension cannot be changed.', // MISSING imageSmall : 'Source image is too small', // MISSING contextMenuName : 'Resize' // MISSING }, // Fileeditor plugin Fileeditor : { save : 'Save', // MISSING fileOpenError : 'Unable to open file.', // MISSING fileSaveSuccess : 'File saved successfully.', // MISSING contextMenuName : 'Edit', // MISSING loadingFile : 'Loading file, please wait...' // MISSING } };
vikigroup/cbuilk
web/skin/temp12/scripts/ckfinder/lang/el.js
JavaScript
apache-2.0
11,785
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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. */ /*! FixedHeader 2.1.2 * ©2010-2014 SpryMedia Ltd - datatables.net/license */ /** * @summary FixedHeader * @description Fix a table's header or footer, so it is always visible while * Scrolling * @version 2.1.2 * @file dataTables.fixedHeader.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2009-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * This source file 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 license files for details. * * For details please refer to: http://www.datatables.net */ /* Global scope for FixedColumns for backwards compatibility - will be removed * in future. Not documented in 1.1.x. */ /* Global scope for FixedColumns */ var FixedHeader; (function(window, document, undefined) { var factory = function( $, DataTable ) { "use strict"; /* * Function: FixedHeader * Purpose: Provide 'fixed' header, footer and columns for a DataTable * Returns: object:FixedHeader - must be called with 'new' * Inputs: mixed:mTable - target table * @param {object} dt DataTables instance or HTML table node. With DataTables * 1.10 this can also be a jQuery collection (with just a single table in its * result set), a jQuery selector, DataTables API instance or settings * object. * @param {object} [oInit] initialisation settings, with the following * properties (each optional) * * bool:top - fix the header (default true) * * bool:bottom - fix the footer (default false) * * int:left - fix the left column(s) (default 0) * * int:right - fix the right column(s) (default 0) * * int:zTop - fixed header zIndex * * int:zBottom - fixed footer zIndex * * int:zLeft - fixed left zIndex * * int:zRight - fixed right zIndex */ FixedHeader = function ( mTable, oInit ) { /* Sanity check - you just know it will happen */ if ( ! this instanceof FixedHeader ) { alert( "FixedHeader warning: FixedHeader must be initialised with the 'new' keyword." ); return; } var that = this; var oSettings = { "aoCache": [], "oSides": { "top": true, "bottom": false, "left": 0, "right": 0 }, "oZIndexes": { "top": 104, "bottom": 103, "left": 102, "right": 101 }, "oCloneOnDraw": { "top": false, "bottom": false, "left": true, "right": true }, "oMes": { "iTableWidth": 0, "iTableHeight": 0, "iTableLeft": 0, "iTableRight": 0, /* note this is left+width, not actually "right" */ "iTableTop": 0, "iTableBottom": 0 /* note this is top+height, not actually "bottom" */ }, "oOffset": { "top": 0 }, "nTable": null, "bFooter": false, "bInitComplete": false }; /* * Function: fnGetSettings * Purpose: Get the settings for this object * Returns: object: - settings object * Inputs: - */ this.fnGetSettings = function () { return oSettings; }; /* * Function: fnUpdate * Purpose: Update the positioning and copies of the fixed elements * Returns: - * Inputs: - */ this.fnUpdate = function () { this._fnUpdateClones(); this._fnUpdatePositions(); }; /* * Function: fnPosition * Purpose: Update the positioning of the fixed elements * Returns: - * Inputs: - */ this.fnPosition = function () { this._fnUpdatePositions(); }; var dt = $.fn.dataTable.Api ? new $.fn.dataTable.Api( mTable ).settings()[0] : mTable.fnSettings(); dt._oPluginFixedHeader = this; /* Let's do it */ this.fnInit( dt, oInit ); }; /* * Variable: FixedHeader * Purpose: Prototype for FixedHeader * Scope: global */ FixedHeader.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation */ /* * Function: fnInit * Purpose: The "constructor" * Returns: - * Inputs: {as FixedHeader function} */ fnInit: function ( oDtSettings, oInit ) { var s = this.fnGetSettings(); var that = this; /* Record the user definable settings */ this.fnInitSettings( s, oInit ); if ( oDtSettings.oScroll.sX !== "" || oDtSettings.oScroll.sY !== "" ) { alert( "FixedHeader 2 is not supported with DataTables' scrolling mode at this time" ); return; } s.nTable = oDtSettings.nTable; oDtSettings.aoDrawCallback.unshift( { "fn": function () { FixedHeader.fnMeasure(); that._fnUpdateClones.call(that); that._fnUpdatePositions.call(that); }, "sName": "FixedHeader" } ); s.bFooter = ($('>tfoot', s.nTable).length > 0) ? true : false; /* Add the 'sides' that are fixed */ if ( s.oSides.top ) { s.aoCache.push( that._fnCloneTable( "fixedHeader", "FixedHeader_Header", that._fnCloneThead ) ); } if ( s.oSides.bottom ) { s.aoCache.push( that._fnCloneTable( "fixedFooter", "FixedHeader_Footer", that._fnCloneTfoot ) ); } if ( s.oSides.left ) { s.aoCache.push( that._fnCloneTable( "fixedLeft", "FixedHeader_Left", that._fnCloneTLeft, s.oSides.left ) ); } if ( s.oSides.right ) { s.aoCache.push( that._fnCloneTable( "fixedRight", "FixedHeader_Right", that._fnCloneTRight, s.oSides.right ) ); } /* Event listeners for window movement */ FixedHeader.afnScroll.push( function () { that._fnUpdatePositions.call(that); } ); $(window).resize( function () { FixedHeader.fnMeasure(); that._fnUpdateClones.call(that); that._fnUpdatePositions.call(that); } ); $(s.nTable) .on('column-reorder.dt', function () { FixedHeader.fnMeasure(); that._fnUpdateClones( true ); that._fnUpdatePositions(); } ) .on('column-visibility.dt', function () { FixedHeader.fnMeasure(); that._fnUpdateClones( true ); that._fnUpdatePositions(); } ); /* Get things right to start with */ FixedHeader.fnMeasure(); that._fnUpdateClones(); that._fnUpdatePositions(); s.bInitComplete = true; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Support functions */ /* * Function: fnInitSettings * Purpose: Take the user's settings and copy them to our local store * Returns: - * Inputs: object:s - the local settings object * object:oInit - the user's settings object */ fnInitSettings: function ( s, oInit ) { if ( oInit !== undefined ) { if ( oInit.top !== undefined ) { s.oSides.top = oInit.top; } if ( oInit.bottom !== undefined ) { s.oSides.bottom = oInit.bottom; } if ( typeof oInit.left == 'boolean' ) { s.oSides.left = oInit.left ? 1 : 0; } else if ( oInit.left !== undefined ) { s.oSides.left = oInit.left; } if ( typeof oInit.right == 'boolean' ) { s.oSides.right = oInit.right ? 1 : 0; } else if ( oInit.right !== undefined ) { s.oSides.right = oInit.right; } if ( oInit.zTop !== undefined ) { s.oZIndexes.top = oInit.zTop; } if ( oInit.zBottom !== undefined ) { s.oZIndexes.bottom = oInit.zBottom; } if ( oInit.zLeft !== undefined ) { s.oZIndexes.left = oInit.zLeft; } if ( oInit.zRight !== undefined ) { s.oZIndexes.right = oInit.zRight; } if ( oInit.offsetTop !== undefined ) { s.oOffset.top = oInit.offsetTop; } if ( oInit.alwaysCloneTop !== undefined ) { s.oCloneOnDraw.top = oInit.alwaysCloneTop; } if ( oInit.alwaysCloneBottom !== undefined ) { s.oCloneOnDraw.bottom = oInit.alwaysCloneBottom; } if ( oInit.alwaysCloneLeft !== undefined ) { s.oCloneOnDraw.left = oInit.alwaysCloneLeft; } if ( oInit.alwaysCloneRight !== undefined ) { s.oCloneOnDraw.right = oInit.alwaysCloneRight; } } }, /* * Function: _fnCloneTable * Purpose: Clone the table node and do basic initialisation * Returns: - * Inputs: - */ _fnCloneTable: function ( sType, sClass, fnClone, iCells ) { var s = this.fnGetSettings(); var nCTable; /* We know that the table _MUST_ has a DIV wrapped around it, because this is simply how * DataTables works. Therefore, we can set this to be relatively position (if it is not * alreadu absolute, and use this as the base point for the cloned header */ if ( $(s.nTable.parentNode).css('position') != "absolute" ) { s.nTable.parentNode.style.position = "relative"; } /* Just a shallow clone will do - we only want the table node */ nCTable = s.nTable.cloneNode( false ); nCTable.removeAttribute( 'id' ); var nDiv = document.createElement( 'div' ); nDiv.style.position = "absolute"; nDiv.style.top = "0px"; nDiv.style.left = "0px"; nDiv.className += " FixedHeader_Cloned "+sType+" "+sClass; /* Set the zIndexes */ if ( sType == "fixedHeader" ) { nDiv.style.zIndex = s.oZIndexes.top; } if ( sType == "fixedFooter" ) { nDiv.style.zIndex = s.oZIndexes.bottom; } if ( sType == "fixedLeft" ) { nDiv.style.zIndex = s.oZIndexes.left; } else if ( sType == "fixedRight" ) { nDiv.style.zIndex = s.oZIndexes.right; } /* remove margins since we are going to position it absolutely */ nCTable.style.margin = "0"; /* Insert the newly cloned table into the DOM, on top of the "real" header */ nDiv.appendChild( nCTable ); document.body.appendChild( nDiv ); return { "nNode": nCTable, "nWrapper": nDiv, "sType": sType, "sPosition": "", "sTop": "", "sLeft": "", "fnClone": fnClone, "iCells": iCells }; }, /* * Function: _fnMeasure * Purpose: Get the current positioning of the table in the DOM * Returns: - * Inputs: - */ _fnMeasure: function () { var s = this.fnGetSettings(), m = s.oMes, jqTable = $(s.nTable), oOffset = jqTable.offset(), iParentScrollTop = this._fnSumScroll( s.nTable.parentNode, 'scrollTop' ), iParentScrollLeft = this._fnSumScroll( s.nTable.parentNode, 'scrollLeft' ); m.iTableWidth = jqTable.outerWidth(); m.iTableHeight = jqTable.outerHeight(); m.iTableLeft = oOffset.left + s.nTable.parentNode.scrollLeft; m.iTableTop = oOffset.top + iParentScrollTop; m.iTableRight = m.iTableLeft + m.iTableWidth; m.iTableRight = FixedHeader.oDoc.iWidth - m.iTableLeft - m.iTableWidth; m.iTableBottom = FixedHeader.oDoc.iHeight - m.iTableTop - m.iTableHeight; }, /* * Function: _fnSumScroll * Purpose: Sum node parameters all the way to the top * Returns: int: sum * Inputs: node:n - node to consider * string:side - scrollTop or scrollLeft */ _fnSumScroll: function ( n, side ) { var i = n[side]; while ( n = n.parentNode ) { if ( n.nodeName == 'HTML' || n.nodeName == 'BODY' ) { break; } i = n[side]; } return i; }, /* * Function: _fnUpdatePositions * Purpose: Loop over the fixed elements for this table and update their positions * Returns: - * Inputs: - */ _fnUpdatePositions: function () { var s = this.fnGetSettings(); this._fnMeasure(); for ( var i=0, iLen=s.aoCache.length ; i<iLen ; i++ ) { if ( s.aoCache[i].sType == "fixedHeader" ) { this._fnScrollFixedHeader( s.aoCache[i] ); } else if ( s.aoCache[i].sType == "fixedFooter" ) { this._fnScrollFixedFooter( s.aoCache[i] ); } else if ( s.aoCache[i].sType == "fixedLeft" ) { this._fnScrollHorizontalLeft( s.aoCache[i] ); } else { this._fnScrollHorizontalRight( s.aoCache[i] ); } } }, /* * Function: _fnUpdateClones * Purpose: Loop over the fixed elements for this table and call their cloning functions * Returns: - * Inputs: - */ _fnUpdateClones: function ( full ) { var s = this.fnGetSettings(); if ( full ) { // This is a little bit of a hack to force a full clone draw. When // `full` is set to true, we want to reclone the source elements, // regardless of the clone-on-draw settings s.bInitComplete = false; } for ( var i=0, iLen=s.aoCache.length ; i<iLen ; i++ ) { s.aoCache[i].fnClone.call( this, s.aoCache[i] ); } if ( full ) { s.bInitComplete = true; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Scrolling functions */ /* * Function: _fnScrollHorizontalLeft * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollHorizontalRight: function ( oCache ) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iFixedWidth = $(nTable).outerWidth(); if ( oWin.iScrollRight < oMes.iTableRight ) { /* Fully right aligned */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft+oMes.iTableWidth-iFixedWidth)+"px", 'left', nTable.style ); } else if ( oMes.iTableLeft < oDoc.iWidth-oWin.iScrollRight-iFixedWidth ) { /* Middle */ this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop-oWin.iScrollTop)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oWin.iWidth-iFixedWidth)+"px", 'left', nTable.style ); } else { /* Fully left aligned */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } }, /* * Function: _fnScrollHorizontalLeft * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollHorizontalLeft: function ( oCache ) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iCellWidth = $(nTable).outerWidth(); if ( oWin.iScrollLeft < oMes.iTableLeft ) { /* Fully left align */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } else if ( oWin.iScrollLeft < oMes.iTableLeft+oMes.iTableWidth-iCellWidth ) { this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop-oWin.iScrollTop)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', "0px", 'left', nTable.style ); } else { /* Fully right align */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft+oMes.iTableWidth-iCellWidth)+"px", 'left', nTable.style ); } }, /* * Function: _fnScrollFixedFooter * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollFixedFooter: function ( oCache ) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iTheadHeight = $("thead", s.nTable).outerHeight(), iCellHeight = $(nTable).outerHeight(); if ( oWin.iScrollBottom < oMes.iTableBottom ) { /* Below */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+oMes.iTableHeight-iCellHeight)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } else if ( oWin.iScrollBottom < oMes.iTableBottom+oMes.iTableHeight-iCellHeight-iTheadHeight ) { this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oWin.iHeight-iCellHeight)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft-oWin.iScrollLeft)+"px", 'left', nTable.style ); } else { /* Above */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+iCellHeight)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } }, /* * Function: _fnScrollFixedHeader * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollFixedHeader: function ( oCache ) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iTbodyHeight = 0, anTbodies = s.nTable.getElementsByTagName('tbody'); for (var i = 0; i < anTbodies.length; ++i) { iTbodyHeight += anTbodies[i].offsetHeight; } if ( oMes.iTableTop > oWin.iScrollTop + s.oOffset.top ) { /* Above the table */ this._fnUpdateCache( oCache, 'sPosition', "absolute", 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } else if ( oWin.iScrollTop + s.oOffset.top > oMes.iTableTop+iTbodyHeight ) { /* At the bottom of the table */ this._fnUpdateCache( oCache, 'sPosition', "absolute", 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+iTbodyHeight)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } else { /* In the middle of the table */ this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', s.oOffset.top+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft-oWin.iScrollLeft)+"px", 'left', nTable.style ); } }, /* * Function: _fnUpdateCache * Purpose: Check the cache and update cache and value if needed * Returns: - * Inputs: object:oCache - local cache object * string:sCache - cache property * string:sSet - value to set * string:sProperty - object property to set * object:oObj - object to update */ _fnUpdateCache: function ( oCache, sCache, sSet, sProperty, oObj ) { if ( oCache[sCache] != sSet ) { oObj[sProperty] = sSet; oCache[sCache] = sSet; } }, /** * Copy the classes of all child nodes from one element to another. This implies * that the two have identical structure - no error checking is performed to that * fact. * @param {element} source Node to copy classes from * @param {element} dest Node to copy classes too */ _fnClassUpdate: function ( source, dest ) { var that = this; if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" || source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" ) { dest.className = source.className; } $(source).children().each( function (i) { that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] ); } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cloning functions */ /* * Function: _fnCloneThead * Purpose: Clone the thead element * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneThead: function ( oCache ) { var s = this.fnGetSettings(); var nTable = oCache.nNode; if ( s.bInitComplete && !s.oCloneOnDraw.top ) { this._fnClassUpdate( $('thead', s.nTable)[0], $('thead', nTable)[0] ); return; } /* Set the wrapper width to match that of the cloned table */ var iDtWidth = $(s.nTable).outerWidth(); oCache.nWrapper.style.width = iDtWidth+"px"; nTable.style.width = iDtWidth+"px"; /* Remove any children the cloned table has */ while ( nTable.childNodes.length > 0 ) { $('thead th', nTable).unbind( 'click' ); nTable.removeChild( nTable.childNodes[0] ); } /* Clone the DataTables header */ var nThead = $('thead', s.nTable).clone(true)[0]; nTable.appendChild( nThead ); /* Copy the widths across - apparently a clone isn't good enough for this */ var a = []; var b = []; $("thead>tr th", s.nTable).each( function (i) { a.push( $(this).width() ); } ); $("thead>tr td", s.nTable).each( function (i) { b.push( $(this).width() ); } ); $("thead>tr th", s.nTable).each( function (i) { $("thead>tr th:eq("+i+")", nTable).width( a[i] ); $(this).width( a[i] ); } ); $("thead>tr td", s.nTable).each( function (i) { $("thead>tr td:eq("+i+")", nTable).width( b[i] ); $(this).width( b[i] ); } ); // Stop DataTables 1.9 from putting a focus ring on the headers when // clicked to sort $('th.sorting, th.sorting_desc, th.sorting_asc', nTable).bind( 'click', function () { this.blur(); } ); }, /* * Function: _fnCloneTfoot * Purpose: Clone the tfoot element * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTfoot: function ( oCache ) { var s = this.fnGetSettings(); var nTable = oCache.nNode; /* Set the wrapper width to match that of the cloned table */ oCache.nWrapper.style.width = $(s.nTable).outerWidth()+"px"; /* Remove any children the cloned table has */ while ( nTable.childNodes.length > 0 ) { nTable.removeChild( nTable.childNodes[0] ); } /* Clone the DataTables footer */ var nTfoot = $('tfoot', s.nTable).clone(true)[0]; nTable.appendChild( nTfoot ); /* Copy the widths across - apparently a clone isn't good enough for this */ $("tfoot:eq(0)>tr th", s.nTable).each( function (i) { $("tfoot:eq(0)>tr th:eq("+i+")", nTable).width( $(this).width() ); } ); $("tfoot:eq(0)>tr td", s.nTable).each( function (i) { $("tfoot:eq(0)>tr td:eq("+i+")", nTable).width( $(this).width() ); } ); }, /* * Function: _fnCloneTLeft * Purpose: Clone the left column(s) * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTLeft: function ( oCache ) { var s = this.fnGetSettings(); var nTable = oCache.nNode; var nBody = $('tbody', s.nTable)[0]; /* Remove any children the cloned table has */ while ( nTable.childNodes.length > 0 ) { nTable.removeChild( nTable.childNodes[0] ); } /* Is this the most efficient way to do this - it looks horrible... */ nTable.appendChild( $("thead", s.nTable).clone(true)[0] ); nTable.appendChild( $("tbody", s.nTable).clone(true)[0] ); if ( s.bFooter ) { nTable.appendChild( $("tfoot", s.nTable).clone(true)[0] ); } /* Remove unneeded cells */ var sSelector = 'gt(' + (oCache.iCells - 1) + ')'; $('thead tr', nTable).each( function (k) { $('th:' + sSelector, this).remove(); } ); $('tfoot tr', nTable).each( function (k) { $('th:' + sSelector, this).remove(); } ); $('tbody tr', nTable).each( function (k) { $('td:' + sSelector, this).remove(); } ); this.fnEqualiseHeights( 'thead', nBody.parentNode, nTable ); this.fnEqualiseHeights( 'tbody', nBody.parentNode, nTable ); this.fnEqualiseHeights( 'tfoot', nBody.parentNode, nTable ); var iWidth = 0; for (var i = 0; i < oCache.iCells; i++) { iWidth += $('thead tr th:eq(' + i + ')', s.nTable).outerWidth(); } nTable.style.width = iWidth+"px"; oCache.nWrapper.style.width = iWidth+"px"; }, /* * Function: _fnCloneTRight * Purpose: Clone the right most column(s) * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTRight: function ( oCache ) { var s = this.fnGetSettings(); var nBody = $('tbody', s.nTable)[0]; var nTable = oCache.nNode; var iCols = $('tbody tr:eq(0) td', s.nTable).length; /* Remove any children the cloned table has */ while ( nTable.childNodes.length > 0 ) { nTable.removeChild( nTable.childNodes[0] ); } /* Is this the most efficient way to do this - it looks horrible... */ nTable.appendChild( $("thead", s.nTable).clone(true)[0] ); nTable.appendChild( $("tbody", s.nTable).clone(true)[0] ); if ( s.bFooter ) { nTable.appendChild( $("tfoot", s.nTable).clone(true)[0] ); } $('thead tr th:lt('+(iCols-oCache.iCells)+')', nTable).remove(); $('tfoot tr th:lt('+(iCols-oCache.iCells)+')', nTable).remove(); /* Remove unneeded cells */ $('tbody tr', nTable).each( function (k) { $('td:lt('+(iCols-oCache.iCells)+')', this).remove(); } ); this.fnEqualiseHeights( 'thead', nBody.parentNode, nTable ); this.fnEqualiseHeights( 'tbody', nBody.parentNode, nTable ); this.fnEqualiseHeights( 'tfoot', nBody.parentNode, nTable ); var iWidth = 0; for (var i = 0; i < oCache.iCells; i++) { iWidth += $('thead tr th:eq('+(iCols-1-i)+')', s.nTable).outerWidth(); } nTable.style.width = iWidth+"px"; oCache.nWrapper.style.width = iWidth+"px"; }, /** * Equalise the heights of the rows in a given table node in a cross browser way. Note that this * is more or less lifted as is from FixedColumns * @method fnEqualiseHeights * @returns void * @param {string} parent Node type - thead, tbody or tfoot * @param {element} original Original node to take the heights from * @param {element} clone Copy the heights to * @private */ "fnEqualiseHeights": function ( parent, original, clone ) { var that = this; var originals = $(parent +' tr', original); var height; $(parent+' tr', clone).each( function (k) { height = originals.eq( k ).css('height'); // This is nasty :-(. IE has a sub-pixel error even when setting // the height below (the Firefox fix) which causes the fixed column // to go out of alignment. Need to add a pixel before the assignment // Can this be feature detected? Not sure how... if ( navigator.appName == 'Microsoft Internet Explorer' ) { height = parseInt( height, 10 ) + 1; } $(this).css( 'height', height ); // For Firefox to work, we need to also set the height of the // original row, to the value that we read from it! Otherwise there // is a sub-pixel rounding error originals.eq( k ).css( 'height', height ); } ); } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static properties and methods * We use these for speed! This information is common to all instances of FixedHeader, so no * point if having them calculated and stored for each different instance. */ /* * Variable: oWin * Purpose: Store information about the window positioning * Scope: FixedHeader */ FixedHeader.oWin = { "iScrollTop": 0, "iScrollRight": 0, "iScrollBottom": 0, "iScrollLeft": 0, "iHeight": 0, "iWidth": 0 }; /* * Variable: oDoc * Purpose: Store information about the document size * Scope: FixedHeader */ FixedHeader.oDoc = { "iHeight": 0, "iWidth": 0 }; /* * Variable: afnScroll * Purpose: Array of functions that are to be used for the scrolling components * Scope: FixedHeader */ FixedHeader.afnScroll = []; /* * Function: fnMeasure * Purpose: Update the measurements for the window and document * Returns: - * Inputs: - */ FixedHeader.fnMeasure = function () { var jqWin = $(window), jqDoc = $(document), oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc; oDoc.iHeight = jqDoc.height(); oDoc.iWidth = jqDoc.width(); oWin.iHeight = jqWin.height(); oWin.iWidth = jqWin.width(); oWin.iScrollTop = jqWin.scrollTop(); oWin.iScrollLeft = jqWin.scrollLeft(); oWin.iScrollRight = oDoc.iWidth - oWin.iScrollLeft - oWin.iWidth; oWin.iScrollBottom = oDoc.iHeight - oWin.iScrollTop - oWin.iHeight; }; FixedHeader.version = "2.1.2"; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Global processing */ /* * Just one 'scroll' event handler in FixedHeader, which calls the required components. This is * done as an optimisation, to reduce calculation and proagation time */ $(window).scroll( function () { FixedHeader.fnMeasure(); for ( var i=0, iLen=FixedHeader.afnScroll.length ; i<iLen ; i++ ) { FixedHeader.afnScroll[i](); } } ); $.fn.dataTable.FixedHeader = FixedHeader; $.fn.DataTable.FixedHeader = FixedHeader; return FixedHeader; }; // /factory // Define as an AMD module if possible if ( typeof define === 'function' && define.amd ) { define( ['jquery', 'datatables'], factory ); } else if ( typeof exports === 'object' ) { // Node/CommonJS factory( require('jquery'), require('datatables') ); } else if ( jQuery && !jQuery.fn.dataTable.FixedHeader ) { // Otherwise simply initialise as normal, stopping multiple evaluation factory( jQuery, jQuery.fn.dataTable ); } })(window, document);
jagathsisira/app-cloud
modules/setup-scripts/conf/wso2das-3.0.1/repository/deployment/server/jaggeryapps/monitoring/themes/theme0/ui/thirdparty/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js
JavaScript
apache-2.0
29,978