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) 1996, 2017, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.zip;
/**
* This class provides support for general purpose compression using the
* popular ZLIB compression library. The ZLIB compression library was
* initially developed as part of the PNG graphics standard and is not
* protected by patents. It is fully described in the specifications at
* the <a href="package-summary.html#package_description">java.util.zip
* package description</a>.
*
* <p>The following code fragment demonstrates a trivial compression
* and decompression of a string using {@code Deflater} and
* {@code Inflater}.
*
* <blockquote><pre>
* try {
* // Encode a String into bytes
* String inputString = "blahblahblah";
* byte[] input = inputString.getBytes("UTF-8");
*
* // Compress the bytes
* byte[] output = new byte[100];
* Deflater compresser = new Deflater();
* compresser.setInput(input);
* compresser.finish();
* int compressedDataLength = compresser.deflate(output);
* compresser.end();
*
* // Decompress the bytes
* Inflater decompresser = new Inflater();
* decompresser.setInput(output, 0, compressedDataLength);
* byte[] result = new byte[100];
* int resultLength = decompresser.inflate(result);
* decompresser.end();
*
* // Decode the bytes into a String
* String outputString = new String(result, 0, resultLength, "UTF-8");
* } catch(java.io.UnsupportedEncodingException ex) {
* // handle
* } catch (java.util.zip.DataFormatException ex) {
* // handle
* }
* </pre></blockquote>
*
* @see Inflater
* @author David Connelly
*/
public
class Deflater {
private final ZStreamRef zsRef;
private byte[] buf = new byte[0];
private int off, len;
private int level, strategy;
private boolean setParams;
private boolean finish, finished;
private long bytesRead;
private long bytesWritten;
/**
* Compression method for the deflate algorithm (the only one currently
* supported).
*/
public static final int DEFLATED = 8;
/**
* Compression level for no compression.
*/
public static final int NO_COMPRESSION = 0;
/**
* Compression level for fastest compression.
*/
public static final int BEST_SPEED = 1;
/**
* Compression level for best compression.
*/
public static final int BEST_COMPRESSION = 9;
/**
* Default compression level.
*/
public static final int DEFAULT_COMPRESSION = -1;
/**
* Compression strategy best used for data consisting mostly of small
* values with a somewhat random distribution. Forces more Huffman coding
* and less string matching.
*/
public static final int FILTERED = 1;
/**
* Compression strategy for Huffman coding only.
*/
public static final int HUFFMAN_ONLY = 2;
/**
* Default compression strategy.
*/
public static final int DEFAULT_STRATEGY = 0;
/**
* Compression flush mode used to achieve best compression result.
*
* @see Deflater#deflate(byte[], int, int, int)
* @since 1.7
*/
public static final int NO_FLUSH = 0;
/**
* Compression flush mode used to flush out all pending output; may
* degrade compression for some compression algorithms.
*
* @see Deflater#deflate(byte[], int, int, int)
* @since 1.7
*/
public static final int SYNC_FLUSH = 2;
/**
* Compression flush mode used to flush out all pending output and
* reset the deflater. Using this mode too often can seriously degrade
* compression.
*
* @see Deflater#deflate(byte[], int, int, int)
* @since 1.7
*/
public static final int FULL_FLUSH = 3;
static {
/* Zip library is loaded from System.initializeSystemClass */
initIDs();
}
/**
* Creates a new compressor using the specified compression level.
* If 'nowrap' is true then the ZLIB header and checksum fields will
* not be used in order to support the compression format used in
* both GZIP and PKZIP.
* @param level the compression level (0-9)
* @param nowrap if true then use GZIP compatible compression
*/
public Deflater(int level, boolean nowrap) {
this.level = level;
this.strategy = DEFAULT_STRATEGY;
this.zsRef = new ZStreamRef(init(level, DEFAULT_STRATEGY, nowrap));
}
/**
* Creates a new compressor using the specified compression level.
* Compressed data will be generated in ZLIB format.
* @param level the compression level (0-9)
*/
public Deflater(int level) {
this(level, false);
}
/**
* Creates a new compressor with the default compression level.
* Compressed data will be generated in ZLIB format.
*/
public Deflater() {
this(DEFAULT_COMPRESSION, false);
}
/**
* Sets input data for compression. This should be called whenever
* needsInput() returns true indicating that more input data is required.
* @param b the input data bytes
* @param off the start offset of the data
* @param len the length of the data
* @see Deflater#needsInput
*/
public void setInput(byte[] b, int off, int len) {
if (b== null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || off > b.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
synchronized (zsRef) {
this.buf = b;
this.off = off;
this.len = len;
}
}
/**
* Sets input data for compression. This should be called whenever
* needsInput() returns true indicating that more input data is required.
* @param b the input data bytes
* @see Deflater#needsInput
*/
public void setInput(byte[] b) {
setInput(b, 0, b.length);
}
/**
* Sets preset dictionary for compression. A preset dictionary is used
* when the history buffer can be predetermined. When the data is later
* uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
* in order to get the Adler-32 value of the dictionary required for
* decompression.
* @param b the dictionary data bytes
* @param off the start offset of the data
* @param len the length of the data
* @see Inflater#inflate
* @see Inflater#getAdler
*/
public void setDictionary(byte[] b, int off, int len) {
if (b == null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || off > b.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
synchronized (zsRef) {
ensureOpen();
setDictionary(zsRef.address(), b, off, len);
}
}
/**
* Sets preset dictionary for compression. A preset dictionary is used
* when the history buffer can be predetermined. When the data is later
* uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
* in order to get the Adler-32 value of the dictionary required for
* decompression.
* @param b the dictionary data bytes
* @see Inflater#inflate
* @see Inflater#getAdler
*/
public void setDictionary(byte[] b) {
setDictionary(b, 0, b.length);
}
/**
* Sets the compression strategy to the specified value.
*
* <p> If the compression strategy is changed, the next invocation
* of {@code deflate} will compress the input available so far with
* the old strategy (and may be flushed); the new strategy will take
* effect only after that invocation.
*
* @param strategy the new compression strategy
* @exception IllegalArgumentException if the compression strategy is
* invalid
*/
public void setStrategy(int strategy) {
switch (strategy) {
case DEFAULT_STRATEGY:
case FILTERED:
case HUFFMAN_ONLY:
break;
default:
throw new IllegalArgumentException();
}
synchronized (zsRef) {
if (this.strategy != strategy) {
this.strategy = strategy;
setParams = true;
}
}
}
/**
* Sets the compression level to the specified value.
*
* <p> If the compression level is changed, the next invocation
* of {@code deflate} will compress the input available so far
* with the old level (and may be flushed); the new level will
* take effect only after that invocation.
*
* @param level the new compression level (0-9)
* @exception IllegalArgumentException if the compression level is invalid
*/
public void setLevel(int level) {
if ((level < 0 || level > 9) && level != DEFAULT_COMPRESSION) {
throw new IllegalArgumentException("invalid compression level");
}
synchronized (zsRef) {
if (this.level != level) {
this.level = level;
setParams = true;
}
}
}
/**
* Returns true if the input data buffer is empty and setInput()
* should be called in order to provide more input.
* @return true if the input data buffer is empty and setInput()
* should be called in order to provide more input
*/
public boolean needsInput() {
synchronized (zsRef) {
return len <= 0;
}
}
/**
* When called, indicates that compression should end with the current
* contents of the input buffer.
*/
public void finish() {
synchronized (zsRef) {
finish = true;
}
}
/**
* Returns true if the end of the compressed data output stream has
* been reached.
* @return true if the end of the compressed data output stream has
* been reached
*/
public boolean finished() {
synchronized (zsRef) {
return finished;
}
}
/**
* Compresses the input data and fills specified buffer with compressed
* data. Returns actual number of bytes of compressed data. A return value
* of 0 indicates that {@link #needsInput() needsInput} should be called
* in order to determine if more input data is required.
*
* <p>This method uses {@link #NO_FLUSH} as its compression flush mode.
* An invocation of this method of the form {@code deflater.deflate(b, off, len)}
* yields the same result as the invocation of
* {@code deflater.deflate(b, off, len, Deflater.NO_FLUSH)}.
*
* @param b the buffer for the compressed data
* @param off the start offset of the data
* @param len the maximum number of bytes of compressed data
* @return the actual number of bytes of compressed data written to the
* output buffer
*/
public int deflate(byte[] b, int off, int len) {
return deflate(b, off, len, NO_FLUSH);
}
/**
* Compresses the input data and fills specified buffer with compressed
* data. Returns actual number of bytes of compressed data. A return value
* of 0 indicates that {@link #needsInput() needsInput} should be called
* in order to determine if more input data is required.
*
* <p>This method uses {@link #NO_FLUSH} as its compression flush mode.
* An invocation of this method of the form {@code deflater.deflate(b)}
* yields the same result as the invocation of
* {@code deflater.deflate(b, 0, b.length, Deflater.NO_FLUSH)}.
*
* @param b the buffer for the compressed data
* @return the actual number of bytes of compressed data written to the
* output buffer
*/
public int deflate(byte[] b) {
return deflate(b, 0, b.length, NO_FLUSH);
}
/**
* Compresses the input data and fills the specified buffer with compressed
* data. Returns actual number of bytes of data compressed.
*
* <p>Compression flush mode is one of the following three modes:
*
* <ul>
* <li>{@link #NO_FLUSH}: allows the deflater to decide how much data
* to accumulate, before producing output, in order to achieve the best
* compression (should be used in normal use scenario). A return value
* of 0 in this flush mode indicates that {@link #needsInput()} should
* be called in order to determine if more input data is required.
*
* <li>{@link #SYNC_FLUSH}: all pending output in the deflater is flushed,
* to the specified output buffer, so that an inflater that works on
* compressed data can get all input data available so far (In particular
* the {@link #needsInput()} returns {@code true} after this invocation
* if enough output space is provided). Flushing with {@link #SYNC_FLUSH}
* may degrade compression for some compression algorithms and so it
* should be used only when necessary.
*
* <li>{@link #FULL_FLUSH}: all pending output is flushed out as with
* {@link #SYNC_FLUSH}. The compression state is reset so that the inflater
* that works on the compressed output data can restart from this point
* if previous compressed data has been damaged or if random access is
* desired. Using {@link #FULL_FLUSH} too often can seriously degrade
* compression.
* </ul>
*
* <p>In the case of {@link #FULL_FLUSH} or {@link #SYNC_FLUSH}, if
* the return value is {@code len}, the space available in output
* buffer {@code b}, this method should be invoked again with the same
* {@code flush} parameter and more output space. Make sure that
* {@code len} is greater than 6 to avoid flush marker (5 bytes) being
* repeatedly output to the output buffer every time this method is
* invoked.
*
* @param b the buffer for the compressed data
* @param off the start offset of the data
* @param len the maximum number of bytes of compressed data
* @param flush the compression flush mode
* @return the actual number of bytes of compressed data written to
* the output buffer
*
* @throws IllegalArgumentException if the flush mode is invalid
* @since 1.7
*/
public int deflate(byte[] b, int off, int len, int flush) {
if (b == null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || off > b.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
synchronized (zsRef) {
ensureOpen();
if (flush == NO_FLUSH || flush == SYNC_FLUSH ||
flush == FULL_FLUSH) {
int thisLen = this.len;
int n = deflateBytes(zsRef.address(), b, off, len, flush);
bytesWritten += n;
bytesRead += (thisLen - this.len);
return n;
}
throw new IllegalArgumentException();
}
}
/**
* Returns the ADLER-32 value of the uncompressed data.
* @return the ADLER-32 value of the uncompressed data
*/
public int getAdler() {
synchronized (zsRef) {
ensureOpen();
return getAdler(zsRef.address());
}
}
/**
* Returns the total number of uncompressed bytes input so far.
*
* <p>Since the number of bytes may be greater than
* Integer.MAX_VALUE, the {@link #getBytesRead()} method is now
* the preferred means of obtaining this information.</p>
*
* @return the total number of uncompressed bytes input so far
*/
public int getTotalIn() {
return (int) getBytesRead();
}
/**
* Returns the total number of uncompressed bytes input so far.
*
* @return the total (non-negative) number of uncompressed bytes input so far
* @since 1.5
*/
public long getBytesRead() {
synchronized (zsRef) {
ensureOpen();
return bytesRead;
}
}
/**
* Returns the total number of compressed bytes output so far.
*
* <p>Since the number of bytes may be greater than
* Integer.MAX_VALUE, the {@link #getBytesWritten()} method is now
* the preferred means of obtaining this information.</p>
*
* @return the total number of compressed bytes output so far
*/
public int getTotalOut() {
return (int) getBytesWritten();
}
/**
* Returns the total number of compressed bytes output so far.
*
* @return the total (non-negative) number of compressed bytes output so far
* @since 1.5
*/
public long getBytesWritten() {
synchronized (zsRef) {
ensureOpen();
return bytesWritten;
}
}
/**
* Resets deflater so that a new set of input data can be processed.
* Keeps current compression level and strategy settings.
*/
public void reset() {
synchronized (zsRef) {
ensureOpen();
reset(zsRef.address());
finish = false;
finished = false;
off = len = 0;
bytesRead = bytesWritten = 0;
}
}
/**
* Closes the compressor and discards any unprocessed input.
* This method should be called when the compressor is no longer
* being used, but will also be called automatically by the
* finalize() method. Once this method is called, the behavior
* of the Deflater object is undefined.
*/
public void end() {
synchronized (zsRef) {
long addr = zsRef.address();
zsRef.clear();
if (addr != 0) {
end(addr);
buf = null;
}
}
}
/**
* Closes the compressor when garbage is collected.
*
* @deprecated The {@code finalize} method has been deprecated.
* Subclasses that override {@code finalize} in order to perform cleanup
* should be modified to use alternative cleanup mechanisms and
* to remove the overriding {@code finalize} method.
* When overriding the {@code finalize} method, its implementation must explicitly
* ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}.
* See the specification for {@link Object#finalize()} for further
* information about migration options.
*/
@Deprecated(since="9")
protected void finalize() {
end();
}
private void ensureOpen() {
assert Thread.holdsLock(zsRef);
if (zsRef.address() == 0)
throw new NullPointerException("Deflater has been closed");
}
private static native void initIDs();
private static native long init(int level, int strategy, boolean nowrap);
private static native void setDictionary(long addr, byte[] b, int off, int len);
private native int deflateBytes(long addr, byte[] b, int off, int len,
int flush);
private static native int getAdler(long addr);
private static native void reset(long addr);
private static native void end(long addr);
}
| dmlloyd/openjdk-modules | jdk/src/java.base/share/classes/java/util/zip/Deflater.java | Java | gpl-2.0 | 20,477 |
<?php
/**
* @package Crowdfunding
* @subpackage Components
* @author Todor Iliev
* @copyright Copyright (C) 2015 Todor Iliev <todor@itprism.com>. All rights reserved.
* @license GNU General Public License version 3 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die;
?>
<div class="span8">
<table class="table table-bordered">
<thead>
<tr>
<th width="1%">#</th>
<th class="title">
<?php echo JText::_("COM_CROWDFUNDING_REWARD"); ?>
</th>
<th width="30%">
<?php echo JText::_("COM_CROWDFUNDING_TRANSACTION_ID"); ?>
</th>
<th width="10%" class="center hidden-phone">
<?php echo JText::_("JSTATUS"); ?>
</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach($this->rewards as $reward) {
$classRow = (!$reward["reward_state"]) ? "" : 'class="success"';
?>
<tr <?php echo $classRow; ?>>
<td><?php echo $i; ?></td>
<td class="has-context">
<a href="<?php echo JRoute::_("index.php?option=com_crowdfunding&view=rewards&pid=".(int)$reward["project_id"]."&filter_search=id:" . (int)$reward["reward_id"]); ?>">
<?php echo $this->escape($reward["reward_name"]); ?>
</a>
<div class="small">
<?php echo JText::_("COM_CROWDFUNDING_PROJECT"); ?>:
<a href="<?php echo JRoute::_("index.php?option=com_crowdfunding&view=projects&filter_search=id:" . (int)$reward["project_id"]); ?>">
<?php echo $this->escape($reward["project"]); ?>
</a>
</div>
</td>
<td>
<a href="<?php echo JRoute::_("index.php?option=com_crowdfunding&view=transactions&filter_search=id:" . (int)$reward["transaction_id"]); ?>">
<?php echo $this->escape($reward["txn_id"]); ?>
</a>
</td>
<td class="center hidden-phone">
<?php echo JHtml::_('crowdfundingbackend.rewardState', $reward["reward_id"], $reward["transaction_id"], $reward["reward_state"], $this->returnUrl); ?>
</td>
</tr>
<?php
$i++;
} ?>
</tbody>
</table>
</div>
| snake77se/proyectoszeppelin | administrator/components/com_crowdfunding/views/user/tmpl/default_rewards.php | PHP | gpl-2.0 | 2,582 |
package trubbl.issues.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import trubbl.sharedkernel.domain.Key;
import trubbl.sharedkernel.domain.Keyable;
public class Issue implements Keyable {
@JsonProperty
private Key key;
@JsonProperty
private String title;
@JsonProperty
private String description;
public Issue(String title, String description) {
this();
this.title = title;
this.description = description;
}
public Key key() {
return this.key;
}
// REST
public Issue() {
this.key = new Key();
}
}
| thesam/trubbl | trubbl-issues/src/main/java/trubbl/issues/domain/Issue.java | Java | gpl-2.0 | 545 |
/*
This file is part of GtkRadiant.
GtkRadiant 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.
GtkRadiant 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 GtkRadiant; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "ufoai_filters.h"
#include "ibrush.h"
#include "ientity.h"
#include "iscenegraph.h"
// believe me, i'm sorry
#include "../../radiant/brush.h"
#include "generic/callback.h"
#include <list>
bool actorclip_active = false;
bool stepon_active = false;
bool nodraw_active = false;
bool weaponclip_active = false;
int level_active = 0;
// TODO: This should be added to ibrush.h
// like already done for Node_getEntity in ientity.h
// FIXME: Doesn't belong here
inline Brush* Node_getBrush(scene::Node& node)
{
return NodeTypeCast<Brush>::cast(node);
}
void hide_node(scene::Node& node, bool hide)
{
hide
? node.enable(scene::Node::eHidden)
: node.disable(scene::Node::eHidden);
}
typedef std::list<Entity*> entitylist_t;
class EntityFindByName : public scene::Graph::Walker
{
const char* m_name;
entitylist_t& m_entitylist;
/* this starts at 1 << level */
int m_flag;
int m_hide;
public:
EntityFindByName(const char* name, entitylist_t& entitylist, int flag, bool hide)
: m_name(name), m_entitylist(entitylist), m_flag(flag), m_hide(hide)
{
}
bool pre(const scene::Path& path, scene::Instance& instance) const
{
int spawnflagsInt;
Entity* entity = Node_getEntity(path.top());
if (entity != 0)
{
if (string_equal(m_name, entity->getKeyValue("classname")))
{
const char *spawnflags = entity->getKeyValue("spawnflags");
globalOutputStream() << "spawnflags for " << m_name << ": " << spawnflags << ".\n";
if (!string_empty(spawnflags)) {
spawnflagsInt = atoi(spawnflags);
if (!(spawnflagsInt & m_flag))
{
hide_node(path.top(), m_hide); // hide/unhide
m_entitylist.push_back(entity);
}
}
else
{
globalOutputStream() << "UFO:AI: Warning: no spawnflags for " << m_name << ".\n";
}
}
}
return true;
}
};
class ForEachFace : public BrushVisitor
{
Brush &m_brush;
public:
mutable int m_contentFlagsVis;
mutable int m_surfaceFlagsVis;
ForEachFace(Brush& brush)
: m_brush(brush)
{
m_contentFlagsVis = -1;
m_surfaceFlagsVis = -1;
}
void visit(Face& face) const
{
#if _DEBUG
if (m_surfaceFlagsVis < 0)
m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags;
else if (m_surfaceFlagsVis >= 0 && m_surfaceFlagsVis != face.getShader().m_flags.m_surfaceFlags)
globalOutputStream() << "Faces with different surfaceflags at brush\n";
if (m_contentFlagsVis < 0)
m_contentFlagsVis = face.getShader().m_flags.m_contentFlags;
else if (m_contentFlagsVis >= 0 && m_contentFlagsVis != face.getShader().m_flags.m_contentFlags)
globalOutputStream() << "Faces with different contentflags at brush\n";
#else
m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags;
m_contentFlagsVis = face.getShader().m_flags.m_contentFlags;
#endif
}
};
typedef std::list<Brush*> brushlist_t;
class BrushGetLevel : public scene::Graph::Walker
{
brushlist_t& m_brushlist;
int m_flag;
bool m_content; // if true - use m_contentFlags - otherwise m_surfaceFlags
mutable bool m_notset;
mutable bool m_hide;
public:
BrushGetLevel(brushlist_t& brushlist, int flag, bool content, bool notset, bool hide)
: m_brushlist(brushlist), m_flag(flag), m_content(content), m_notset(notset), m_hide(hide)
{
}
bool pre(const scene::Path& path, scene::Instance& instance) const
{
Brush* brush = Node_getBrush(path.top());
if (brush != 0)
{
ForEachFace faces(*brush);
brush->forEachFace(faces);
// contentflags?
if (m_content)
{
// are any flags set?
if (faces.m_contentFlagsVis > 0)
{
// flag should not be set
if (m_notset && (!(faces.m_contentFlagsVis & m_flag)))
{
hide_node(path.top(), m_hide);
m_brushlist.push_back(brush);
}
// check whether flag is set
else if (!m_notset && ((faces.m_contentFlagsVis & m_flag)))
{
hide_node(path.top(), m_hide);
m_brushlist.push_back(brush);
}
}
}
// surfaceflags?
else
{
// are any flags set?
if (faces.m_surfaceFlagsVis > 0)
{
// flag should not be set
if (m_notset && (!(faces.m_surfaceFlagsVis & m_flag)))
{
hide_node(path.top(), m_hide);
m_brushlist.push_back(brush);
}
// check whether flag is set
else if (!m_notset && ((faces.m_surfaceFlagsVis & m_flag)))
{
hide_node(path.top(), m_hide);
m_brushlist.push_back(brush);
}
}
}
}
return true;
}
};
/**
* @brief Activates the level filter for the given level
* @param[in] level Which level to show?
* @todo Entities
*/
void filter_level(int flag)
{
int level;
brushlist_t brushes;
entitylist_t entities;
level = (flag >> 8);
if (level_active)
{
GlobalSceneGraph().traverse(BrushGetLevel(brushes, (level_active << 8), true, true, false));
GlobalSceneGraph().traverse(EntityFindByName("func_door", entities, level_active, false));
GlobalSceneGraph().traverse(EntityFindByName("func_breakable", entities, level_active, false));
GlobalSceneGraph().traverse(EntityFindByName("misc_model", entities, level_active, false));
GlobalSceneGraph().traverse(EntityFindByName("misc_particle", entities, level_active, false));
entities.erase(entities.begin(), entities.end());
brushes.erase(brushes.begin(), brushes.end());
if (level_active == level)
{
level_active = 0;
// just disabĺe level filter
return;
}
}
level_active = level;
globalOutputStream() << "UFO:AI: level_active: " << level_active << ", flag: " << flag << ".\n";
// first all brushes
GlobalSceneGraph().traverse(BrushGetLevel(brushes, flag, true, true, true));
// now all entities
GlobalSceneGraph().traverse(EntityFindByName("func_door", entities, level, true));
GlobalSceneGraph().traverse(EntityFindByName("func_breakable", entities, level, true));
GlobalSceneGraph().traverse(EntityFindByName("misc_model", entities, level, true));
GlobalSceneGraph().traverse(EntityFindByName("misc_particle", entities, level, true));
#ifdef _DEBUG
if (brushes.empty())
{
globalOutputStream() << "UFO:AI: No brushes.\n";
}
else
{
globalOutputStream() << "UFO:AI: Found " << Unsigned(brushes.size()) << " brushes.\n";
}
// now let's filter all entities like misc_model, func_breakable and func_door that have the spawnflags set
if (entities.empty())
{
globalOutputStream() << "UFO:AI: No entities.\n";
}
else
{
globalOutputStream() << "UFO:AI: Found " << Unsigned(entities.size()) << " entities.\n";
}
#endif
}
void filter_stepon (void)
{
if (stepon_active) {
stepon_active = false;
} else {
stepon_active = true;
}
brushlist_t brushes;
GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_STEPON, true, false, stepon_active));
if (brushes.empty())
{
globalOutputStream() << "UFO:AI: No brushes.\n";
}
else
{
globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " stepon brushes.\n";
}
}
void filter_nodraw (void)
{
if (nodraw_active) {
nodraw_active = false;
} else {
nodraw_active = true;
}
brushlist_t brushes;
GlobalSceneGraph().traverse(BrushGetLevel(brushes, SURF_NODRAW, false, false, nodraw_active));
#ifdef _DEBUG
if (brushes.empty())
{
globalOutputStream() << "UFO:AI: No brushes.\n";
}
else
{
globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " nodraw brushes.\n";
}
#endif
}
void filter_actorclip (void)
{
if (actorclip_active) {
actorclip_active = false;
} else {
actorclip_active = true;
}
brushlist_t brushes;
GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_ACTORCLIP, true, false, actorclip_active));
#ifdef _DEBUG
if (brushes.empty())
{
globalOutputStream() << "UFO:AI: No brushes.\n";
}
else
{
globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " actorclip brushes.\n";
}
#endif
}
void filter_weaponclip (void)
{
if (weaponclip_active) {
weaponclip_active = false;
} else {
weaponclip_active = true;
}
brushlist_t brushes;
GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_WEAPONCLIP, true, false, weaponclip_active));
#ifdef _DEBUG
if (brushes.empty())
{
globalOutputStream() << "UFO:AI: No brushes.\n";
}
else
{
globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " weaponclip brushes.\n";
}
#endif
}
| raynorpat/cake | src_radiant/contrib/ufoaiplug/ufoai_filters.cpp | C++ | gpl-2.0 | 8,959 |
/****************************************************************************
** Meta object code from reading C++ file 'mimepart.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../GCApp/emailapi/mimepart.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mimepart.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_MimePart_t {
QByteArrayData data[1];
char stringdata0[9];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MimePart_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MimePart_t qt_meta_stringdata_MimePart = {
{
QT_MOC_LITERAL(0, 0, 8) // "MimePart"
},
"MimePart"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MimePart[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MimePart::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject MimePart::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_MimePart.data,
qt_meta_data_MimePart, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *MimePart::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MimePart::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_MimePart.stringdata0))
return static_cast<void*>(const_cast< MimePart*>(this));
return QObject::qt_metacast(_clname);
}
int MimePart::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| nigoole/GCIM | GCIM/build/app/moc_mimepart.cpp | C++ | gpl-2.0 | 2,592 |
<?php
require_once('common.php');
check_logged_in();
if(isset($_SESSION['user']) && $_SESSION['user']['is_logged']==1) {
$PageTitle=getLang('ptitle_logged');
}else{
$PageTitle=getLang('ptitle_notlogged');
}
$db=new DBConnection();
$query='SELECT user_firstname, trading_type,user_lastname,user_account_num FROM users WHERE user_account_num="'.$_SESSION['user']['user_account_num'].'" LIMIT 1';
$res=$db->rq($query);
$username=$db->fetch($res);
$userProfile = '';
//---------------------------------------------
$total_trading=0;
$total_trading2=0;
$total_total_fees=0;
$total_purchase=0;
$total_sales=0;
$total_fees=0;
$query='SELECT SUM(trade_value) AS total_purchase FROM trades WHERE trade_type=1 AND trade_status IN (1,4) AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_trading-=$row['total_purchase'];
$total_trading2-=$row['total_purchase'];
$total_purchase+=$row['total_purchase'];
$query='SELECT SUM(trade_value) AS total_purchase FROM stock_trades WHERE trade_type=1 AND trade_status IN (1,4) AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_trading-=$row['total_purchase'];
$total_trading2-=$row['total_purchase'];
$total_purchase+=$row['total_purchase'];
$query='SELECT SUM(trade_value) AS total_purchase FROM stock_trades WHERE trade_type=3 AND trade_status IN (1,4) AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_trading-=$row['total_purchase'];
$total_trading2-=$row['total_purchase'];
$total_purchase+=$row['total_purchase'];
$query='SELECT SUM(trade_value) AS total_sales FROM trades WHERE trade_type=2 AND trade_status IN (1,4) AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_trading+=$row['total_sales'];
$total_trading2+=$row['total_sales'];
$total_sales+=$row['total_sales'];
$query='SELECT SUM(trade_value) AS total_sales FROM stock_trades WHERE trade_type=2 AND trade_status IN (1,4) AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_trading+=$row['total_sales'];
$total_trading2+=$row['total_sales'];
$total_sales+=$row['total_sales'];
$query='SELECT SUM(trade_value) AS total_sales FROM stock_trades WHERE trade_type=4 AND trade_status IN (1,4) AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_trading+=$row['total_sales'];
$total_trading2+=$row['total_sales'];
$total_sales+=$row['total_sales'];
$query='SELECT SUM(trade_fees) AS total_fees FROM trades WHERE trade_status IN (1,4) AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_trading-=$row['total_fees'];
$total_total_fees+=$row['total_fees'];
$total_fees+=$row['total_fees'];
$query='SELECT SUM(trade_fees) AS total_fees FROM stock_trades WHERE trade_status IN (1,4) AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_trading-=$row['total_fees'];
$total_total_fees+=$row['total_fees'];
$total_fees+=$row['total_fees'];
if($total_trading<0) {
$total_trading=number_format($total_trading,2);
$total_trading=str_replace('-','$',$total_trading);
$total_trading='<b class="text-danger">'.$total_trading.'</b>';
}else{
$total_trading='<b class="text-success">$'.number_format($total_trading,2).'</b>';
}
//----------------------------
$total_funding=0;
$total_funding2=0;
$query='SELECT SUM(tr_value) AS total_deposit FROM transfers WHERE tr_type=1 AND tr_status=1 AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_funding+=$row['total_deposit'];
$total_funding2+=$row['total_deposit'];
$total_deposit=number_format($row['total_deposit'],2);
$query='SELECT SUM(tr_value) AS total_withdraw FROM transfers WHERE tr_type=2 AND tr_status=1 AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_funding-=$row['total_withdraw'];
$total_funding2-=$row['total_withdraw'];
$total_withdraw=number_format($row['total_withdraw'],2);
$query='SELECT SUM(tr_fees) AS total_fees2 FROM transfers WHERE tr_status=1 AND user_account_num="'.$_SESSION['user']['user_account_num'].'"';
$res=$db->rq($query);
$row=$db->fetch($res);
$total_funding-=$row['total_fees2'];
$total_total_fees+=$row['total_fees2'];
$total_fees2=number_format($row['total_fees2'],2);
if($total_funding<0) {
$total_funding=number_format($total_funding,2);
$total_funding=str_replace('-','-$',$total_funding);
$total_funding='<b class="text-danger">'.$total_funding.'</b>';
}else{
$total_funding='<b class="text-success">$'.number_format($total_funding,2).'</b>';
}
//----------------------------------------------------------------
$account_balance=0;
$query='SELECT * FROM users WHERE user_account_num="'.$_SESSION['user']['user_account_num'].'" LIMIT 1';
$res=$db->rq($query);
$row=$db->fetch($res);
$userTitles=array(1=>'Mr.',2=>'Mrs.',3=>'Miss',4=>'Dr.',5=>'Pr.');
$account_num_short=explode('-',$row['user_fullref']);
$account_balance=$row['user_balance'];
if($total_trading2<0) {
$total_trading2=number_format($total_trading2,2);
$total_trading2=str_replace('-','-$',$total_trading2);
$total_trading2='<b class="text-danger">'.$total_trading2.'</b>';
}else{
$total_trading2='<b class="text-success">$'.number_format($total_trading2,2).'</b>';
}
if($total_funding2<0) {
$total_funding2=number_format($total_funding2,2);
$total_funding2=str_replace('-','-$',$total_funding2);
$total_funding2='<b class="text-danger">'.$total_funding2.'</b>';
}else{
$total_funding2='<b class="text-success">$'.number_format($total_funding2,2).'</b>';
}
$total_total_fees='<b class="text-danger">$'.number_format($total_total_fees,2).'</b>';
if($account_balance<0) {
$account_balance=number_format($account_balance,2);
$account_balance=str_replace('-','-$',$account_balance);
$account_balance='<b class="text-danger">'.$account_balance.'</b>';
}else{
$account_balance='<b class="text-success">$'.number_format($account_balance,2).'</b>';
}
// ------------------------------------
if($row['user_advisor1']>0) {
$query2 = 'SELECT * FROM users_advisors WHERE users_advisors_id=' . ($row['user_advisor1'] + 0) . ' LIMIT 1';
$res2 = $db->rq($query2);
$row2 = $db->fetch($res2);
} else {
$row2 = false;
}
if($row['user_advisor2']>0&&$row['user_advisor1']!=$row['user_advisor2']) {
$query2 = 'SELECT * FROM users_advisors WHERE users_advisors_id=' . ($row['user_advisor2'] + 0) . ' LIMIT 1';
$res2 = $db->rq($query2);
$row3 = $db->fetch($res2);
} else {
$row3 = false;
}
$line_script = "<script type=\"text/javascript\">
analytics.identify('{$row['user_account_num']}', {
email : '{$row['user_email']}',
firm : '{$row2['advisor_firm']}',
name : '{$row['user_account_name']}'
});
analytics.track('Signed In');
analytics.page('WP Login');
</script>";
$active = 'index';
get_view('layouts/header', compact('username', 'PageTitle'));
get_view('layouts/sidebar', compact('active'));
get_view('index_view', compact('row3', 'row2', 'userTitles', 'row', 'total_trading2', 'total_funding2', 'total_total_fees', 'account_balance', 'total_purchase', 'total_sales', 'total_fees', 'total_trading', 'total_deposit', 'total_withdraw', 'total_fees2', 'total_funding'));
get_view('layouts/right_sidebar');
get_view('layouts/footer', compact('line_script')); | sahartak/v1poject | index.php | PHP | gpl-2.0 | 7,744 |
<?php
if (empty($feed)) {
$blog = 1;
$feed = 'rss';
$doing_rss = 1;
require('wp-blog-header.php');
}
header('Content-type: text/xml; charset=' . get_settings('blog_charset'), true);
$more = 1;
?>
<?php echo '<?xml version="1.0" encoding="'.get_settings('blog_charset').'"?'.'>'; ?>
<!-- generator="wordpress/<?php echo $wp_version ?>" -->
<rss version="0.92">
<channel>
<title><?php bloginfo_rss('name') ?></title>
<link><?php bloginfo_rss('url') ?></link>
<description><?php bloginfo_rss('description') ?></description>
<lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), 0); ?></lastBuildDate>
<docs>http://backend.userland.com/rss092</docs>
<language><?php echo get_option('rss_language'); ?></language>
<?php $items_count = 0; if ($posts) { foreach ($posts as $post) { start_wp(); ?>
<item>
<title><?php the_title_rss() ?></title>
<?php if (get_settings('rss_use_excerpt')) { ?>
<description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
<?php } else { // use content ?>
<description><?php the_content_rss('', 0, '', get_settings('rss_excerpt_length')) ?></description>
<?php } ?>
<link><?php permalink_single_rss() ?></link>
</item>
<?php $items_count++; if (($items_count == get_settings('posts_per_rss')) && empty($m)) { break; } } } ?>
</channel>
</rss>
| JoaoBGusmao/WordPress | wp-rss.php | PHP | gpl-2.0 | 1,341 |
import gnu.qif.RecordArray;
import gnu.qif.AccountRecord;
import gnu.qif.QIFRecord;
/*
The gnu.qif package: A tool for creating QIF files.
Copyright (C) 2001 Nicolas Marchildon
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
import gnu.qif.BankTransaction;
import gnu.qif.OpeningBalanceRecord;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.util.Date;
/**
* <p>A sample usage of the gnu.qif package, used to show how to
* transfer funds from "First Account" to "Second Account"
* back and forth.</p>
*
* <p>You can run this sample by first setting your CLASSPATH
* so that it included the gnu.qif classes (maybe the jar file),
* by compiling it ("javac Sample1.java"), and running it ("java Sample1").</p>
*
* @see gnu.qif
*
* @author <a href="mailto:nicolas@marchildon.net">Nicolas Marchildon</a>
* @version $Id: Sample1.java,v 1.1 2001/11/17 07:29:07 nicolas Exp $
*/
public class Sample1 {
public static void main(String[] args) throws Exception {
RecordArray records = new RecordArray();
String firstAccountName = "First account";
String secondAccountName = "Second account";
/* First, we define the first account */
AccountRecord firstAccount = new AccountRecord(firstAccountName);
records.addRecord(firstAccount);
/* This means we deposit 2$ into firstAccount, from secondAccount */
BankTransaction tr = new BankTransaction();
tr.setNumber("1");
tr.setTotal(2); // Deposit if positive, withdrawal when negative
tr.setDate(new Date());
tr.setMemo("Memo1");
tr.setPayee("Payee1");
tr.setAccount(secondAccountName);
records.addRecord(tr);
/* Now we define the second account */
AccountRecord secondAccount = new AccountRecord(secondAccountName);
records.addRecord(secondAccount);
/* Deposit of 4$ into secondAccount from firstAccount */
BankTransaction tr2 = new BankTransaction();
tr2.setNumber("3");
tr2.setTotal(4);
tr2.setDate(new Date());
tr2.setMemo("Memo2");
tr2.setPayee("Payee2");
tr2.setAccount(firstAccountName);
records.addRecord(tr2);
System.out.println(records.toString());
}
}
| elecnix/gnu-qif | src/gnu/qif/doc-files/Sample1.java | Java | gpl-2.0 | 2,988 |
/*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package com.panet.imeta.job.entries.zipfile;
import com.panet.imeta.i18n.BaseMessages;
public class Messages
{
public static final String packageName = Messages.class.getPackage().getName();
public static String getString(String key)
{
return BaseMessages.getString(packageName, key);
}
public static String getString(String key, String param1)
{
return BaseMessages.getString(packageName, key, param1);
}
public static String getString(String key, String param1, String param2)
{
return BaseMessages.getString(packageName, key, param1, param2);
}
public static String getString(String key, String param1, String param2, String param3)
{
return BaseMessages.getString(packageName, key, param1, param2, param3);
}
public static String getString(String key, String param1, String param2, String param3,
String param4)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4);
}
public static String getString(String key, String param1, String param2, String param3,
String param4, String param5)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5);
}
public static String getString(String key, String param1, String param2, String param3,
String param4, String param5, String param6)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5,
param6);
}
}
| panbasten/imeta | imeta2.x/imeta-src/imeta/src/main/java/com/panet/imeta/job/entries/zipfile/Messages.java | Java | gpl-2.0 | 2,273 |
<?php
$esp = array(
'default:asesores:convocatoria' => ' Se ha abierto una nueva convocatoria: %s. Nos gustaria que fueras parte de ella como asesor,'
. 'esperamos contar contigo. Ingresa en la comunidad Virtual Enjambre e inscribite como evaluador en esta convocatoria'
. ' ¡Te esperamos!.<br><br>'
. 'Para ver los detalles de la convocatoria, %s',
'rechazar_asesor:ok' => 'El Asesor no ha sido aceptado en el Banco',
'rechazar_asesor:error' => 'El Asesor no se pudo rechazar',
'edit:asesoria:ok' => 'Se guardaron los cambios correctamente',
'edit:asesoria:error' => 'Ha ocurrido un error al guardar los cambios',
'asesor:aceptar:ok' => 'Ahora el Maestro pertenece al Banco de Asesores',
'asesor:aceptar:fail' => 'No se ha podido completar la acción',
'asesor:convocar:ok' => 'Se ha notificado a los maestros que integran el banco de asesores.',
'asesor:inscripcion:noasesor' => 'No se puede inscribir, porque no hace parte del banco de asesores.',
'asesor:inscripcion:exitoso' => 'Se ha realizado la inscripción como asesor.',
'asesor:inscripcion:error' => 'No se ha completado la acción.',
'rechazar_asesor:ok' => 'Inscripción del maestro como asesor, rechazado.',
);
add_translation('es', $esp);
| jonreycas/enjambre | mod/asesores/languages/es.php | PHP | gpl-2.0 | 1,304 |
var _hc_windowTimeout;
var _hc_newDemographicHandler = function(args) {
clearTimeout(_hc_windowTimeout);
var window = jQuery("#_hc_window");
jQuery(window).find("#_hc_message, #_hc_read, #_hc_actions, #_hc_match, #_hc_noMatch, #_hc_matchSearch, #_hc_closeBtn").hide();
jQuery(window).find("._hc_mismatch").removeClass("_hc_mismatch");
jQuery(window).find("#_hc_errors").children().remove();
if (!(typeof args["error"] == "undefined")) {
jQuery(window).find("#_hc_closeBtn").hide();
jQuery(window).find("#_hc_status_text_success").hide();
jQuery(window).find("#_hc_status_text_error, #_hc_message_tryAgain, #_hc_message").show();
jQuery(window).find("#_hc_status_icon").attr("class", "_hc_inlineBlock _hc_status_error");
if (args["error"] == "INVALID") {
jQuery(window).find("#_hc_message_readError").css("display", "inline-block");
jQuery(window).find("#_hc_message_issuerError").css("display", "none");
} else if (args["error"] == "ISSUER") {
jQuery(window).find("#_hc_message_readError").css("display", "none");
jQuery(window).find("#_hc_message_issuerError").css("display", "inline-block");
} else {
jQuery(window).find("#_hc_message_readError").css("display", "none");
jQuery(window).find("#_hc_message_issuerError").css("display", "none");
}
_hc_windowTimeout = setTimeout(function() {
jQuery("#_hc_window").css("display", "none");
}, 3000);
} else {
jQuery(window).find("#_hc_status_text_success, #_hc_read, #_hc_layout").show();
jQuery(window).find("#_hc_message, #_hc_status_text_error").hide();
jQuery(window).find("#_hc_status_icon").attr("class", "_hc_inlineBlock _hc_status_success");
jQuery(window).find("#_hc_layout_name").text(args["lastName"] + ", " + args["firstName"]);
jQuery(window).find("#_hc_layout_hin_num").html(args["hin"].substring(0,4) + "• " + args["hin"].substring(4,7) + "• " + args["hin"].substring(7,10) + "•");
jQuery(window).find("#_hc_layout_hin_ver").text(args["hinVer"]);
jQuery(window).find("#_hc_layout_info_dob").text(args["dob"].substring(0,4) + "/" + args["dob"].substring(4,6) + "/" + args["dob"].substring(6,8));
jQuery(window).find("#_hc_layout_info_sex").text((args["sex"] == "1" ? "M" : (args["sex"] == "2" ? "F" : "")));
var issueDate = (args["issueDate"].substring(0,2) <= 30 ? "20" : "19") + args["issueDate"];
jQuery(window).find("#_hc_layout_valid_from").text(issueDate.substring(0,4) + "/" + issueDate.substring(4,6) + "/" + issueDate.substring(6,8));
var hinExp = (args["hinExp"].substring(0,2) <= 30 ? "20" : "19") + args["hinExp"];
jQuery(window).find("#_hc_layout_valid_to").text(hinExp.substring(0,4) + "/" + hinExp.substring(4,6));
if (hinExp != "0000") {
var hinExp = (args["hinExp"].substring(0,2) <= 30 ? "20" : "19") + args["hinExp"] + args["dob"].substring(6,8);
jQuery(window).find("#_hc_layout_valid_to").text(hinExp.substring(0,4) + "/" + hinExp.substring(4,6) + "/" + hinExp.substring(6,8));
var date = new Date();
var hinExpDate = new Date(hinExp.substring(0,4) + "/" + hinExp.substring(4,6) + "/" + hinExp.substring(6, 8));
if (hinExpDate <= new Date()) {
jQuery(window).find("#_hc_layout_valid_to").addClass("_hc_mismatch");
jQuery(window).find("#_hc_errors").append("<div class='_hc_error'>This health card has expired.</div>");
}
jQuery("input[name='end_date_year']").val(hinExp.substring(0,4));
jQuery("input[name='end_date_month']").val(hinExp.substring(4,6));
jQuery("input[name='end_date_date']").val(hinExp.substring(6,8));
} else {
jQuery(window).find("#_hc_layout_valid_to").text("No Expiry");
jQuery("input[name='end_date_year']").val("");
jQuery("input[name='end_date_month']").val("");
jQuery("input[name='end_date_date']").val("");
}
// Add all of these values to the correct fields on the page
jQuery("input[name='keyword']").val("");
jQuery("select[name='hc_type']").val("ON");
if (jQuery("select[name='hc_type']").val() != "ON"){
jQuery("input[name='hc_type']").css({'background-color' : 'yellow'});
jQuery("input[name='hc_type']").val("ON");
}
if (jQuery("input[name='last_name']").val() != args["lastName"]){
jQuery("input[name='last_name']").css({'background-color' : 'yellow'});
jQuery("input[name='last_name']").val(args["lastName"]);
}
if (jQuery("input[name='first_name']").val() != args["firstName"]){
jQuery("input[name='first_name']").css({'background-color' : 'yellow'});
jQuery("input[name='first_name']").val(args["firstName"]);
}
if (jQuery("input[name='hin']").val() != args["hin"]){
jQuery("input[name='hin']").css({'background-color' : 'yellow'});
jQuery("input[name='hin']").val(args["hin"]);
}
if (jQuery("input[name='year_of_birth']").val() != args["dob"].substring(0,4)){
jQuery("input[name='year_of_birth']").css({'background-color' : 'yellow'});
jQuery("input[name='year_of_birth']").val(args["dob"].substring(0,4));
}
if (jQuery("input[name='month_of_birth']").val() != args["dob"].substring(4,6)){
jQuery("input[name='month_of_birth']").css({'background-color' : 'yellow'});
jQuery("input[name='month_of_birth']").val(args["dob"].substring(4,6));
}
if (jQuery("input[name='date_of_birth']").val() != args["dob"].substring(6,8)){
jQuery("input[name='date_of_birth']").css({'background-color' : 'yellow'});
jQuery("input[name='date_of_birth']").val(args["dob"].substring(6,8));
}
if (jQuery("input[name='ver']").val() != args["hinVer"]){
jQuery("input[name='ver']").css({'background-color' : 'yellow'});
jQuery("input[name='ver']").val(args["hinVer"]);
}
if (jQuery("input[name='sex']").val() != (args["sex"] == "1" ? "M" : (args["sex"] == "2" ? "F" : ""))){
jQuery("input[name='sex']").css({'background-color' : 'yellow'});
jQuery("input[name='sex']").val((args["sex"] == "1" ? "M" : (args["sex"] == "2" ? "F" : "")));
}
if (jQuery("input[name='eff_date_year']").val() != issueDate.substring(0,4)){
jQuery("input[name='eff_date_year']").css({'background-color' : 'yellow'});
jQuery("input[name='eff_date_year']").val(issueDate.substring(0,4));
}
if (jQuery("input[name='eff_date_year']").val() != issueDate.substring(0,4)){
jQuery("input[name='eff_date_year']").css({'background-color' : 'yellow'});
jQuery("input[name='eff_date_year']").val(issueDate.substring(0,4));
}
if (jQuery("input[name='eff_date_year']").val() != issueDate.substring(0,4)){
jQuery("input[name='eff_date_year']").css({'background-color' : 'yellow'});
jQuery("input[name='eff_date_year']").val(issueDate.substring(0,4));
}
showEdit();
_hc_windowTimeout = setTimeout(function() {
jQuery("#_hc_window").css("display", "none");
}, 3000);
}
jQuery(window).css("display", "block");
}
jQuery(document).ready(function() {
jQuery("#_hc_window #_hc_matchSearch img").attr("src", window.pageContext + "/images/DMSLoader.gif");
jQuery("#_hc_window #_hc_closeBtn").click(function() {
jQuery("#_hc_window").hide();
});
new HealthCardHandler(_hc_newDemographicHandler);
});
| vvanherk/oscar_emr | src/main/webapp/hcHandler/hcHandlerUpdateDemographic.js | JavaScript | gpl-2.0 | 7,508 |
<?php
namespace ECP;
use ECP\Base\ItemFilterTypeQuery as BaseItemFilterTypeQuery;
/**
* Skeleton subclass for performing query and update operations on the 'itemfiltertype' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
*/
class ItemFilterTypeQuery extends BaseItemFilterTypeQuery
{
}
| Fijo/EVE-Composition-Planer | public/rest/models/ECP/ItemFilterTypeQuery.php | PHP | gpl-2.0 | 456 |
# Django settings for imageuploads project.
import os
PROJECT_DIR = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
MEDIA_ROOT = os.path.join(PROJECT_DIR, "media")
STATIC_ROOT = os.path.join(PROJECT_DIR, "static")
MEDIA_URL = "/media/"
STATIC_URL = "/static/"
# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, "site_static"),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'qomeppi59pg-(^lh7o@seb!-9d(yr@5n^=*y9w&(=!yd2p7&e^'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'imageuploads.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'imageuploads.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, "templates"),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'crispy_forms',
'ajaxuploader',
'images',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
CRISPY_TEMPLATE_PACK = 'bootstrap3'
try:
execfile(os.path.join(os.path.dirname(__file__), "local_settings.py"))
except IOError:
pass
| archatas/imageuploads | imageuploads/settings.py | Python | gpl-2.0 | 4,670 |
package org.cohorte.utilities.sql.pool;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.cohorte.utilities.sql.DBException;
import org.cohorte.utilities.sql.IDBConnection;
import org.cohorte.utilities.sql.IDBPool;
import org.cohorte.utilities.sql.exec.CDBConnectionFactory;
import org.cohorte.utilities.sql.exec.CDBConnectionInfos;
import org.psem2m.utilities.logging.CActivityLoggerNull;
import org.psem2m.utilities.logging.IActivityLogger;
/**
* @author ogattaz
*
*/
public class CDBPool implements IDBPool {
// The max unused duration of a dbconnection (default 15 minutes =
// 15*60*1000)
private static long DB_POOL_MAX_UNUSED_DURATION = 15 * 60 * 1000;
private final List<IDBConnection> pConnections = new LinkedList<IDBConnection>();
private CDBConnectionInfos pDBConnectionInfos;
private IActivityLogger pLogger;
/**
* Gestion des connexions innutilisées dans le pool de connexion de la base
* agiliumdb
*/
private final long pMaxUnusedDuration;
private final AtomicBoolean pOpened = new AtomicBoolean();
private final CDBPoolMonitor pPoolMonitor;
/**
*
*/
public CDBPool(final CDBConnectionInfos aDBConnectionInfos) {
this(null, aDBConnectionInfos);
}
/**
*
*/
public CDBPool(final IActivityLogger aLogger,
final CDBConnectionInfos aDBConnectionInfos) {
super();
setLogger(aLogger);
setDBConnectionInfos(aDBConnectionInfos);
pMaxUnusedDuration = DB_POOL_MAX_UNUSED_DURATION;
pPoolMonitor = new CDBPoolMonitor(this);
pLogger.logInfo(this, "<init>",
"MaxUnusedDuration=[%d] NbConnection=[%d]", pMaxUnusedDuration,
getNbConnection());
}
/**
* @throws Exception
*/
IDBConnection addNewDbConnection() throws DBException {
return addNewDbConnection(createDbConnection());
}
/**
* @return
* @throws ClusterStorageException
*/
private IDBConnection addNewDbConnection(final IDBConnection aConnection)
throws DBException {
if (!aConnection.isOpened()) {
boolean wOpened = aConnection.open();
pLogger.logInfo(this, "addNewDbConnection",
"NbConnection=[%d] Idx=[%d] Opened=[%b]",
getNbConnection(), aConnection.getIdx(), wOpened);
}
synchronized (pConnections) {
pConnections.add(aConnection);
}
return aConnection;
}
/*
* (non-Javadoc)
*
* @see fr.agilium.ng.commons.sql.IDBPool#checkIn(fr.agilium.ng.commons.sql.
* IDBConnection)
*/
@Override
public void checkIn(final IDBConnection aDbConn) {
// MOD_172
if (aDbConn != null) {
// if no SQLException occurs during thes usage
if (aDbConn.isValid()) {
aDbConn.setBusyOff();
} else {
aDbConn.close();
synchronized (pConnections) {
pConnections.remove(aDbConn);
}
}
}
}
/*
* (non-Javadoc)
*
* @see fr.agilium.ng.commons.sql.IDBPool#checkOut()
*/
@Override
public IDBConnection checkOut() throws IllegalStateException, Exception {
if (!isConnected()) {
throw new IllegalStateException("DBPool is not opened");
}
IDBConnection wConnection = findFirstFree();
if (wConnection == null) {
wConnection = createDbConnection();
wConnection.setBusyOn();
addNewDbConnection(wConnection);
pLogger.logInfo(this, "checkOut",
"NbConnection=[%d] NewConnectionIdx=[%d]",
getNbConnection(), wConnection.getIdx());
}
return wConnection;
}
/**
*
*/
private void close() {
pPoolMonitor.stopMonitor();
pLogger.logInfo(this, "close(): NbConnection to close=[%d]",
getNbConnection());
synchronized (pConnections) {
for (IDBConnection wConnection : pConnections) {
wConnection.close();
}
pConnections.clear();
}
}
/**
* @return
* @throws ClusterStorageException
*/
IDBConnection createDbConnection() throws DBException {
return CDBConnectionFactory
.newDbConnection(pLogger, pDBConnectionInfos);
}
/*
* (non-Javadoc)
*
* @see fr.agilium.ng.commons.sql.IDBBase#dbClose()
*/
@Override
public boolean dbClose() throws IllegalStateException {
if (!isConnected()) {
throw new IllegalStateException("DBPool is not opened");
}
close();
pOpened.set(false);
return true;
}
/*
* (non-Javadoc)
*
* @see fr.agilium.ng.commons.sql.IDBBase#dbOpen()
*/
@Override
public boolean dbOpen() throws IllegalStateException, Exception {
if (isConnected()) {
throw new IllegalStateException("DBPool is already opened");
}
try {
// add a new connection according the current DBConnectionInfos
addNewDbConnection();
pOpened.set(true);
} catch (Exception e) {
pLogger.logSevere(this, "<init>",
"Unable to create a connection to open the pool: %s", e);
}
return false;
}
@Override
public boolean dbOpen(final CDBConnectionInfos aDBConnectionInfos)
throws Exception {
if (isConnected()) {
throw new Exception("Pool is already opened");
}
setDBConnectionInfos(aDBConnectionInfos);
return dbOpen();
}
/**
*
* detect and invalidate the unused connexions since more that the max
* autorized unused duration
*
* @return the first "unbusy" db connexion found in the list
*/
private IDBConnection findFirstFree() {
synchronized (pConnections) {
for (IDBConnection wConnection : pConnections) {
// if not used and always valid
if (!wConnection.isBusy() && wConnection.isValid()) {
// if unused since too much time
if (wConnection.isUnusedTooLoong()) {
wConnection.invalidate();
} else {
wConnection.setBusyOn();
return wConnection;
}
}
}
}
return null;
}
/**
* MOD_99
*
* @return
*/
List<IDBConnection> getConnections() {
return pConnections;
}
/*
* (non-Javadoc)
*
* @see fr.agilium.ng.commons.sql.IDBBase#getDBConnection()
*/
@Override
public IDBConnection getDBConnection() throws Exception {
return checkOut();
}
/**
* @return
*/
@Override
public CDBConnectionInfos getDBConnectionInfos() {
return pDBConnectionInfos;
}
/**
* @return
*/
IActivityLogger getLogger() {
return pLogger;
}
/**
* @return
*/
public int getNbConnection() {
synchronized (pConnections) {
return pConnections.size();
}
}
/*
* (non-Javadoc)
*
* @see fr.agilium.ng.commons.sql.IDBBase#isConnected()
*/
@Override
public boolean isConnected() {
return pOpened.get();
}
/**
* @param aDBConnectionInfos
*/
private void setDBConnectionInfos(
final CDBConnectionInfos aDBConnectionInfos) {
pDBConnectionInfos = aDBConnectionInfos;
}
/**
* @param aLogger
* @return the logger
*/
public void setLogger(final IActivityLogger aLogger) {
pLogger = (aLogger != null) ? aLogger : CActivityLoggerNull
.getInstance();
}
}
| isandlaTech/cohorte-utilities | extra/org.cohorte.utilities.sql/src/org/cohorte/utilities/sql/pool/CDBPool.java | Java | gpl-2.0 | 6,719 |
<?php namespace Administracion\Tablas;
/**
* Description of ParentescosController
*
* @author Nadin Yamani
*/
class ParentescosController extends \Administracion\TablasBaseController {
} | kentronvzla/sasyc | app/controllers/administracion/tablas/ParentescosController.php | PHP | gpl-2.0 | 192 |
<?php
/**
* Plugin element to render series of checkboxes
*
* @package Joomla.Plugin
* @subpackage Fabrik.element.checkbox
* @copyright Copyright (C) 2005-2015 fabrikar.com - All rights reserved.
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
// No direct access
defined('_JEXEC') or die('Restricted access');
/**
* Plugin element to render series of checkboxes
*
* @package Joomla.Plugin
* @subpackage Fabrik.element.checkbox
* @since 3.0
*/
class PlgFabrik_ElementCheckbox extends PlgFabrik_ElementList
{
protected $inputType = 'checkbox';
/**
* Set the element id
* and maps parameter names for common ElementList options
*
* @param int $id element id
*
* @return void
*/
public function setId($id)
{
parent::setId($id);
$params = $this->getParams();
// Set elementlist params from checkbox params
$params->set('options_per_row', $params->get('ck_options_per_row'));
$params->set('allow_frontend_addto', (bool) $params->get('allow_frontend_addtocheckbox', false));
$params->set('allowadd-onlylabel', (bool) $params->get('chk-allowadd-onlylabel', true));
$params->set('savenewadditions', (bool) $params->get('chk-savenewadditions', false));
}
/**
* Shows the RAW list data - can be overwritten in plugin class
*
* @param string $data element data
* @param object $thisRow all the data in the tables current row
*
* @return string formatted value
*/
public function renderRawListData($data, $thisRow)
{
return json_encode($data);
}
/**
* Will the element allow for multiple selections
*
* @since 3.0.6
*
* @return bool
*/
protected function isMultiple()
{
return true;
}
/**
* Returns javascript which creates an instance of the class defined in formJavascriptClass()
*
* @param int $repeatCounter Repeat group counter
*
* @return array
*/
public function elementJavascript($repeatCounter)
{
$params = $this->getParams();
$id = $this->getHTMLId($repeatCounter);
$values = (array) $this->getSubOptionValues();
$labels = (array) $this->getSubOptionLabels();
$data = $this->getFormModel()->data;
$opts = $this->getElementJSOptions($repeatCounter);
$opts->value = $this->getValue($data, $repeatCounter);
$opts->defaultVal = $this->getDefaultValue($data);
$opts->data = (empty($values) && empty($labels)) ? array() : array_combine($values, $labels);
$opts->allowadd = (bool) $params->get('allow_frontend_addtocheckbox', false);
JText::script('PLG_ELEMENT_CHECKBOX_ENTER_VALUE_LABEL');
return array('FbCheckBox', $id, $opts);
}
/**
* If your element risks not to post anything in the form (e.g. check boxes with none checked)
* the this function will insert a default value into the database
*
* @param array &$data form data
*
* @return array form data
*/
public function getEmptyDataValue(&$data)
{
$params = $this->getParams();
$element = $this->getElement();
$value = FArrayHelper::getValue($data, $element->name, '');
if ($value === '')
{
$data[$element->name] = $params->get('sub_default_value');
$data[$element->name . '_raw'] = array($params->get('sub_default_value'));
}
}
/**
* If the search value isn't what is stored in the database, but rather what the user
* sees then switch from the search string to the db value here
* overwritten in things like checkbox and radio plugins
*
* @param string $value filterVal
*
* @return string
*/
protected function prepareFilterVal($value)
{
$values = $this->getSubOptionValues();
$labels = $this->getSubOptionLabels();
for ($i = 0; $i < count($labels); $i++)
{
if (JString::strtolower($labels[$i]) == JString::strtolower($value))
{
return $values[$i];
}
}
return $value;
}
/**
* If no filter condition supplied (either via querystring or in posted filter data
* return the most appropriate filter option for the element.
*
* @return string default filter condition ('=', 'REGEXP' etc.)
*/
public function getDefaultFilterCondition()
{
return '=';
}
/**
* Manipulates posted form data for insertion into database
*
* @param mixed $val this elements posted form data
* @param array $data posted form data
*
* @return mixed
*/
public function storeDatabaseFormat($val, $data)
{
if (is_array($val))
{
// Ensure that array is incremental numeric key -otherwise json_encode turns it into an object
$val = array_values($val);
}
if (is_array($val) || is_object($val))
{
return json_encode($val);
}
else
{
/*
* $$$ hugh - nastyish hack to try and make sure we consistently save as JSON,
* for instance in CSV import, if data is just a single option value like 2,
* instead of ["2"], we have been saving it as just that value, rather than a single
* item JSON array.
*/
if (isset($val))
{
// We know it's not an array or an object, so lets see if it's a string
// which doesn't contain ", [ or ]
if (!preg_match('#["\[\]]#', $val))
{
// No ", [ or ], so lets see if wrapping it up in JSON array format
// produces valid JSON
$json_val = '["' . $val . '"]';
if (FabrikWorker::isJSON($json_val))
{
// Looks like we we have a valid JSON array, so return that
return $json_val;
}
else
{
// Give up and just store whatever it was we got!
return $val;
}
}
else
{
// Contains ", [ or ], so wtf, hope it's json
return $val;
}
}
else
{
return '';
}
}
}
}
| rodhoff/cdn1 | plugins/fabrik_element/checkbox/checkbox.php | PHP | gpl-2.0 | 5,686 |
/* BEGIN_COMMON_COPYRIGHT_HEADER
*
* TOra - An Oracle Toolkit for DBA's and developers
*
* Shared/mixed copyright is held throughout files in this product
*
* Portions Copyright (C) 2000-2001 Underscore AB
* Portions Copyright (C) 2003-2005 Quest Software, Inc.
* Portions Copyright (C) 2004-2013 Numerous Other Contributors
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; only version 2 of
* the License is valid for this program.
*
* 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 as the file COPYING.txt; if not, please see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* As a special exception, you have permission to link this program
* with the Oracle Client libraries and distribute executables, as long
* as you follow the requirements of the GNU GPL in regard to all of the
* software in the executable aside from Oracle client libraries.
*
* All trademarks belong to their respective owners.
*
* END_COMMON_COPYRIGHT_HEADER */
#include "tools/tosecurity.h"
#include "ui_tosecurityuserui.h"
#include "ui_tosecurityroleui.h"
#include "core/utils.h"
#include "core/tochangeconnection.h"
#include "core/tomemoeditor.h"
#include "core/toconnectionsub.h"
#include "core/toglobalevent.h"
#include <QSplitter>
#include <QToolBar>
#include "icons/addrole.xpm"
#include "icons/adduser.xpm"
#include "icons/commit.xpm"
#include "icons/copyuser.xpm"
#include "icons/refresh.xpm"
#include "icons/sql.xpm"
#include "icons/tosecurity.xpm"
#include "icons/trash.xpm"
static toSQL SQLUserInfo("toSecurity:UserInfo",
"SELECT Account_Status,\n"
" Password,\n"
" External_Name,\n"
" Profile,\n"
" Default_Tablespace,\n"
" Temporary_Tablespace\n"
" FROM sys.DBA_Users\n"
" WHERE UserName = :f1<char[100]>",
"Get information about a user, must have same columns and same binds.");
static toSQL SQLUserInfo7("toSecurity:UserInfo",
"SELECT 'OPEN',\n"
" Password,\n"
" NULL,\n"
" Profile,\n"
" Default_Tablespace,\n"
" Temporary_Tablespace\n"
" FROM sys.DBA_Users\n"
" WHERE UserName = :f1<char[100]>",
"",
"0703");
static toSQL SQLRoleInfo("toSecurity:RoleInfo",
"SELECT Role,Password_required FROM sys.DBA_Roles WHERE Role = :f1<char[101]>",
"Get information about a role, must have same columns and same binds.");
static toSQL SQLProfiles("toSecurity:Profiles",
"SELECT DISTINCT Profile FROM sys.DBA_Profiles ORDER BY Profile",
"Get profiles available.");
static toSQL SQLTablespace("toSecurity:Tablespaces",
"SELECT DISTINCT Tablespace_Name FROM sys.DBA_Tablespaces\n"
" WHERE contents = :f1<char[30]>\n"
" ORDER BY Tablespace_Name",
"Get tablespaces available.");
static toSQL SQLRoles("toSecurity:Roles",
"SELECT Role FROM sys.Dba_Roles ORDER BY Role",
"Get roles available in DB, should return one entry");
static toSQL SQLListSystem("toSecurity:ListSystemPrivs",
"SELECT a.name\n"
" FROM system_privilege_map a,\n"
" v$enabledprivs b\n"
" WHERE b.priv_number = a.privilege\n"
" ORDER BY a.name",
"Get name of available system privileges");
static toSQL SQLQuota("toSecurity:Quota",
"SELECT Tablespace_name,\n"
" Bytes,\n"
" Max_bytes\n"
" FROM sys.DBA_TS_Quotas\n"
" WHERE Username = :f1<char[200]>\n"
" ORDER BY Tablespace_name",
"Get information about what quotas the user has, "
"must have same columns and same binds.");
static toSQL SQLSystemGrant("toSecurity:SystemGrant",
"SELECT privilege, NVL(admin_option,'NO') FROM sys.dba_sys_privs WHERE grantee = :f1<char[100]>",
"Get information about the system privileges a user has, should have same bindings and columns");
static toSQL SQLRoleGrant("toSecurity:RoleGrant",
"SELECT granted_role,\n"
" admin_option,\n"
" default_role\n"
" FROM sys.dba_role_privs\n"
" WHERE grantee = :f1<char[100]>",
"Get the roles granted to a user or role, "
"must have same columns and binds");
class toSecurityTool : public toTool
{
protected:
virtual const char **pictureXPM(void)
{
return const_cast<const char**>(tosecurity_xpm);
}
public:
toSecurityTool()
: toTool(40, "Security Manager")
{ }
virtual const char *menuItem()
{
return "Security Manager";
}
virtual toToolWidget* toolWindow(QWidget *parent, toConnection &connection)
{
return new toSecurity(parent, connection);
}
virtual void closeWindow(toConnection &connection) {};
};
static toSecurityTool SecurityTool;
void toSecurityQuota::changeSize(void)
{
if (CurrentItem)
{
if (Value->isChecked())
{
QString siz;
siz.sprintf("%.0f KB", double(Size->value()));
CurrentItem->setText(1, siz);
}
else if (None->isChecked())
{
CurrentItem->setText(1, qApp->translate("toSecurityQuota", "None"));
}
else if (Unlimited->isChecked())
{
CurrentItem->setText(1, qApp->translate("toSecurityQuota", "Unlimited"));
}
}
else
SizeGroup->setEnabled(false);
}
toSecurityQuota::toSecurityQuota(QWidget *parent)
: QWidget(parent)
{
setupUi(this);
CurrentItem = NULL;
update();
QButtonGroup *group = new QButtonGroup(SizeGroup);
group->addButton(Value, 1);
group->addButton(None, 2);
group->addButton(Unlimited, 3);
connect(Tablespaces, SIGNAL(selectionChanged()),
this, SLOT(changeTablespace()));
connect(group, SIGNAL(buttonClicked(int)),
this, SLOT(changeSize()));
connect(Size, SIGNAL(valueChanged()),
this, SLOT(changeSize()));
connect(Value, SIGNAL(toggled(bool)),
Size, SLOT(setEnabled(bool)));
}
void toSecurityQuota::update(void)
{
Tablespaces->clear();
try
{
toConnectionSubLoan conn(toConnection::currentConnection(this));
toQuery tablespaces(conn, SQLTablespace, toQueryParams() << QString::fromLatin1("PERMANENT"));
toTreeWidgetItem *item = NULL;
while (!tablespaces.eof())
{
item = new toResultViewItem(Tablespaces, item, (QString)tablespaces.readValue());
item->setText(1, qApp->translate("toSecurityQuota", "None"));
item->setText(3, qApp->translate("toSecurityQuota", "None"));
}
}
TOCATCH
}
void toSecurityQuota::clearItem(toTreeWidgetItem *item)
{
item->setText(1, qApp->translate("toSecurityQuota", "None"));
item->setText(2, QString::null);
item->setText(3, qApp->translate("toSecurityQuota", "None"));
}
void toSecurityQuota::clear(void)
{
for (toTreeWidgetItem *item = Tablespaces->firstChild(); item; item = item->nextSibling())
item->setText(3, qApp->translate("toSecurityQuota", "None"));
}
void toSecurityQuota::changeUser(const QString &user)
{
Tablespaces->show();
SizeGroup->show();
Disabled->hide(); // Do we really have to bother about this?
Tablespaces->clearSelection();
toTreeWidgetItem *item = Tablespaces->firstChild();
if (!user.isEmpty())
{
try
{
toConnectionSubLoan conn(toConnection::currentConnection(this));
toQuery quota(conn, SQLQuota, toQueryParams() << user);
while (!quota.eof())
{
double maxQuota;
double usedQuota;
QString tbl(quota.readValue());
while (item && item->text(0) != tbl)
{
clearItem(item);
item = item->nextSibling();
}
usedQuota = quota.readValue().toDouble();
maxQuota = quota.readValue().toDouble();
if (item)
{
QString usedStr;
QString maxStr;
usedStr.sprintf("%.0f KB", usedQuota / 1024);
if (maxQuota < 0)
maxStr = qApp->translate("toSecurityQuota", "Unlimited");
else if (maxQuota == 0)
maxStr = qApp->translate("toSecurityQuota", "None");
else
{
maxStr.sprintf("%.0f KB", maxQuota / 1024);
}
item->setText(1, maxStr);
item->setText(2, usedStr);
item->setText(3, maxStr);
item = item->nextSibling();
}
}
}
TOCATCH
}
while (item)
{
clearItem(item);
item = item->nextSibling();
}
SizeGroup->setEnabled(false);
CurrentItem = NULL;
}
void toSecurityQuota::changeTablespace(void)
{
CurrentItem = Tablespaces->selectedItem();
if (CurrentItem)
{
QString siz = CurrentItem->text(1);
if (siz == qApp->translate("toSecurityQuota", "None"))
None->setChecked(true);
else if (siz == qApp->translate("toSecurityQuota", "Unlimited"))
Unlimited->setChecked(true);
else
{
Value->setChecked(true);
Size->setValue(siz.toInt());
}
}
SizeGroup->setEnabled(true);
}
QString toSecurityQuota::sql(void)
{
QString ret;
for (toTreeWidgetItem *item = Tablespaces->firstChild(); item; item = item->nextSibling())
{
if (item->text(1) != item->text(3))
{
QString siz = item->text(1);
if (siz.right(2) == QString::fromLatin1("KB"))
siz.truncate(siz.length() - 1);
else if (siz == qApp->translate("toSecurityQuota", "None"))
siz = QString::fromLatin1("0 K");
else if (siz == qApp->translate("toSecurityQuota", "Unlimited"))
siz = QString::fromLatin1("UNLIMITED");
ret += QString::fromLatin1(" QUOTA ");
ret += siz;
ret += QString::fromLatin1(" ON ");
ret += item->text(0);
}
}
return ret;
}
class toSecurityUpper : public QValidator
{
public:
toSecurityUpper(QWidget *parent)
: QValidator(parent)
{ }
virtual State validate(QString &str, int &) const
{
str = str.toUpper();
return Acceptable;
}
};
class toSecurityUser : public QWidget, public Ui::toSecurityUserUI
{
toConnection &Connection;
toSecurityQuota *Quota;
enum
{
password,
global,
external
} AuthType;
QString OrgProfile;
QString OrgDefault;
QString OrgTemp;
QString OrgGlobal;
QString OrgPassword;
bool OrgLocked;
bool OrgExpired;
public:
toSecurityUser(toSecurityQuota *quota, toConnection &conn, QWidget *parent);
void clear(bool all = true);
void update();
void changeUser(const QString &);
QString name(void)
{
return Name->text();
}
QString sql(void);
};
QString toSecurityUser::sql(void)
{
QString extra;
if (Authentication->currentWidget() == PasswordTab)
{
if (Password->text() != Password2->text())
{
switch (TOMessageBox::warning(this,
qApp->translate("toSecurityUser", "Passwords don't match"),
qApp->translate("toSecurityUser", "The two versions of the password doesn't match"),
qApp->translate("toSecurityUser", "Don't save"),
qApp->translate("toSecurityUser", "Cancel")))
{
case 0:
return QString::null;
case 1:
throw qApp->translate("toSecurityUser", "Passwords don't match");
}
}
if (Password->text() != OrgPassword)
{
extra = QString::fromLatin1(" IDENTIFIED BY \"");
extra += Password->text();
extra += QString::fromLatin1("\"");
}
if (OrgExpired != ExpirePassword->isChecked())
{
if (ExpirePassword->isChecked())
extra += QString::fromLatin1(" PASSWORD EXPIRE");
}
}
else if (Authentication->currentWidget() == GlobalTab)
{
if (OrgGlobal != GlobalName->text())
{
extra = QString::fromLatin1(" IDENTIFIED GLOBALLY AS '");
extra += GlobalName->text();
extra += QString::fromLatin1("'");
}
}
else if ((AuthType != external) && (Authentication->currentWidget() == ExternalTab))
extra = QString::fromLatin1(" IDENTIFIED EXTERNALLY");
if (OrgProfile != Profile->currentText())
{
extra += QString::fromLatin1(" PROFILE \"");
extra += Profile->currentText();
extra += QString::fromLatin1("\"");
}
if (OrgDefault != DefaultSpace->currentText())
{
extra += QString::fromLatin1(" DEFAULT TABLESPACE \"");
extra += DefaultSpace->currentText();
extra += QString::fromLatin1("\"");
}
if (OrgTemp != TempSpace->currentText())
{
extra += QString::fromLatin1(" TEMPORARY TABLESPACE \"");
extra += TempSpace->currentText();
extra += QString::fromLatin1("\"");
}
if (OrgLocked != Locked->isChecked())
{
extra += QString::fromLatin1(" ACCOUNT ");
if (Locked->isChecked())
extra += QString::fromLatin1("LOCK");
else
extra += QString::fromLatin1("UNLOCK");
}
extra += Quota->sql();
QString sql;
if (Name->isEnabled())
{
if (Name->text().isEmpty())
return QString::null;
sql = QString::fromLatin1("CREATE ");
}
else
{
if (extra.isEmpty())
return QString::null;
sql = QString::fromLatin1("ALTER ");
}
sql += QString::fromLatin1("USER \"");
sql += Name->text();
sql += QString::fromLatin1("\"");
sql += extra;
return sql;
}
toSecurityUser::toSecurityUser(toSecurityQuota *quota, toConnection &conn, QWidget *parent)
: QWidget(parent), Connection(conn), Quota(quota)
{
setupUi(this);
Name->setValidator(new toSecurityUpper(Name));
setFocusProxy(Name);
update();
}
void toSecurityUser::update()
{
try
{
toConnectionSubLoan conn(Connection);
toQuery profiles(conn, SQLProfiles, toQueryParams());
while (!profiles.eof())
Profile->addItem((QString)profiles.readValue());
QString buf;
toQuery tablespaces(conn, SQLTablespace, toQueryParams() << QString::fromLatin1("PERMANENT"));
DefaultSpace->clear();
while (!tablespaces.eof())
{
buf = (QString)tablespaces.readValue();
DefaultSpace->addItem(buf);
}
toQuery temp(conn, SQLTablespace, toQueryParams() << QString::fromLatin1("TEMPORARY"));
TempSpace->clear();
while (!temp.eof())
{
buf = (QString)temp.readValue();
TempSpace->addItem(buf);
}
}
TOCATCH
}
void toSecurityUser::clear(bool all)
{
Name->setText(QString::null);
Password->setText(QString::null);
Password2->setText(QString::null);
GlobalName->setText(QString::null);
if (all)
{
Profile->setCurrentIndex(0);
Authentication->setCurrentIndex(Authentication->indexOf(PasswordTab));
ExpirePassword->setChecked(false);
ExpirePassword->setEnabled(true);
TempSpace->setCurrentIndex(0);
DefaultSpace->setCurrentIndex(0);
Locked->setChecked(false);
}
OrgProfile = OrgDefault = OrgTemp = OrgGlobal = QString::null;
AuthType = password;
Name->setEnabled(true);
OrgLocked = OrgExpired = false;
}
void toSecurityUser::changeUser(const QString &user)
{
clear();
try
{
toConnectionSubLoan conn(Connection);
toQuery query(conn, SQLUserInfo, toQueryParams() << user);
if (!query.eof())
{
Name->setEnabled(false);
Name->setText(user);
QString str(query.readValue());
if (str.contains(QString::fromLatin1("EXPIRED")))
{
ExpirePassword->setChecked(true);
ExpirePassword->setEnabled(false);
OrgExpired = true;
}
if (str.contains(QString::fromLatin1("LOCKED")))
{
Locked->setChecked(true);
OrgLocked = true;
}
OrgPassword = (QString)query.readValue();
QString pass = (QString)query.readValue();
if (OrgPassword == QString::fromLatin1("GLOBAL"))
{
OrgPassword = QString::null;
Authentication->setCurrentIndex(Authentication->indexOf(GlobalTab));
OrgGlobal = pass;
GlobalName->setText(OrgGlobal);
AuthType = global;
}
else if (OrgPassword == QString::fromLatin1("EXTERNAL"))
{
OrgPassword = QString::null;
Authentication->setCurrentIndex(Authentication->indexOf(ExternalTab));
AuthType = external;
}
else
{
Password->setText(OrgPassword);
Password2->setText(OrgPassword);
AuthType = password;
}
{
str = (QString)query.readValue();
for (int i = 0; i < Profile->count(); i++)
{
if (Profile->itemText(i) == str)
{
Profile->setCurrentIndex(i);
OrgProfile = str;
break;
}
}
}
{
str = (QString)query.readValue();
for (int i = 0; i < DefaultSpace->count(); i++)
{
if (DefaultSpace->itemText(i) == str)
{
DefaultSpace->setCurrentIndex(i);
OrgDefault = str;
break;
}
}
}
{
str = (QString)query.readValue();
for (int i = 0; i < TempSpace->count(); i++)
{
if (TempSpace->itemText(i) == str)
{
TempSpace->setCurrentIndex(i);
OrgTemp = str;
break;
}
}
}
}
}
TOCATCH
}
class toSecurityRole : public QWidget, public Ui::toSecurityRoleUI
{
toConnection &Connection;
toSecurityQuota *Quota;
enum
{
password,
global,
external,
none
} AuthType;
public:
toSecurityRole(toSecurityQuota *quota, toConnection &conn, QWidget *parent)
: QWidget(parent), Connection(conn)
, Quota(quota)
, AuthType(password)
{
setupUi(this);
Name->setValidator(new toSecurityUpper(Name));
setFocusProxy(Name);
}
void clear(void);
void changeRole(const QString &);
QString sql(void);
QString name(void)
{
return Name->text();
}
};
QString toSecurityRole::sql(void)
{
QString extra;
if (Authentication->currentWidget() == PasswordTab)
{
if (Password->text() != Password2->text())
{
switch (TOMessageBox::warning(this,
qApp->translate("toSecurityRole", "Passwords don't match"),
qApp->translate("toSecurityRole", "The two versions of the password doesn't match"),
qApp->translate("toSecurityRole", "Don't save"),
qApp->translate("toSecurityRole", "Cancel")))
{
case 0:
return QString::null;
case 1:
throw qApp->translate("toSecurityRole", "Passwords don't match");
}
}
if (Password->text().length() > 0)
{
extra = QString::fromLatin1(" IDENTIFIED BY \"");
extra += Password->text();
extra += QString::fromLatin1("\"");
}
}
else if ((AuthType != global) && (Authentication->currentWidget() == GlobalTab))
extra = QString::fromLatin1(" IDENTIFIED GLOBALLY");
else if ((AuthType != external) && (Authentication->currentWidget() == ExternalTab))
extra = QString::fromLatin1(" IDENTIFIED EXTERNALLY");
else if ((AuthType != none) && (Authentication->currentWidget() == NoneTab))
extra = QString::fromLatin1(" NOT IDENTIFIED");
extra += Quota->sql();
QString sql;
if (Name->isEnabled())
{
if (Name->text().isEmpty())
return QString::null;
sql = QString::fromLatin1("CREATE ");
}
else
{
if (extra.isEmpty())
return QString::null;
sql = QString::fromLatin1("ALTER ");
}
sql += QString::fromLatin1("ROLE \"");
sql += Name->text();
sql += QString::fromLatin1("\"");
sql += extra;
return sql;
}
void toSecurityRole::clear(void)
{
Name->setText(QString::null);
Name->setEnabled(true);
}
void toSecurityRole::changeRole(const QString &role)
{
try
{
toConnectionSubLoan conn(Connection);
toQuery query(conn, SQLRoleInfo, toQueryParams() << role);
Password->setText(QString::null);
Password2->setText(QString::null);
if (!query.eof())
{
Name->setText(role);
Name->setEnabled(false);
QString str(query.readValue());
if (str == QString::fromLatin1("YES"))
{
AuthType = password;
Authentication->setCurrentIndex(Authentication->indexOf(PasswordTab));
}
else if (str == QString::fromLatin1("GLOBAL"))
{
AuthType = global;
Authentication->setCurrentIndex(Authentication->indexOf(GlobalTab));
}
else if (str == QString::fromLatin1("EXTERNAL"))
{
AuthType = external;
Authentication->setCurrentIndex(Authentication->indexOf(ExternalTab));
}
else
{
AuthType = none;
Authentication->setCurrentIndex(Authentication->indexOf(NoneTab));
}
}
else
{
Name->setText(QString::null);
Name->setEnabled(true);
AuthType = none;
Authentication->setCurrentIndex(Authentication->indexOf(NoneTab));
}
}
TOCATCH
}
class toSecurityPage : public QWidget
{
toSecurityRole *Role;
toSecurityUser *User;
public:
toSecurityPage(toSecurityQuota *quota, toConnection &conn, QWidget *parent)
: QWidget(parent)
{
QVBoxLayout *vbox = new QVBoxLayout;
vbox->setSpacing(0);
vbox->setContentsMargins(0, 0, 0, 0);
setLayout(vbox);
Role = new toSecurityRole(quota, conn, this);
vbox->addWidget(Role);
Role->hide();
User = new toSecurityUser(quota, conn, this);
vbox->addWidget(User);
setFocusProxy(User);
}
void changePage(const QString &nam, bool user)
{
if (user)
{
Role->hide();
User->show();
User->changeUser(nam);
setFocusProxy(User);
}
else
{
User->hide();
Role->show();
Role->changeRole(nam);
setFocusProxy(Role);
}
}
QString name(void)
{
if (User->isHidden())
return Role->name();
else
return User->name();
}
void clear(void)
{
if (User->isHidden())
Role->clear();
else
User->clear(false);
}
bool user(void)
{
if (User->isHidden())
return false;
return true;
}
QString sql(void)
{
if (User->isHidden())
return Role->sql();
else
return User->sql();
}
void update()
{
User->update();
Role->update();
}
};
toSecurityObject::toSecurityObject(QWidget *parent)
: QTreeView(parent)
{
setObjectName("toSecurityObject");
m_model = new toSecurityTreeModel(this);
setModel(m_model);
// update();
}
void toSecurityObject::update(void)
{
m_model->setupModelData(toConnection::currentConnection(this).user());
}
void toSecurityObject::eraseUser(bool all)
{
m_model->setupModelData(toConnection::currentConnection(this).user());
}
void toSecurityObject::changeUser(const QString &user)
{
m_model->setupModelData(user);
}
void toSecurityObject::sql(const QString &user, std::list<QString> &sqlLst)
{
m_model->sql(user, sqlLst);
}
toSecuritySystem::toSecuritySystem(QWidget *parent)
: toListView(parent)
{
addColumn(tr("Privilege name"));
setRootIsDecorated(true);
update();
setSorting(0);
connect(this, SIGNAL(clicked(toTreeWidgetItem *)), this, SLOT(changed(toTreeWidgetItem *)));
}
void toSecuritySystem::update(void)
{
clear();
try
{
toConnectionSubLoan conn(toConnection::currentConnection(this));
toQuery priv(conn, SQLListSystem, toQueryParams());
while (!priv.eof())
{
toResultViewCheck *item = new toResultViewCheck(this, (QString)priv.readValue(),
toTreeWidgetCheck::CheckBox);
new toResultViewCheck(item, tr("Admin"), toTreeWidgetCheck::CheckBox);
}
}
TOCATCH
}
void toSecuritySystem::sql(const QString &user, std::list<QString> &sqlLst)
{
for (toTreeWidgetItem *item = firstChild(); item; item = item->nextSibling())
{
QString sql;
toResultViewCheck *check = dynamic_cast<toResultViewCheck *>(item);
toResultViewCheck *chld = dynamic_cast<toResultViewCheck *>(item->firstChild());
if (chld && chld->isOn() && chld->text(1).isEmpty())
{
sql = QString::fromLatin1("GRANT ");
sql += item->text(0);
sql += QString::fromLatin1(" TO \"");
sql += user;
sql += QString::fromLatin1("\" WITH ADMIN OPTION");
sqlLst.insert(sqlLst.end(), sql);
}
else if (check->isOn() && !item->text(1).isEmpty())
{
if (chld && !chld->isOn() && !chld->text(1).isEmpty())
{
sql = QString::fromLatin1("REVOKE ");
sql += item->text(0);
sql += QString::fromLatin1(" FROM \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
sql = QString::fromLatin1("GRANT ");
sql += item->text(0);
sql += QString::fromLatin1(" TO \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
}
}
else if (check->isOn() && item->text(1).isEmpty())
{
sql = QString::fromLatin1("GRANT ");
sql += item->text(0);
sql += QString::fromLatin1(" TO \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
}
else if (!check->isOn() && !item->text(1).isEmpty())
{
sql = QString::fromLatin1("REVOKE ");
sql += item->text(0);
sql += QString::fromLatin1(" FROM \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
}
}
}
void toSecuritySystem::changed(toTreeWidgetItem *org)
{
toResultViewCheck *item = dynamic_cast<toResultViewCheck *>(org);
if (item)
{
if (item->isOn())
{
item = dynamic_cast<toResultViewCheck *>(item->parent());
if (item)
item->setOn(true);
}
else
{
item = dynamic_cast<toResultViewCheck *>(item->firstChild());
if (item)
item->setOn(false);
}
}
}
void toSecuritySystem::eraseUser(bool all)
{
for (toTreeWidgetItem *item = firstChild(); item; item = item->nextSibling())
{
toResultViewCheck * chk = dynamic_cast<toResultViewCheck *>(item);
if (chk && all)
chk->setOn(false);
item->setText(1, QString::null);
for (toTreeWidgetItem *chld = item->firstChild(); chld; chld = chld->nextSibling())
{
chld->setText(1, QString::null);
toResultViewCheck *chk = dynamic_cast<toResultViewCheck *>(chld);
if (chk && all)
chk->setOn(false);
}
}
}
void toSecuritySystem::changeUser(const QString &user)
{
eraseUser();
try
{
toConnectionSubLoan conn(toConnection::currentConnection(this));
toQuery query(conn, SQLSystemGrant, toQueryParams() << user);
while (!query.eof())
{
QString str = (QString)query.readValue();
QString admin = (QString)query.readValue();
for (toTreeWidgetItem *item = firstChild(); item; item = item->nextSibling())
{
if (item->text(0) == str)
{
toResultViewCheck * chk = dynamic_cast<toResultViewCheck *>(item);
if (chk)
chk->setOn(true);
item->setText(1, tr("ON"));
if (admin != tr("NO") && item->firstChild())
{
chk = dynamic_cast<toResultViewCheck *>(item->firstChild());
if (chk)
chk->setOn(true);
if (chk->parent())
chk->parent()->setOpen(true);
item->firstChild()->setText(1, tr("ON"));
}
break;
}
}
}
}
TOCATCH
}
toSecurityRoleGrant::toSecurityRoleGrant(QWidget *parent)
: toListView(parent)
{
addColumn(tr("Role name"));
setRootIsDecorated(true);
update();
setSorting(0);
connect(this, SIGNAL(clicked(toTreeWidgetItem *)), this, SLOT(changed(toTreeWidgetItem *)));
}
void toSecurityRoleGrant::update(void)
{
clear();
try
{
toConnectionSubLoan conn(toConnection::currentConnection(this));
toQuery priv(conn, SQLRoles, toQueryParams());
while (!priv.eof())
{
toResultViewCheck *item = new toResultViewCheck(this, (QString)priv.readValue(), toTreeWidgetCheck::CheckBox);
new toResultViewCheck(item, tr("Admin"), toTreeWidgetCheck::CheckBox);
new toResultViewCheck(item, tr("Default"), toTreeWidgetCheck::CheckBox);
}
}
TOCATCH
}
toTreeWidgetCheck *toSecurityRoleGrant::findChild(toTreeWidgetItem *parent, const QString &name)
{
for (toTreeWidgetItem *item = parent->firstChild(); item; item = item->nextSibling())
{
if (item->text(0) == name)
{
toResultViewCheck * ret = dynamic_cast<toResultViewCheck *>(item);
if (ret->isEnabled())
return ret;
else
return NULL;
}
}
return NULL;
}
void toSecurityRoleGrant::sql(const QString &user, std::list<QString> &sqlLst)
{
bool any = false;
bool chg = false;
QString except;
QString sql;
for (toTreeWidgetItem *item = firstChild(); item; item = item->nextSibling())
{
toResultViewCheck * check = dynamic_cast<toResultViewCheck *>(item);
toTreeWidgetCheck *chld = findChild(item, tr("Admin"));
toTreeWidgetCheck *def = findChild(item, tr("Default"));
if (def && check)
{
if (!def->isOn() && check->isOn())
{
if (!except.isEmpty())
except += QString::fromLatin1(",\"");
else
except += QString::fromLatin1(" EXCEPT \"");
except += item->text(0);
except += QString::fromLatin1("\"");
}
else if (check->isOn() && def->isOn())
any = true;
if (def->isOn() == def->text(1).isEmpty())
chg = true;
}
if (chld && chld->isOn() && chld->text(1).isEmpty())
{
if (check->isOn() && !item->text(1).isEmpty())
{
sql = QString::fromLatin1("REVOKE \"");
sql += item->text(0);
sql += QString::fromLatin1("\" FROM \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
}
sql = QString::fromLatin1("GRANT \"");
sql += item->text(0);
sql += QString::fromLatin1("\" TO \"");
sql += user;
sql += QString::fromLatin1("\" WITH ADMIN OPTION");
sqlLst.insert(sqlLst.end(), sql);
chg = true;
}
else if (check->isOn() && !item->text(1).isEmpty())
{
if (chld && !chld->isOn() && !chld->text(1).isEmpty())
{
sql = QString::fromLatin1("REVOKE \"");
sql += item->text(0);
sql += QString::fromLatin1("\" FROM \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
sql = QString::fromLatin1("GRANT \"");
sql += item->text(0);
sql += QString::fromLatin1("\" TO \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
chg = true;
}
}
else if (check->isOn() && item->text(1).isEmpty())
{
sql = QString::fromLatin1("GRANT \"");
sql += item->text(0);
sql += QString::fromLatin1("\" TO \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
chg = true;
}
else if (!check->isOn() && !item->text(1).isEmpty())
{
sql = QString::fromLatin1("REVOKE \"");
sql += item->text(0);
sql += QString::fromLatin1("\" FROM \"");
sql += user;
sql += QString::fromLatin1("\"");
sqlLst.insert(sqlLst.end(), sql);
chg = true;
}
}
if (chg)
{
sql = QString::fromLatin1("ALTER USER \"");
sql += user;
sql += QString::fromLatin1("\" DEFAULT ROLE ");
if (any)
{
sql += QString::fromLatin1("ALL");
sql += except;
}
else
sql += QString::fromLatin1("NONE");
sqlLst.insert(sqlLst.end(), sql);
}
}
void toSecurityRoleGrant::changed(toTreeWidgetItem *org)
{
toResultViewCheck *item = dynamic_cast<toResultViewCheck *>(org);
if (item)
{
if (item->isOn())
{
toTreeWidgetCheck *chld = findChild(item, tr("Default"));
if (chld)
chld->setOn(true);
item = dynamic_cast<toResultViewCheck *>(item->parent());
if (item)
item->setOn(true);
}
else
{
for (toTreeWidgetItem *item = firstChild(); item; item = item->nextSibling())
{
toResultViewCheck * chk = dynamic_cast<toResultViewCheck *>(item->firstChild());
if (chk)
chk->setOn(false);
}
}
}
}
void toSecurityRoleGrant::eraseUser(bool user, bool all)
{
for (toTreeWidgetItem *item = firstChild(); item; item = item->nextSibling())
{
toResultViewCheck * chk = dynamic_cast<toResultViewCheck *>(item);
if (chk && all)
chk->setOn(false);
item->setText(1, QString::null);
for (toTreeWidgetItem *chld = item->firstChild(); chld; chld = chld->nextSibling())
{
chld->setText(1, QString::null);
toResultViewCheck *chk = dynamic_cast<toResultViewCheck *>(chld);
if (chk)
{
if (all)
{
chk->setOn(false);
if (chk->text(0) == tr("Default"))
chk->setEnabled(user);
}
}
}
}
}
void toSecurityRoleGrant::changeUser(bool user, const QString &username)
{
eraseUser(user);
try
{
toConnectionSubLoan conn(toConnection::currentConnection(this));
toQuery query(conn, SQLRoleGrant, toQueryParams() << username);
while (!query.eof())
{
QString str = (QString)query.readValue();
QString admin = (QString)query.readValue();
QString def = (QString)query.readValue();
for (toTreeWidgetItem *item = firstChild(); item; item = item->nextSibling())
{
if (item->text(0) == str)
{
toTreeWidgetCheck * chk = dynamic_cast<toResultViewCheck *>(item);
if (chk)
chk->setOn(true);
item->setText(1, tr("ON"));
chk = findChild(item, tr("Admin"));
if (admin == tr("YES") && chk)
{
chk->setOn(true);
chk->setText(1, tr("ON"));
if (chk->parent())
chk->parent()->setOpen(true);
}
chk = findChild(item, tr("Default"));
if (def == tr("YES") && chk)
{
chk->setOn(true);
chk->setText(1, tr("ON"));
if (chk->parent())
chk->parent()->setOpen(true);
}
break;
}
}
}
}
TOCATCH
}
toSecurity::toSecurity(QWidget *main, toConnection &connection)
: toToolWidget(SecurityTool, "security.html", main, connection, "toSecurity")
{
Utils::toBusy busy;
QToolBar *toolbar = Utils::toAllocBar(this, tr("Security manager"));
toolbar->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
layout()->addWidget(toolbar);
UpdateListAct = new QAction(QPixmap(const_cast<const char**>(refresh_xpm)),
tr("Update user and role list"), this);
connect(UpdateListAct, SIGNAL(triggered()), this, SLOT(refresh(void)));
UpdateListAct->setShortcut(QKeySequence::Refresh);
toolbar->addAction(UpdateListAct);
toolbar->addSeparator();
SaveAct = new QAction(QPixmap(const_cast<const char**>(commit_xpm)),
tr("Save changes"), this);
connect(SaveAct, SIGNAL(triggered()), this, SLOT(saveChanges(void)));
SaveAct->setShortcut(Qt::CTRL | Qt::Key_Return);
toolbar->addAction(SaveAct);
DropAct = new QAction(QPixmap(const_cast<const char**>(trash_xpm)),
tr("Remove user/role"), this);
connect(DropAct, SIGNAL(triggered()), this, SLOT(drop(void)));
toolbar->addAction(DropAct);
DropAct->setEnabled(false);
toolbar->addSeparator();
AddUserAct = new QAction(QPixmap(const_cast<const char**>(adduser_xpm)),
tr("Add new user"), this);
connect(AddUserAct, SIGNAL(triggered()), this, SLOT(addUser(void)));
AddUserAct->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_U);
toolbar->addAction(AddUserAct);
AddRoleAct = new QAction(QPixmap(const_cast<const char**>(addrole_xpm)),
tr("Add new role"), this);
connect(AddRoleAct, SIGNAL(triggered()), this, SLOT(addRole(void)));
AddRoleAct->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_R);
toolbar->addAction(AddRoleAct);
CopyAct = new QAction(QPixmap(const_cast<const char**>(copyuser_xpm)),
tr("Copy current user or role"), this);
connect(CopyAct, SIGNAL(triggered()), this, SLOT(copy(void)));
CopyAct->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_O);
toolbar->addAction(CopyAct);
CopyAct->setEnabled(false);
toolbar->addSeparator();
DisplaySQLAct = new QAction(QPixmap(const_cast<const char**>(sql_xpm)),
tr("Display SQL needed to make current changes"), this);
connect(DisplaySQLAct, SIGNAL(triggered()), this, SLOT(displaySQL(void)));
DisplaySQLAct->setShortcut(Qt::Key_F4);
toolbar->addAction(DisplaySQLAct);
toolbar->addWidget(new Utils::toSpacer());
new toChangeConnection(toolbar);
QSplitter *splitter = new QSplitter(Qt::Horizontal, this);
layout()->addWidget(splitter);
UserList = new toListView(splitter);
UserList->addColumn(tr("Users/Roles"));
UserList->setSQLName(QString::fromLatin1("toSecurity:Users/Roles"));
UserList->setRootIsDecorated(true);
UserList->setSelectionMode(toTreeWidget::Single);
Tabs = new QTabWidget(splitter);
Quota = new toSecurityQuota(Tabs);
General = new toSecurityPage(Quota, connection, Tabs);
Tabs->addTab(General, tr("&General"));
RoleGrant = new toSecurityRoleGrant(Tabs);
Tabs->addTab(RoleGrant, tr("&Roles"));
SystemGrant = new toSecuritySystem(Tabs);
Tabs->addTab(SystemGrant, tr("&System Privileges"));
ObjectGrant = new toSecurityObject(Tabs);
Tabs->addTab(ObjectGrant, tr("&Object Privileges"));
Tabs->addTab(Quota, tr("&Quota"));
UserList->setSelectionMode(toTreeWidget::Single);
connect(UserList, SIGNAL(selectionChanged(toTreeWidgetItem *)),
this, SLOT(changeUser(toTreeWidgetItem *)));
ToolMenu = NULL;
// connect(toMainWidget()->workspace(), SIGNAL(subWindowActivated(QMdiSubWindow *)),
// this, SLOT(windowActivated(QMdiSubWindow *)));
refresh();
connect(this, SIGNAL(connectionChange()),
this, SLOT(refresh()));
setFocusProxy(Tabs);
}
void toSecurity::slotWindowActivated(toToolWidget *widget)
{
if (!widget)
return;
if (widget == this)
{
if (!ToolMenu)
{
ToolMenu = new QMenu(tr("&Security"), this);
ToolMenu->addAction(UpdateListAct);
ToolMenu->addSeparator();
ToolMenu->addAction(SaveAct);
ToolMenu->addAction(DropAct);
ToolMenu->addSeparator();
ToolMenu->addAction(AddUserAct);
ToolMenu->addAction(AddRoleAct);
ToolMenu->addAction(CopyAct);
ToolMenu->addSeparator();
ToolMenu->addAction(DisplaySQLAct);
toGlobalEventSingle::Instance().addCustomMenu(ToolMenu);
}
}
else
{
delete ToolMenu;
ToolMenu = NULL;
}
}
void toSecurity::displaySQL(void)
{
std::list<QString> lines = sql();
QString res;
for (std::list<QString>::iterator i = lines.begin(); i != lines.end(); i++)
{
res += *i;
res += QString::fromLatin1(";\n");
}
if (res.length() > 0)
new toMemoEditor(this, res, -1, -1, true);
else
Utils::toStatusMessage(tr("No changes made"));
}
std::list<QString> toSecurity::sql(void)
{
std::list<QString> ret;
try
{
QString tmp = General->sql();
if (!tmp.isEmpty())
ret.insert(ret.end(), tmp);
QString name = General->name();
if (!name.isEmpty())
{
SystemGrant->sql(name, ret);
ObjectGrant->sql(name, ret);
RoleGrant->sql(name, ret);
}
}
catch (const QString &str)
{
Utils::toStatusMessage(str);
std::list<QString> empty;
return empty;
}
return ret;
}
void toSecurity::changeUser(bool ask)
{
if (ask)
{
try
{
std::list<QString> sqlList = sql();
if (sqlList.size() != 0)
{
switch (TOMessageBox::warning(this,
tr("Save changes?"),
tr("Save the changes made to this user?"),
tr("Save"), tr("Discard"), tr("Cancel")))
{
case 0:
saveChanges();
return ;
case 1:
break;
case 2:
return ;
}
}
}
catch (const QString &str)
{
Utils::toStatusMessage(str);
return ;
}
}
try
{
QString sel;
toTreeWidgetItem *item = UserList->selectedItem();
if (item)
{
Utils::toBusy busy;
UserID = item->text(1);
DropAct->setEnabled(item->parent());
CopyAct->setEnabled(item->parent());
if (UserID[4].toLatin1() != ':')
throw tr("Invalid security ID");
bool user = false;
if (UserID.startsWith(QString::fromLatin1("USER")))
user = true;
QString username = UserID.right(UserID.length() - 5);
General->changePage(username, user);
Quota->changeUser(username);
Tabs->setTabEnabled(Tabs->indexOf(Quota), user);
RoleGrant->changeUser(user, username);
SystemGrant->changeUser(username);
ObjectGrant->changeUser(username);
}
}
TOCATCH
}
void toSecurity::refresh(void)
{
Utils::toBusy busy;
disconnect(UserList, SIGNAL(selectionChanged(toTreeWidgetItem *)),
this, SLOT(changeUser(toTreeWidgetItem *)));
SystemGrant->update();
RoleGrant->update();
ObjectGrant->update();
Quota->update();
General->update();
UserList->clear();
try
{
toTreeWidgetItem *parent = new toResultViewItem(UserList, NULL, QString::fromLatin1("Users"));
parent->setText(1, QString::fromLatin1("USER:"));
parent->setOpen(true);
toConnectionSubLoan conn(connection());
toQuery user(conn, toSQL::string(toSQL::TOSQL_USERLIST, connection()), toQueryParams());
toTreeWidgetItem *item = NULL;
while (!user.eof())
{
QString tmp = (QString)user.readValue();
QString id = QString::fromLatin1("USER:");
id += tmp;
item = new toResultViewItem(parent, item, tmp);
item->setText(1, id);
if (id == UserID)
UserList->setSelected(item, true);
}
parent = new toResultViewItem(UserList, parent, tr("Roles"));
parent->setText(1, QString::fromLatin1("ROLE:"));
parent->setOpen(true);
toQuery roles(conn, SQLRoles, toQueryParams());
item = NULL;
while (!roles.eof())
{
QString tmp = (QString)roles.readValue();
QString id = QString::fromLatin1("ROLE:");
id += tmp;
item = new toResultViewItem(parent, item, tmp);
item->setText(1, id);
if (id == UserID)
UserList->setSelected(item, true);
}
}
TOCATCH
connect(UserList, SIGNAL(selectionChanged(toTreeWidgetItem *)),
this, SLOT(changeUser(toTreeWidgetItem *)));
}
void toSecurity::saveChanges()
{
std::list<QString> sqlList = sql();
toConnectionSubLoan conn(connection());
for (std::list<QString>::iterator i = sqlList.begin(); i != sqlList.end(); i++)
{
try
{
conn->execute(*i);
}
TOCATCH
}
if (General->user())
UserID = QString::fromLatin1("USER:");
else
UserID = QString::fromLatin1("ROLE:");
UserID += General->name();
refresh();
changeUser(false);
}
void toSecurity::drop()
{
if (UserID.length() > 5)
{
QString str = QString::fromLatin1("DROP ");
if (General->user())
str += QString::fromLatin1("USER");
else
str += QString::fromLatin1("ROLE");
str += QString::fromLatin1(" \"");
str += UserID.right(UserID.length() - 5);
str += QString::fromLatin1("\"");
try
{
toConnectionSubLoan conn(connection());
conn->execute(str);
refresh();
changeUser(false);
}
catch (...)
{
switch (TOMessageBox::warning(this,
tr("Are you sure?"),
tr("The user still owns objects, add the cascade option?"),
tr("Yes"), tr("No")))
{
case 0:
str += QString::fromLatin1(" CASCADE");
try
{
toConnectionSubLoan conn(connection());
conn->execute(str);
refresh();
changeUser(false);
}
TOCATCH
return ;
case 1:
break;
}
}
}
}
void toSecurity::addUser(void)
{
for (toTreeWidgetItem *item = UserList->firstChild(); item; item = item->nextSibling())
if (item->text(1) == QString::fromLatin1("USER:"))
{
UserList->clearSelection();
UserList->setCurrentItem(item);
Tabs->setCurrentIndex(Tabs->indexOf(General));
General->setFocus();
break;
}
}
void toSecurity::addRole(void)
{
for (toTreeWidgetItem *item = UserList->firstChild(); item; item = item->nextSibling())
if (item->text(1) == QString::fromLatin1("ROLE:"))
{
UserList->clearSelection();
UserList->setCurrentItem(item);
Tabs->setCurrentIndex(Tabs->indexOf(General));
General->setFocus();
break;
}
}
void toSecurity::copy(void)
{
General->clear();
SystemGrant->eraseUser(false);
RoleGrant->eraseUser(General->user(), false);
ObjectGrant->eraseUser(false);
Quota->clear();
if (General->user())
UserID = QString::fromLatin1("USER:");
else
UserID = QString::fromLatin1("ROLE:");
for (toTreeWidgetItem *item = UserList->firstChild(); item; item = item->nextSibling())
if (item->text(1) == UserID)
{
disconnect(UserList, SIGNAL(selectionChanged(toTreeWidgetItem *)),
this, SLOT(changeUser(toTreeWidgetItem *)));
UserList->clearSelection();
UserList->setCurrentItem(item);
connect(UserList, SIGNAL(selectionChanged(toTreeWidgetItem *)),
this, SLOT(changeUser(toTreeWidgetItem *)));
break;
}
}
| tonytheodore/tora | src/tools/tosecurity.cpp | C++ | gpl-2.0 | 53,525 |
/*
* Copyright 2021 KylinSoft Co., Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <libudev.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/XInput.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
static int find_event_from_touchId(int pId ,char *_event,char *devnode,int max_len)
{
Display *_dpy = XOpenDisplay(NULL);
int ret = -1;
if(NULL == _dpy || NULL == _event)
{
printf("[%s%d] NULL ptr. \n", __FUNCTION__, __LINE__);
return ret;
}
int i = 0;
int j = 0;
int num_devices = 0;
XDeviceInfo *pXDevs_info = NULL;
XDevice *pXDev = NULL;
unsigned char *cNode = NULL;
const char cName[] = "event";
const char *cEvent = NULL;
int nprops = 0;
Atom *props = NULL;
char *name;
Atom act_type;
int act_format;
unsigned long nitems, bytes_after;
unsigned char *data;
pXDevs_info = XListInputDevices(_dpy, &num_devices);
for(i = 0; i < num_devices; i++)
{
pXDev = XOpenDevice(_dpy, pXDevs_info[i].id);
if (!pXDev)
{
printf("unable to open device '%s'\n", pXDevs_info[i].name);
continue;
}
props = XListDeviceProperties(_dpy, pXDev, &nprops);
if (!props)
{
printf("Device '%s' does not report any properties.\n", pXDevs_info[i].name);
continue;
}
//printf("pId=%d, pXDevs_info[i].id=%d \n",pId,pXDevs_info[i].id);
if(pId == pXDevs_info[i].id)
{
for(j = 0; j < nprops; j++)
{
name = XGetAtomName(_dpy, props[j]);
if(0 != strcmp(name, "Device Node"))
{
continue;
}
XGetDeviceProperty(_dpy, pXDev, props[j], 0, 1000, False,
AnyPropertyType, &act_type, &act_format,
&nitems, &bytes_after, &data);
cNode = data;
}
if(NULL == cNode)
{
continue;
}
cEvent = strstr((const char*)cNode, cName);
if(NULL == cEvent)
{
continue;
}
strcpy(devnode,(const char*)cNode);
strncpy(_event, cEvent, max_len>0?(max_len-1):max_len);
//printf("cNode=%s,cEvent=%s,_event=%s\n",cNode,cEvent,_event);
ret = Success;
break;
}
}
return ret;
}
static int find_serial_from_event(char *_name, char *_event, char *_serial, int max_len)
{
int ret = -1;
if((NULL == _name) || (NULL == _event))
{
printf("[%s%d] NULL ptr. \n", __FUNCTION__, __LINE__);
return ret;
}
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *devices, *dev_list_entry;
struct udev_device *dev;
udev = udev_new();
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "input");
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(dev_list_entry, devices)
{
const char *pPath;
const char *pEvent;
const char cName[] = "event";
pPath = udev_list_entry_get_name(dev_list_entry);
//printf("[%s%d] path: %s\n",__FUNCTION__, __LINE__, pPath);
dev = udev_device_new_from_syspath(udev, pPath);
//touchScreen is usb_device
dev = udev_device_get_parent_with_subsystem_devtype(
dev,
"usb",
"usb_device");
if (!dev)
{
//printf("Unable to find parent usb device. \n");
continue;
}
const char *pProduct = udev_device_get_sysattr_value(dev,"product");
pEvent = strstr(pPath, cName);
if(NULL == pEvent || (NULL == pProduct))
{
continue;
}
//printf("pEvent=%s,_event=%s\n",pEvent,_event);
//printf("_name=%s,pProduct=%s\n",_name,pProduct);
char *ret=strstr(_name, pProduct);
if((NULL!=ret) && (0 == strcmp(_event, pEvent)))
{
const char *pSerial = udev_device_get_sysattr_value(dev, "serial");
//printf(" _serial:%s\n pSerial: %s\n",_serial, pSerial);
if(NULL == pSerial)
{
continue;
}
strncpy(_serial, pSerial, max_len>0?(max_len-1):max_len);
ret = Success;
//printf(" _serial:%s\n pSerial: %s\n",_serial, pSerial);
break;
}
udev_device_unref(dev);
}
udev_enumerate_unref(enumerate);
udev_unref(udev);
return ret;
}
int findSerialFromId(int touchid,char *touchname,char *_touchserial,char *devnode,int maxlen)
{
char event[32]={0};
int ret=find_event_from_touchId(touchid, event,devnode, 32);
ret=find_serial_from_event(touchname, event,_touchserial,maxlen);
if(!strcmp(_touchserial,""))
strncpy(_touchserial,"kydefault",maxlen>0?(maxlen-1):maxlen);
return ret;
}
| ukui/ukui-control-center | plugins/system/touchscreen/touchserialquery.cpp | C++ | gpl-2.0 | 5,944 |
#include "ns3/log.h"
#include "ipv4-drb.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE("Ipv4Drb");
NS_OBJECT_ENSURE_REGISTERED (Ipv4Drb);
TypeId
Ipv4Drb::GetTypeId (void)
{
static TypeId tid = TypeId("ns3::Ipv4Drb")
.SetParent<Object>()
.SetGroupName ("Internet")
.AddConstructor<Ipv4Drb> ();
return tid;
}
Ipv4Drb::Ipv4Drb ()
{
NS_LOG_FUNCTION (this);
}
Ipv4Drb::~Ipv4Drb ()
{
NS_LOG_FUNCTION (this);
}
Ipv4Address
Ipv4Drb::GetCoreSwitchAddress (uint32_t flowId)
{
NS_LOG_FUNCTION (this);
uint32_t listSize = m_coreSwitchAddressList.size();
if (listSize == 0)
{
return Ipv4Address ();
}
uint32_t index = rand () % listSize;
std::map<uint32_t, uint32_t>::iterator itr = m_indexMap.find (flowId);
if (itr != m_indexMap.end ())
{
index = itr->second;
}
m_indexMap[flowId] = ((index + 1) % listSize);
Ipv4Address addr = m_coreSwitchAddressList[index];
NS_LOG_DEBUG (this << " The index for flow: " << flowId << " is : " << index);
return addr;
}
void
Ipv4Drb::AddCoreSwitchAddress (Ipv4Address addr)
{
NS_LOG_FUNCTION (this << addr);
m_coreSwitchAddressList.push_back (addr);
}
void
Ipv4Drb::AddCoreSwitchAddress (uint32_t k, Ipv4Address addr)
{
for (uint32_t i = 0; i < k; i++)
{
Ipv4Drb::AddCoreSwitchAddress(addr);
}
}
}
| snowzjx/ns3-buffer-management | src/internet/model/ipv4-drb.cc | C++ | gpl-2.0 | 1,311 |
/*
* java-gnome, a UI library for writing GTK and GNOME programs from Java!
*
* Copyright © 2007-2010 Operational Dynamics Consulting, Pty Ltd and Others
*
* The code in this file, and the program it is a part of, is made available
* to you by its authors as open source software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License version
* 2 ("GPL") as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details.
*
* You should have received a copy of the GPL along with this program. If not,
* see http://www.gnu.org/licenses/. The authors of this program may be
* contacted through http://java-gnome.sourceforge.net/.
*
* Linking this library statically or dynamically with other modules is making
* a combined work based on this library. Thus, the terms and conditions of
* the GPL cover the whole combination. As a special exception (the
* "Claspath Exception"), the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library. If
* you modify this library, you may extend the Classpath Exception to your
* version of the library, but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version.
*/
package org.gnome.gtk;
/**
* A MenuToolButton is an special kind of ToolButton that has an additional
* drop-down Menu.
*
* <p>
* Next to the ToolButton itself, a MenuToolButton shows another little Button
* with an arrow. When the user clicks this additional Button, a drop-down
* Menu pops up.
*
* <p>
* The main usage of a MenuToolButton is to provide access to several related
* actions in a Toolbar without wasting too much screen space. For example,
* your application can have a MenuToolButton for the "New Document" action,
* using the attached Menu to let users choose what kind of new document they
* want to create.
*
* <p>
* A MenuToolButton has a default action, to be executed when user clicks the
* main Button itself and not the the arrow Button. You can capture that
* default event with the {@link ToolButton.Clicked} signal. User Menu
* selections are captured with the usual {@link MenuItem.Activate} signal of
* each <code>MenuItem</code>.
*
* @see Toolbar
* @see Menu
*
* @author Vreixo Formoso
* @since 4.0.4
*/
public class MenuToolButton extends ToolButton
{
protected MenuToolButton(long pointer) {
super(pointer);
}
/**
* Creates a new MenuToolButton using the given icon and Label.
*
* @param iconWidget
* The Widget to be used as the icon for the MenuToolButton.
* Usually you will want to use a Widget display an image, such
* as {@link Image}. Use <code>null</code> if you do not want
* an icon.
* @param label
* The Label for the MenuToolButton, or <code>null</code> to
* provide not Label.
*/
public MenuToolButton(Widget iconWidget, String label) {
super(GtkMenuToolButton.createMenuToolButton(iconWidget, label));
}
/**
* Creates a new MenuToolButton from the specific stock item. Both the
* Label and icon will be set properly from the stock item. By using a
* system stock item, the newly created MenuToolButton with use the same
* Label and Image as other GNOME applications. To ensure consistent look
* and feel between applications, it is highly recommended that you use
* provided stock items whenever possible.
*
* @param stock
* The StockId that will determine the Label and icon of the
* MenuToolButton.
*/
public MenuToolButton(Stock stock) {
super(GtkMenuToolButton.createMenuToolButtonFromStock(stock.getStockId()));
}
/**
* Sets the Menu to be popped up when the user clicks the arrow Button.
*
* <p>
* You can pass <code>null</code> to make arrow insensitive.
*/
public void setMenu(Menu menu) {
GtkMenuToolButton.setMenu(this, menu);
}
/**
* Get the Menu associated with the MenuToolButton.
*
* @return The associated Menu or <code>null</code> if no Menu has been
* set.
*/
public Menu getMenu() {
return (Menu) GtkMenuToolButton.getMenu(this);
}
}
| cyberpython/java-gnome | src/bindings/org/gnome/gtk/MenuToolButton.java | Java | gpl-2.0 | 4,952 |
// This file is part of Chaotic Rage (c) 2010 Josh Heidenreich
//
// kate: tab-width 4; indent-width 4; space-indent off; word-wrap off;
#include "SPK_TextureQuadRenderer.h"
#include <Core/SPK_Particle.h>
#include <Core/SPK_Group.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "../render_opengl/texture_2d_array.h"
#include "../render_opengl/gl.h"
namespace SPK
{
namespace GL
{
GL2InstanceQuadRenderer::GL2InstanceQuadRenderer(float size) :
BaseQuadRenderer(),
texture(NULL),
vao(0),
vboBillboardVertex(0),
vboPositions(0),
vboColors(0),
buffer(NULL),
buffer_sz(0)
{
this->size[0] = this->size[1] = size;
}
GL2InstanceQuadRenderer::~GL2InstanceQuadRenderer()
{
free(buffer);
}
void GL2InstanceQuadRenderer::initGLbuffers()
{
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// The VBO containing the 4 vertices of the particles.
// Thanks to instancing, they will be shared by all particles.
static const GLfloat quad_vertex_data[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, 0.5f, 0.0f,
0.5f, 0.5f, 0.0f,
};
// Set up vertex buffer
glGenBuffers(1, &vboBillboardVertex);
glBindBuffer(GL_ARRAY_BUFFER, vboBillboardVertex);
glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertex_data), quad_vertex_data, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribDivisor(0, 0);
// Set up position buffer
glGenBuffers(1, &vboPositions);
glBindBuffer(GL_ARRAY_BUFFER, vboPositions);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribDivisor(1, 1);
// Set up colors buffer
glGenBuffers(1, &vboColors);
glBindBuffer(GL_ARRAY_BUFFER, vboColors);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribDivisor(2, 1);
glBindVertexArray(0);
shaderIndex = createShaderProgram(
"in vec3 vVertexPosition;\n"
"in vec4 vParticlePosition;\n"
"in vec4 vColor;\n"
"out vec4 fColor;\n"
"out vec2 fTexUV;\n"
"out float fTexIndex;\n"
"uniform vec3 camUp;\n"
"uniform vec3 camRight;\n"
"uniform vec2 size;\n"
"uniform mat4 mVP;\n"
"void main() {\n"
"vec3 pos = vParticlePosition.xyz\n"
"+ camRight * vVertexPosition.x * size.x\n"
"+ camUp * vVertexPosition.y * size.y;\n"
"gl_Position = mVP * vec4(pos, 1.0);\n"
"fColor = vColor;\n"
"fTexUV = vVertexPosition.xy + vec2(0.5, 0.5);\n"
"fTexIndex = vParticlePosition.w;\n"
"}\n",
"in vec4 fColor;\n"
"in vec2 fTexUV;\n"
"in float fTexIndex;\n"
"uniform sampler2DArray tex;\n"
"void main() {\n"
"gl_FragColor = texture(tex, vec3(fTexUV.xy, fTexIndex)) * fColor;\n"
"}\n"
);
uniform_camUp = glGetUniformLocation(shaderIndex, "camUp");
uniform_camRight = glGetUniformLocation(shaderIndex, "camRight");
uniform_size = glGetUniformLocation(shaderIndex, "size");
uniform_mvp = glGetUniformLocation(shaderIndex, "mVP");
}
void GL2InstanceQuadRenderer::destroyGLbuffers()
{
glDeleteBuffers(1, &vboBillboardVertex);
glDeleteBuffers(1, &vboPositions);
glDeleteBuffers(1, &vboColors);
glDeleteVertexArrays(1, &vao);
glDeleteProgram(shaderIndex);
vboBillboardVertex = 0;
vboPositions = 0;
vboColors = 0;
vao = 0;
shaderIndex = 0;
}
void GL2InstanceQuadRenderer::render(const Group& group)
{
float* ptr;
size_t num = group.getNbParticles();
// Unable to render if no texture set
if (texture == NULL) {
return;
}
// Resize buffer if not large enough
if (num > buffer_sz) {
if (buffer_sz == 0) buffer_sz = 1024;
while (buffer_sz < num) {
buffer_sz *= 2;
}
free(buffer);
buffer = (float*) malloc(sizeof(float) * 4 * buffer_sz);
}
// Copy data into buffer with the correct layout
// XYZ is coordinate and W is texture index
ptr = buffer;
for (size_t i = 0; i < num; ++i) {
const Particle& particle = group.getParticle(i);
*ptr++ = particle.position().x;
*ptr++ = particle.position().y;
*ptr++ = particle.position().z;
*ptr++ = particle.getParamCurrentValue(SPK::PARAM_TEXTURE_INDEX);
}
// Set position data
glBindBuffer(GL_ARRAY_BUFFER, vboPositions);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * num, buffer, GL_DYNAMIC_DRAW);
// again for the color buffer
ptr = buffer;
for (size_t i = 0; i < num; ++i) {
const Particle& particle = group.getParticle(i);
*ptr++ = particle.getParamCurrentValue(SPK::PARAM_RED);
*ptr++ = particle.getParamCurrentValue(SPK::PARAM_GREEN);
*ptr++ = particle.getParamCurrentValue(SPK::PARAM_BLUE);
*ptr++ = particle.getParamCurrentValue(SPK::PARAM_ALPHA);
}
// Set color data
glBindBuffer(GL_ARRAY_BUFFER, vboColors);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * num, buffer, GL_DYNAMIC_DRAW);
glm::vec3 camUp = glm::vec3(v_matrix[0][1], v_matrix[1][1], v_matrix[2][1]);
glm::vec3 camRight = glm::vec3(v_matrix[0][0], v_matrix[1][0], v_matrix[2][0]);
glBindTexture(GL_TEXTURE_2D_ARRAY, texture->getTexIndex());
// Bind VAO and shader, set uniforms, draw
glBindVertexArray(vao);
glUseProgram(shaderIndex);
glUniform3fv(uniform_camUp, 1, glm::value_ptr(camUp));
glUniform3fv(uniform_camRight, 1, glm::value_ptr(camRight));
glUniform2fv(uniform_size, 1, this->size);
glUniformMatrix4fv(uniform_mvp, 1, GL_FALSE, glm::value_ptr(vp_matrix));
glDepthMask(GL_FALSE);
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num);
glDepthMask(GL_TRUE);
glBindVertexArray(0);
}
}}
| TheJosh/chaotic-rage | src/fx/SPK_TextureQuadRenderer.cpp | C++ | gpl-2.0 | 5,561 |
package ebu.metadata_schema.ebucore_2015;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Classe Java pour positionInteractionRangeType complex type.
*
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
*
* <pre>
* <complexType name="positionInteractionRangeType">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>float">
* <attribute name="coordinate" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="bound" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "positionInteractionRangeType", propOrder = {
"value"
})
public class PositionInteractionRangeType
implements Serializable
{
private final static long serialVersionUID = -1L;
@XmlValue
protected float value;
@XmlAttribute(name = "coordinate")
protected java.lang.String coordinate;
@XmlAttribute(name = "bound")
protected java.lang.String bound;
/**
* Obtient la valeur de la propriété value.
*
*/
public float getValue() {
return value;
}
/**
* Définit la valeur de la propriété value.
*
*/
public void setValue(float value) {
this.value = value;
}
/**
* Obtient la valeur de la propriété coordinate.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getCoordinate() {
return coordinate;
}
/**
* Définit la valeur de la propriété coordinate.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setCoordinate(java.lang.String value) {
this.coordinate = value;
}
/**
* Obtient la valeur de la propriété bound.
*
* @return
* possible object is
* {@link java.lang.String }
*
*/
public java.lang.String getBound() {
return bound;
}
/**
* Définit la valeur de la propriété bound.
*
* @param value
* allowed object is
* {@link java.lang.String }
*
*/
public void setBound(java.lang.String value) {
this.bound = value;
}
}
| mikrosimage/jebu-core | src/main/java/ebu/metadata_schema/ebucore_2015/PositionInteractionRangeType.java | Java | gpl-2.0 | 2,653 |
/* $Id: errmsgwin.cpp $ */
/** @file
* IPRT - Status code messages.
*/
/*
* Copyright (C) 2006-2011 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <Windows.h>
#include <iprt/err.h>
#include <iprt/asm.h>
#include <iprt/string.h>
#include <iprt/err.h>
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/** Array of messages.
* The data is generated by a sed script.
*/
static const RTWINERRMSG g_aStatusMsgs[] =
{
#ifndef IPRT_NO_ERROR_DATA
# include "errmsgcomdata.h"
# if defined(VBOX) && !defined(IN_GUEST)
# include "errmsgvboxcomdata.h"
# endif
#else
{ "Success.", "ERROR_SUCCESS", 0 },
#endif
{ NULL, NULL, 0 }
};
/** Temporary buffers to format unknown messages in.
* @{
*/
static char g_aszUnknownStr[4][64];
static RTWINERRMSG g_aUnknownMsgs[4] =
{
{ &g_aszUnknownStr[0][0], &g_aszUnknownStr[0][0], 0 },
{ &g_aszUnknownStr[1][0], &g_aszUnknownStr[1][0], 0 },
{ &g_aszUnknownStr[2][0], &g_aszUnknownStr[2][0], 0 },
{ &g_aszUnknownStr[3][0], &g_aszUnknownStr[3][0], 0 }
};
/** Last used index in g_aUnknownMsgs. */
static volatile uint32_t g_iUnknownMsgs;
/** @} */
/**
* Get the message corresponding to a given status code.
*
* @returns Pointer to read-only message description.
* @param rc The status code.
*/
RTDECL(PCRTWINERRMSG) RTErrWinGet(long rc)
{
unsigned i;
for (i = 0; i < RT_ELEMENTS(g_aStatusMsgs) - 1U; i++)
if (g_aStatusMsgs[i].iCode == rc)
return &g_aStatusMsgs[i];
/* The g_aStatusMsgs table contains a wild mix of error codes with and
* without included facility and severity. So the chance is high that there
* was no exact match. Try to find a non-exact match, and include the
* actual value in case we pick the wrong entry. Better than always using
* the "Unknown Status" case. */
for (i = 0; i < RT_ELEMENTS(g_aStatusMsgs) - 1U; i++)
if (g_aStatusMsgs[i].iCode == HRESULT_CODE(rc))
{
int32_t iMsg = (ASMAtomicIncU32(&g_iUnknownMsgs) - 1) % RT_ELEMENTS(g_aUnknownMsgs);
RTStrPrintf(&g_aszUnknownStr[iMsg][0], sizeof(g_aszUnknownStr[iMsg]), "%s 0x%X", g_aStatusMsgs[i].pszDefine, rc);
return &g_aUnknownMsgs[iMsg];
}
/*
* Need to use the temporary stuff.
*/
int32_t iMsg = (ASMAtomicIncU32(&g_iUnknownMsgs) - 1) % RT_ELEMENTS(g_aUnknownMsgs);
RTStrPrintf(&g_aszUnknownStr[iMsg][0], sizeof(g_aszUnknownStr[iMsg]), "Unknown Status 0x%X", rc);
return &g_aUnknownMsgs[iMsg];
}
RTDECL(PCRTCOMERRMSG) RTErrCOMGet(uint32_t rc)
{
return RTErrWinGet((long)rc);
}
| bayasist/vbox | src/VBox/Runtime/win/errmsgwin.cpp | C++ | gpl-2.0 | 3,978 |
<?php
class GrandAccess {
static $alreadyDone = array();
static function setupGrandAccess($user, &$aRights){
global $wgRoleValues;
if(isset(self::$alreadyDone[$user->getId()])){
$user->mGroups = self::$alreadyDone[$user->getId()];
$aRights = $user->mGroups;
return true;
}
$me = Person::newFromId($user->getId());
$i = 1000;
$oldRights = $aRights;
foreach($oldRights as $right){
$aRights[$i++] = $right;
}
if(count($me->getProjects()) > 0){
foreach($me->getProjects() as $project){
$aRights[$i++] = $project->getName();
}
}
if($me->isThemeLeader() || $me->isThemeCoordinator()){
$aRights[$i++] = TL;
$aRights[$i++] = TC;
}
foreach(array_merge($me->getLeadThemes(), $me->getCoordThemes()) as $theme){
$aRights[$i++] = $theme->getAcronym();
}
foreach($me->getThemeProjects() as $project){
$aRights[$i++] = $project->getName();
}
if($me->isRoleAtLeast(STAFF)){
$aRights[$i++] = PL;
$aRights[$i++] = TL;
$aRights[$i++] = TC;
}
if($me->isEvaluator()){
$aRights[$i++] = "Evaluator";
$aRights[$i++] = "Evaluator+";
}
if($me->isRole(NI)){
$aRights[$i++] = "NI";
$aRights[$i++] = "NI+";
}
if($me->isRole(ADMIN)){
$aRights[$i++] = "sysop";
$aRights[$i++] = "bureaucrat";
}
foreach(array_keys($wgRoleValues) as $role){
if($me->isRoleAtLeast($role)){
$aRights[$i++] = $role.'+';
if(($role == STAFF || $role == MANAGER || $role == ADMIN) && array_search('Evaluator+', $aRights) === false){
$aRights[$i++] = 'Evaluator+';
}
}
}
if(count($me->getRoles()) > 0){
foreach($me->getRoles() as $role){
$aRights[$i++] = $role->getRole();
$user->mGroups[] = $role->getRole().'_Wiki';
}
}
foreach($aRights as $right){
$user->mGroups[] = $right;
}
if($user->isLoggedIn()){
$user->mGroups[] = "Poster";
$user->mGroups[] = "Presentation";
}
self::$alreadyDone[$user->getId()] = $aRights;
return true;
}
static function changeGroups($user, &$aRights){
global $wgRoles;
foreach($aRights as $key => $right){
if($key >= 1000){
continue;
}
unset($aRights[$key]);
}
$aRights[0] = 'read';
return true;
}
}
?>
| UniversityOfAlberta/GrandForum | extensions/AccessControls/GrandAccess.php | PHP | gpl-2.0 | 2,615 |
from StateMachine.State import State
from StateMachine.StateMachine import StateMachine
from StateMachine.InputAction import InputAction
from GameData.GameData import GameData
class StateT(State):
state_stack = list()
game_data = GameData()
def __init__(self):
self.transitions = None
def next(self, input):
if self.transitions.has_key(input):
return self.transitions[input]
else:
raise Exception("Input not supported for current state")
class NightBegins(StateT):
def run(self):
print("NightTime Falls")
def next(self, input):
StateT.state_stack.append(self)
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.playQuestCard : GameStates.nightBegins,
InputAction.drawDSCard : GameStates.drawDSCard,
}
return StateT.next(self, input)
class DrawDSCard(StateT):
def run(self):
print("Darkness Spreads drawing card")
StateT.current_ds_card = StateT.game_data.ds_cards.pop()
StateT.current_ds_card.display()
print "STACK: " + str(StateT.state_stack)
def next(self, input):
StateT.state_stack.append(self)
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.playQuestCard : GameStates.nightBegins,
InputAction.drawDSCard : GameStates.drawDSCard,
InputAction.executeDSCard : GameStates.executeDSCard,
}
return StateT.next(self, input)
class ExecuteDSCard(StateT):
def run(self):
print("Darkness Spreads - executing card")
StateT.current_ds_card.execute(StateT.game_data)
print "STACK: " + str(StateT.state_stack)
def next(self, input):
StateT.state_stack.append(self)
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.playQuestCard : GameStates.nightBegins,
InputAction.drawDSCard : GameStates.drawDSCard,
InputAction.advanceToDay : GameStates.dayBegins,
}
return StateT.next(self, input)
class DayBegins(StateT):
def run(self):
print("Day Time")
print "STACK: " + str(StateT.state_stack)
def next(self, input):
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.PlayQuestCard : GameStates.nightBegins,
InputAction.advanceToEvening : GameStates.eveningBegins,
}
return StateT.next(self, input)
class EveningBegins(StateT):
def run(self):
print("Day Time")
print "STACK: " + str(StateT.state_stack)
def next(self, input):
if not self.transitions:
self.transitions = {
InputAction.getGameData : GameStates.nightBegins,
InputAction.playHeroCard : GameStates.nightBegins,
InputAction.PlayQuestCard : GameStates.nightBegins,
InputAction.advanceToNight : GameStates.nightBegins,
}
return StateT.next(self, input)
class GameStates(StateMachine):
def __init__(self):
# Initial state
StateMachine.__init__(self, GameStates.nightBegins)
# Static variable initialization:
GameStates.nightBegins = NightBegins()
GameStates.drawDSCard = DrawDSCard()
GameStates.executeDSCard = ExecuteDSCard()
GameStates.eveningBegins = EveningBegins()
GameStates.dayBegins = DayBegins()
| jmacleod/dotr | GameStates.py | Python | gpl-2.0 | 3,904 |
<?php
namespace TYPO3\CMS\Extensionmanager\Controller;
/***************************************************************
* Copyright notice
*
* (c) 2012-2013 Susanne Moog, <typo3@susannemoog.de>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
* A copy is found in the textfile GPL.txt and important notices to the license
* from the author is found in LICENSE.txt distributed with these scripts.
*
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* Controller for extension listings (TER or local extensions)
*
* @author Susanne Moog <typo3@susannemoog.de>
*/
class ListController extends \TYPO3\CMS\Extensionmanager\Controller\AbstractController {
/**
* @var \TYPO3\CMS\Extensionmanager\Domain\Repository\ExtensionRepository
*/
protected $extensionRepository;
/**
* @var \TYPO3\CMS\Extensionmanager\Utility\ListUtility
*/
protected $listUtility;
/**
* Dependency injection of the Extension Repository
*
* @param \TYPO3\CMS\Extensionmanager\Domain\Repository\ExtensionRepository $extensionRepository
* @return void
*/
public function injectExtensionRepository(\TYPO3\CMS\Extensionmanager\Domain\Repository\ExtensionRepository $extensionRepository) {
$this->extensionRepository = $extensionRepository;
}
/**
* @param \TYPO3\CMS\Extensionmanager\Utility\ListUtility $listUtility
* @return void
*/
public function injectListUtility(\TYPO3\CMS\Extensionmanager\Utility\ListUtility $listUtility) {
$this->listUtility = $listUtility;
}
/**
* @var \TYPO3\CMS\Core\Page\PageRenderer
*/
protected $pageRenderer;
/**
* @param \TYPO3\CMS\Core\Page\PageRenderer $pageRenderer
* @return void
*/
public function injectPageRenderer(\TYPO3\CMS\Core\Page\PageRenderer $pageRenderer) {
$this->pageRenderer = $pageRenderer;
}
/**
* Add the needed JavaScript files for all actions
*/
public function initializeAction() {
$this->pageRenderer->addJsFile('../t3lib/js/extjs/notifications.js');
$this->pageRenderer->addInlineLanguageLabelFile('EXT:extensionmanager/Resources/Private/Language/locallang.xlf');
}
/**
* Shows list of extensions present in the system
*
* @return void
*/
public function indexAction() {
$availableExtensions = $this->listUtility->getAvailableExtensions();
$availableAndInstalledExtensions = $this->listUtility->getAvailableAndInstalledExtensions($availableExtensions);
$availableAndInstalledExtensions = $this->listUtility->enrichExtensionsWithEmConfAndTerInformation($availableAndInstalledExtensions);
$this->view->assign('extensions', $availableAndInstalledExtensions);
$this->handleTriggerArguments();
}
/**
* Shows extensions from TER
* Either all extensions or depending on a search param
*
* @param string $search
*/
public function terAction($search = '') {
if (!empty($search)) {
$extensions = $this->extensionRepository->findByTitleOrAuthorNameOrExtensionKey($search);
} else {
$extensions = $this->extensionRepository->findAll();
}
$availableAndInstalledExtensions = $this->listUtility->getAvailableAndInstalledExtensionsWithAdditionalInformation();
$this->view->assign('extensions', $extensions)
->assign('search', $search)
->assign('availableAndInstalled', $availableAndInstalledExtensions);
}
/**
* Shows all versions of a specific extension
*
* @param string $extensionKey
*/
public function showAllVersionsAction($extensionKey) {
$currentVersion = $this->extensionRepository->findOneByCurrentVersionByExtensionKey($extensionKey);
$extensions = $this->extensionRepository->findByExtensionKeyOrderedByVersion($extensionKey);
$this->view->assignMultiple(
array(
'extensionKey' => $extensionKey,
'currentVersion' => $currentVersion,
'extensions' => $extensions
)
);
}
}
?> | tonglin/pdPm | public_html/typo3_src-6.1.7/typo3/sysext/extensionmanager/Classes/Controller/ListController.php | PHP | gpl-2.0 | 4,499 |
/* This file is part of the KDE project
Copyright (C) 2006-2011 Jarosław Staniek <staniek@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kexidatetimeformatter.h"
#include <kdebug.h>
#include <klocale.h>
#include <kglobal.h>
#include <kdatepicker.h>
#include <kdatetable.h>
#include <klineedit.h>
#include <kmenu.h>
#include <kdatewidget.h>
class KexiDateFormatter::Private
{
public:
Private() {}
//! Input mask generated using the formatter settings. Can be used in QLineEdit::setInputMask().
QString inputMask;
//! Order of date sections
Order order;
//! 4 or 2 digits
bool longYear;
bool monthWithLeadingZero, dayWithLeadingZero;
//! Date format used in toString()
QString qtFormat;
//! Used in fromString(const QString&) to convert string back to QDate
int yearpos, monthpos, daypos;
QString separator;
};
class KexiTimeFormatter::Private
{
public:
Private()
: hmsRegExp(new QRegExp(
QLatin1String("(\\d*):(\\d*):(\\d*).*( am| pm){,1}"), Qt::CaseInsensitive))
, hmRegExp(new QRegExp(
QLatin1String("(\\d*):(\\d*).*( am| pm){,1}"), Qt::CaseInsensitive))
{
}
~Private()
{
delete hmsRegExp;
delete hmRegExp;
}
//! Input mask generated using the formatter settings. Can be used in QLineEdit::setInputMask().
QString inputMask;
// //! Order of date sections
// QDateEdit::Order order;
//! 12 or 12h
bool is24h;
bool hoursWithLeadingZero;
//! Time format used in toString(). Notation from KLocale::setTimeFormat() is used.
QString outputFormat;
//! Used in fromString(const QString&) to convert string back to QTime
int hourpos, minpos, secpos, ampmpos;
QRegExp *hmsRegExp, *hmRegExp;
};
KexiDateFormatter::KexiDateFormatter()
: d(new Private)
{
// use "short date" format system settings
//! @todo allow to override the format using column property and/or global app settings
QString df(KGlobal::locale()->dateFormatShort());
if (df.length() > 2)
d->separator = df.mid(2, 1);
else
d->separator = "-";
const int separatorLen = d->separator.length();
QString yearMask("9999");
QString yearDateFormat("yyyy");
QString monthDateFormat("MM");
QString dayDateFormat("dd"); //for setting up d->dateFormat
bool ok = df.length() >= 8;
int yearpos, monthpos, daypos; //result of df.find()
if (ok) {//look at % variables
//! @todo more variables are possible here, see void KLocale::setDateFormatShort() docs
//! http://developer.kde.org/documentation/library/3.5-api/kdelibs-apidocs/kdecore/html/classKLocale.html#a59
yearpos = df.indexOf("%y", 0, Qt::CaseInsensitive); //&y or %y
d->longYear = !(yearpos >= 0 && df.mid(yearpos + 1, 1) == "y");
if (!d->longYear) {
yearMask = "99";
yearDateFormat = "yy";
}
monthpos = df.indexOf("%m", 0, Qt::CaseSensitive); //%m or %n
d->monthWithLeadingZero = true;
if (monthpos < 0) {
monthpos = df.indexOf("%n", 0, Qt::CaseInsensitive);
d->monthWithLeadingZero = false;
monthDateFormat = "M";
}
daypos = df.indexOf("%d", 0, Qt::CaseSensitive);//%d or %e
d->dayWithLeadingZero = true;
if (daypos < 0) {
daypos = df.indexOf("%e", 0, Qt::CaseInsensitive);
d->dayWithLeadingZero = false;
dayDateFormat = "d";
}
ok = (yearpos >= 0 && monthpos >= 0 && daypos >= 0);
}
d->order = YMD; //default
if (ok) {
if (yearpos < monthpos && monthpos < daypos) {
//will be set in "default: YMD"
} else if (yearpos < daypos && daypos < monthpos) {
d->order = YDM;
//! @todo use QRegExp (to replace %Y by %1, etc.) instead of hardcoded "%1%299%399"
//! because df may contain also other characters
d->inputMask = yearMask + d->separator + QLatin1String("99") + d->separator + QLatin1String("99");
d->qtFormat = yearDateFormat + d->separator + dayDateFormat + d->separator + monthDateFormat;
d->yearpos = 0;
d->daypos = yearMask.length() + separatorLen;
d->monthpos = d->daypos + 2 + separatorLen;
} else if (daypos < monthpos && monthpos < yearpos) {
d->order = DMY;
d->inputMask = QLatin1String("99") + d->separator + QLatin1String("99") + d->separator + yearMask;
d->qtFormat = dayDateFormat + d->separator + monthDateFormat + d->separator + yearDateFormat;
d->daypos = 0;
d->monthpos = 2 + separatorLen;
d->yearpos = d->monthpos + 2 + separatorLen;
} else if (monthpos < daypos && daypos < yearpos) {
d->order = MDY;
d->inputMask = QLatin1String("99") + d->separator + QLatin1String("99") + d->separator + yearMask;
d->qtFormat = monthDateFormat + d->separator + dayDateFormat + d->separator + yearDateFormat;
d->monthpos = 0;
d->daypos = 2 + separatorLen;
d->yearpos = d->daypos + 2 + separatorLen;
} else
ok = false;
}
if (!ok || d->order == YMD) {//default: YMD
d->inputMask = yearMask + d->separator + QLatin1String("99") + d->separator + QLatin1String("99");
d->qtFormat = yearDateFormat + d->separator + monthDateFormat + d->separator + dayDateFormat;
d->yearpos = 0;
d->monthpos = yearMask.length() + separatorLen;
d->daypos = d->monthpos + 2 + separatorLen;
}
d->inputMask += ";_";
}
KexiDateFormatter::~KexiDateFormatter()
{
delete d;
}
QDate KexiDateFormatter::fromString(const QString& str) const
{
bool ok = true;
int year = str.mid(d->yearpos, d->longYear ? 4 : 2).toInt(&ok);
if (!ok)
return QDate();
if (year < 30) {//2000..2029
year = 2000 + year;
} else if (year < 100) {//1930..1999
year = 1900 + year;
}
int month = str.mid(d->monthpos, 2).toInt(&ok);
if (!ok)
return QDate();
int day = str.mid(d->daypos, 2).toInt(&ok);
if (!ok)
return QDate();
QDate date(year, month, day);
if (!date.isValid())
return QDate();
return date;
}
QVariant KexiDateFormatter::stringToVariant(const QString& str) const
{
if (isEmpty(str))
return QVariant();
const QDate date(fromString(str));
if (date.isValid())
return date;
return QVariant();
}
bool KexiDateFormatter::isEmpty(const QString& str) const
{
QString s(str);
return s.remove(d->separator).trimmed().isEmpty();
}
QString KexiDateFormatter::inputMask() const
{
return d->inputMask;
}
QString KexiDateFormatter::separator() const
{
return d->separator;
}
QString KexiDateFormatter::toString(const QDate& date) const
{
return date.toString(d->qtFormat);
}
//------------------------------------------------
KexiTimeFormatter::KexiTimeFormatter()
: d(new Private)
{
QString tf(KGlobal::locale()->timeFormat());
//d->hourpos, d->minpos, d->secpos; are result of tf.indexOf()
QString hourVariable, minVariable, secVariable;
//detect position of HOUR section: find %H or %k or %I or %l
d->is24h = true;
d->hoursWithLeadingZero = true;
d->hourpos = tf.indexOf("%H", 0, Qt::CaseSensitive);
if (d->hourpos >= 0) {
d->is24h = true;
d->hoursWithLeadingZero = true;
} else {
d->hourpos = tf.indexOf("%k", 0, Qt::CaseSensitive);
if (d->hourpos >= 0) {
d->is24h = true;
d->hoursWithLeadingZero = false;
} else {
d->hourpos = tf.indexOf("%I", 0, Qt::CaseSensitive);
if (d->hourpos >= 0) {
d->is24h = false;
d->hoursWithLeadingZero = true;
} else {
d->hourpos = tf.indexOf("%l", 0, Qt::CaseSensitive);
if (d->hourpos >= 0) {
d->is24h = false;
d->hoursWithLeadingZero = false;
}
}
}
}
d->minpos = tf.indexOf("%M", 0, Qt::CaseSensitive);
d->secpos = tf.indexOf("%S", 0, Qt::CaseSensitive); //can be -1
d->ampmpos = tf.indexOf("%p", 0, Qt::CaseSensitive); //can be -1
if (d->hourpos < 0 || d->minpos < 0) {
//set default: hr and min are needed, sec are optional
tf = "%H:%M:%S";
d->is24h = true;
d->hoursWithLeadingZero = false;
d->hourpos = 0;
d->minpos = 3;
d->secpos = d->minpos + 3;
d->ampmpos = -1;
}
hourVariable = tf.mid(d->hourpos, 2);
d->inputMask = tf;
// d->inputMask.replace( hourVariable, "00" );
// d->inputMask.replace( "%M", "00" );
// d->inputMask.replace( "%S", "00" ); //optional
d->inputMask.replace(hourVariable, "99");
d->inputMask.replace("%M", "99");
d->inputMask.replace("%S", "00"); //optional
d->inputMask.replace("%p", "AA"); //am or pm
d->inputMask += ";_";
d->outputFormat = tf;
}
KexiTimeFormatter::~KexiTimeFormatter()
{
delete d;
}
QTime KexiTimeFormatter::fromString(const QString& str) const
{
int hour, min, sec;
bool pm = false;
bool tryWithoutSeconds = true;
if (d->secpos >= 0) {
if (-1 != d->hmsRegExp->indexIn(str)) {
hour = d->hmsRegExp->cap(1).toInt();
min = d->hmsRegExp->cap(2).toInt();
sec = d->hmsRegExp->cap(3).toInt();
if (d->ampmpos >= 0 && d->hmsRegExp->numCaptures() > 3)
pm = d->hmsRegExp->cap(4).trimmed().toLower() == "pm";
tryWithoutSeconds = false;
}
}
if (tryWithoutSeconds) {
if (-1 == d->hmRegExp->indexIn(str))
return QTime(99, 0, 0);
hour = d->hmRegExp->cap(1).toInt();
min = d->hmRegExp->cap(2).toInt();
sec = 0;
if (d->ampmpos >= 0 && d->hmRegExp->numCaptures() > 2)
pm = d->hmsRegExp->cap(4).toLower() == "pm";
}
if (pm && hour < 12)
hour += 12; //PM
return QTime(hour, min, sec);
}
QVariant KexiTimeFormatter::stringToVariant(const QString& str)
{
if (isEmpty(str))
return QVariant();
const QTime time(fromString(str));
if (time.isValid())
return time;
return QVariant();
}
bool KexiTimeFormatter::isEmpty(const QString& str) const
{
QString s(str);
return s.remove(':').trimmed().isEmpty();
}
QString KexiTimeFormatter::toString(const QTime& time) const
{
if (!time.isValid())
return QString();
QString s(d->outputFormat);
if (d->is24h) {
if (d->hoursWithLeadingZero)
s.replace("%H", QString::fromLatin1(time.hour() < 10 ? "0" : "") + QString::number(time.hour()));
else
s.replace("%k", QString::number(time.hour()));
} else {
int time12 = (time.hour() > 12) ? (time.hour() - 12) : time.hour();
if (d->hoursWithLeadingZero)
s.replace("%I", QString::fromLatin1(time12 < 10 ? "0" : "") + QString::number(time12));
else
s.replace("%l", QString::number(time12));
}
s.replace("%M", QString::fromLatin1(time.minute() < 10 ? "0" : "") + QString::number(time.minute()));
if (d->secpos >= 0)
s.replace("%S", QString::fromLatin1(time.second() < 10 ? "0" : "") + QString::number(time.second()));
if (d->ampmpos >= 0)
s.replace("%p", ki18n( time.hour() >= 12 ? "pm" : "am" ).toString( KGlobal::locale() ));
return s;
}
QString KexiTimeFormatter::inputMask() const
{
return d->inputMask;
}
//------------------------------------------------
QString KexiDateTimeFormatter::inputMask(const KexiDateFormatter& dateFormatter,
const KexiTimeFormatter& timeFormatter)
{
QString mask(dateFormatter.inputMask());
mask.truncate(dateFormatter.inputMask().length() - 2);
return mask + " " + timeFormatter.inputMask();
}
QDateTime KexiDateTimeFormatter::fromString(
const KexiDateFormatter& dateFormatter,
const KexiTimeFormatter& timeFormatter, const QString& str)
{
QString s(str.trimmed());
const int timepos = s.indexOf(' ');
const bool emptyTime = timepos >= 0 && timeFormatter.isEmpty(s.mid(timepos + 1)); //.remove(':').trimmed().isEmpty();
if (emptyTime)
s = s.left(timepos);
if (timepos > 0 && !emptyTime) {
return QDateTime(
dateFormatter.fromString(s.left(timepos)),
timeFormatter.fromString(s.mid(timepos + 1))
);
} else {
return QDateTime(
dateFormatter.fromString(s),
QTime(0, 0, 0)
);
}
}
QString KexiDateTimeFormatter::toString(const KexiDateFormatter &dateFormatter,
const KexiTimeFormatter &timeFormatter,
const QDateTime &value)
{
if (value.isValid())
return dateFormatter.toString(value.date()) + ' '
+ timeFormatter.toString(value.time());
return QString();
}
bool KexiDateTimeFormatter::isEmpty(const KexiDateFormatter& dateFormatter,
const KexiTimeFormatter& timeFormatter,
const QString& str)
{
int timepos = str.indexOf(' ');
const bool emptyTime = timepos >= 0 && timeFormatter.isEmpty(str.mid(timepos + 1)); //s.mid(timepos+1).remove(':').trimmed().isEmpty();
return (timepos >= 0 && dateFormatter.isEmpty(str.left(timepos)) //s.left(timepos).remove(d->dateFormatter.separator()).trimmed().isEmpty()
&& emptyTime);
}
bool KexiDateTimeFormatter::isValid(const KexiDateFormatter& dateFormatter,
const KexiTimeFormatter& timeFormatter, const QString& str)
{
int timepos = str.indexOf(' ');
const bool emptyTime = timepos >= 0 && timeFormatter.isEmpty(str.mid(timepos + 1)); //s.mid(timepos+1).remove(':').trimmed().isEmpty();
if (timepos >= 0 && dateFormatter.isEmpty(str.left(timepos)) // s.left(timepos).remove(d->dateFormatter.separator()).trimmed().isEmpty()
&& emptyTime)
//empty date/time is valid
return true;
return timepos >= 0 && dateFormatter.fromString(str.left(timepos)).isValid()
&& (emptyTime /*date without time is also valid*/ || timeFormatter.fromString(str.mid(timepos + 1)).isValid());
}
| yxl/emscripten-calligra-mobile | kexi/widget/utils/kexidatetimeformatter.cpp | C++ | gpl-2.0 | 15,194 |
<?php
/**
* Copyright (c) 2011 ScientiaMobile, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Refer to the COPYING file distributed with this package.
*
*
* @category WURFL
* @package WURFL_Handlers
* @copyright ScientiaMobile, Inc.
* @license GNU Affero General Public License
* @version $id$
*/
/**
* KyoceraUserAgentHandler
*
*
* @category WURFL
* @package WURFL_Handlers
* @copyright ScientiaMobile, Inc.
* @license GNU Affero General Public License
* @version $id$
*/
class WURFL_Handlers_KyoceraHandler extends WURFL_Handlers_Handler {
function __construct($wurflContext, $userAgentNormalizer = null) {
parent::__construct ( $wurflContext, $userAgentNormalizer );
}
/**
* Intercept all UAs starting with either
* "kyocera", "QC-" or "KWC-"
*
* @param string $userAgent
* @return boolean
*/
public function canHandle($userAgent) {
return WURFL_Handlers_Utils::checkIfStartsWith ( $userAgent, "kyocera" ) || WURFL_Handlers_Utils::checkIfStartsWith ( $userAgent, "QC-" ) || WURFL_Handlers_Utils::checkIfStartsWith ( $userAgent, "KWC-" );
}
protected $prefix = "KYOCERA";
}
| mikeusry/BLG6 | sites/all/libraries/wurfl/WURFL/Handlers/KyoceraHandler.php | PHP | gpl-2.0 | 1,423 |
'use strict';
angular.module('wordclashApp').controller('LoginCtrl', ['$scope', '$location', 'authService', 'ngAuthSettings', function ($scope, $location, authService, ngAuthSettings) {
$scope.loginData = {
userName: "",
password: "",
useRefreshTokens: false
};
$scope.message = "";
$scope.clicked = false;
$scope.login = function () {
$scope.clicked = true;
authService.login($scope.loginData).then(function (response) {
$scope.clicked = false;
$location.path('/arena');
},
function (err) {
$scope.clicked = false;
$scope.message = err.error_description;
});
};
$scope.authExternalProvider = function (provider) {
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.$windowScope = $scope;
var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
};
$scope.authCompletedCB = function (fragment) {
$scope.$apply(function () {
if (fragment.haslocalaccount == 'False') {
authService.logOut();
authService.externalAuthData = {
provider: fragment.provider,
userName: fragment.external_user_name,
externalAccessToken: fragment.external_access_token
};
$location.path('/associate');
}
else {
//Obtain access token and redirect to orders
var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
authService.obtainAccessToken(externalData).then(function (response) {
$location.path('/arena');
},
function (err) {
$scope.message = err.error_description;
});
}
});
}
}]); | PascalS86/wordclash | wordclash/app/login/login.controller.js | JavaScript | gpl-2.0 | 2,373 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from distutils.core import setup
setup(name = "palabre",
version = "0.6b",
description = "XML Socket Python Server",
long_description = "Flash XML Multiuser Socket Server",
author = "Célio Conort",
author_email = "palabre-dev@lists.tuxfamily.org",
url = "http://palabre.gavroche.net/",
license = "GPL, see COPYING for details",
platforms = "Linux",
packages = ["palabre","modules"],
scripts = ["scripts/palabre","setup.py"],
data_files = [('',['Palabre.py']),
("/etc", ["etc/palabre.conf"]
),
("doc",["doc/README.txt"]),
("./",["AUTHORS","COPYING","MANIFEST","MANIFEST.in","PKG-INFO"]),
("/usr/local/share/doc/palabre", ["doc/README.txt"])
]
)
| opixido/palabre | setup.py | Python | gpl-2.0 | 879 |
<?php
/**
* A class of methods related to users and their profiles.
*
* @since 1.0.0
* @package Rosh
* @subpackage Rosh/classes
*/
class Rosh_Users {
/**
* Constructor
*
* @since 1.0.0
*/
public function __construct() {}
/**
* Registers all the WordPress hooks and filters for this class.
*/
public function hooks() {
add_filter( 'user_contactmethods', array( $this, 'remove_contact_methods' ), 10, 1 );
add_filter( 'user_contactmethods', array( $this, 'add_contact_methods' ), 10, 1 );
} // hooks()
/**
* Adds contact method fields to the user profiles.
*
* @param array $contactmethods The current contact methods.
* @return array The modified contact methods.
*/
public function add_contact_methods( $contactmethods ) {
$contactmethods['linkedin'] = __( 'LinkedIn' , 'rosh' );
$contactmethods['youtube'] = __( 'YouTube' , 'rosh' );
$contactmethods['vimeo'] = __( 'Vimeo' , 'rosh' );
$contactmethods['wordpress'] = __( 'WordPress' , 'rosh' );
$contactmethods['pinterest'] = __( 'Pinterest' , 'rosh' );
$contactmethods['instagram'] = __( 'Instagram' , 'rosh' );
return $contactmethods;
} // add_contact_methods()
/**
* Removes contact method fields from the user profiles.
*
* @param array $contactmethods The current contact methods.
* @return array The modified contact methods.
*/
public function remove_contact_methods( $contactmethods ) {
unset( $contactmethods[ 'aim' ] );
unset( $contactmethods[ 'yim' ] );
unset( $contactmethods[ 'jabber' ] );
return $contactmethods;
} // remove_contact_methods()
} // class
| slushman/rosh | classes/class-users.php | PHP | gpl-2.0 | 1,656 |
using System;
using System.Collections;
using Server.Items;
using Server.Targeting;
namespace Server.Mobiles
{
[CorpseName( "o corpo de uma harpia" )]
public class Harpy : BaseCreature
{
[Constructable]
public Harpy() : base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 )
{
Name = "a harpy";
Body = 30;
BaseSoundID = 402;
SetStr( 96, 120 );
SetDex( 86, 110 );
SetInt( 51, 75 );
SetHits( 58, 72 );
SetDamage( 5, 7 );
SetDamageType( ResistanceType.Physical, 100 );
SetResistance( ResistanceType.Physical, 25, 30 );
SetResistance( ResistanceType.Fire, 10, 20 );
SetResistance( ResistanceType.Cold, 10, 30 );
SetResistance( ResistanceType.Poison, 20, 30 );
SetResistance( ResistanceType.Energy, 10, 20 );
SetSkill( SkillName.MagicResist, 50.1, 65.0 );
SetSkill( SkillName.Tactics, 70.1, 100.0 );
SetSkill( SkillName.Wrestling, 60.1, 90.0 );
Fame = 2500;
Karma = -2500;
VirtualArmor = 28;
}
public override void GenerateLoot()
{
AddLoot( LootPack.Meager, 2 );
}
public override int GetAttackSound()
{
return 916;
}
public override int GetAngerSound()
{
return 916;
}
public override int GetDeathSound()
{
return 917;
}
public override int GetHurtSound()
{
return 919;
}
public override int GetIdleSound()
{
return 918;
}
public override bool CanRummageCorpses{ get{ return true; } }
public override int Meat{ get{ return 4; } }
public override MeatType MeatType{ get{ return MeatType.Bird; } }
public override int Feathers{ get{ return 50; } }
public override bool CanFly { get { return true; } }
public Harpy( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | felladrin/runuo-pt-br | Scripts/Mobiles/Monsters/Reptile/Melee/Harpy.cs | C# | gpl-2.0 | 2,068 |
<?php // $Id: format.php 68 2009-07-31 18:23:01Z dlandau $
// format.php - course format featuring single activity
// included from view.php
$module = $course->format;
require_once($CFG->dirroot.'/mod/'.$module.'/locallib.php');
// Bounds for block widths
// more flexible for theme designers taken from theme config.php
$lmin = (empty($THEME->block_l_min_width)) ? 100 : $THEME->block_l_min_width;
$lmax = (empty($THEME->block_l_max_width)) ? 210 : $THEME->block_l_max_width;
$rmin = (empty($THEME->block_r_min_width)) ? 100 : $THEME->block_r_min_width;
$rmax = (empty($THEME->block_r_max_width)) ? 210 : $THEME->block_r_max_width;
define('BLOCK_L_MIN_WIDTH', $lmin);
define('BLOCK_L_MAX_WIDTH', $lmax);
define('BLOCK_R_MIN_WIDTH', $rmin);
define('BLOCK_R_MAX_WIDTH', $rmax);
$preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]),
BLOCK_L_MAX_WIDTH);
$preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]),
BLOCK_R_MAX_WIDTH);
$strgroups = get_string('groups');
$strgroupmy = get_string('groupmy');
$editing = $PAGE->user_is_editing();
echo '<table id="layout-table" cellspacing="0" summary="'.get_string('layouttable').'">';
echo '<tr>';
if (blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $editing) {
echo '<td style="width:'.$preferred_width_left.'px" id="left-column">';
blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT);
echo '</td>';
}
echo '<td id="middle-column">'. skip_main_destination();
$moduleformat = $module.'_course_format_display';
if (function_exists($moduleformat)) {
$moduleformat($USER,$course);
} else {
notify('The module '. $module. ' does not support single activity course format');
}
echo '</td>';
// The right column
if (blocks_have_content($pageblocks, BLOCK_POS_RIGHT) || $editing) {
echo '<td style="width:'.$preferred_width_right.'px" id="right-column">';
blocks_print_group($PAGE, $pageblocks, BLOCK_POS_RIGHT);
echo '</td>';
}
echo '</tr>';
echo '</table>';
?>
| bobpuffer/1.9.12-LAE1.3 | course/format/scorm/format.php | PHP | gpl-2.0 | 2,345 |
/*************************************************************************************
Grid physics library, www.github.com/paboyle/Grid
Source file: ./tests/Test_dwf_compressed_lanczos_reorg.cc
Copyright (C) 2017
Author: Leans heavily on Christoph Lehner's code
Author: Peter Boyle <paboyle@ph.ed.ac.uk>
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.
See the full license in the file "LICENSE" in the top level distribution directory
*************************************************************************************/
/* END LEGAL */
/*
* Reimplement the badly named "multigrid" lanczos as compressed Lanczos using the features
* in Grid that were intended to be used to support blocked Aggregates, from
*/
#include <Grid/Grid.h>
#include <Grid/algorithms/iterative/ImplicitlyRestartedLanczos.h>
using namespace std;
using namespace Grid;
using namespace Grid::QCD;
template<class Fobj,class CComplex,int nbasis>
class ProjectedHermOp : public LinearFunction<Lattice<iVector<CComplex,nbasis > > > {
public:
typedef iVector<CComplex,nbasis > CoarseSiteVector;
typedef Lattice<CoarseSiteVector> CoarseField;
typedef Lattice<CComplex> CoarseScalar; // used for inner products on fine field
typedef Lattice<Fobj> FineField;
LinearOperatorBase<FineField> &_Linop;
Aggregation<Fobj,CComplex,nbasis> &_Aggregate;
ProjectedHermOp(LinearOperatorBase<FineField>& linop, Aggregation<Fobj,CComplex,nbasis> &aggregate) :
_Linop(linop),
_Aggregate(aggregate) { };
void operator()(const CoarseField& in, CoarseField& out) {
GridBase *FineGrid = _Aggregate.FineGrid;
FineField fin(FineGrid);
FineField fout(FineGrid);
_Aggregate.PromoteFromSubspace(in,fin);
_Linop.HermOp(fin,fout);
_Aggregate.ProjectToSubspace(out,fout);
}
};
template<class Fobj,class CComplex,int nbasis>
class ProjectedFunctionHermOp : public LinearFunction<Lattice<iVector<CComplex,nbasis > > > {
public:
typedef iVector<CComplex,nbasis > CoarseSiteVector;
typedef Lattice<CoarseSiteVector> CoarseField;
typedef Lattice<CComplex> CoarseScalar; // used for inner products on fine field
typedef Lattice<Fobj> FineField;
OperatorFunction<FineField> & _poly;
LinearOperatorBase<FineField> &_Linop;
Aggregation<Fobj,CComplex,nbasis> &_Aggregate;
ProjectedFunctionHermOp(OperatorFunction<FineField> & poly,LinearOperatorBase<FineField>& linop,
Aggregation<Fobj,CComplex,nbasis> &aggregate) :
_poly(poly),
_Linop(linop),
_Aggregate(aggregate) { };
void operator()(const CoarseField& in, CoarseField& out) {
GridBase *FineGrid = _Aggregate.FineGrid;
FineField fin(FineGrid) ;fin.checkerboard =_Aggregate.checkerboard;
FineField fout(FineGrid);fout.checkerboard =_Aggregate.checkerboard;
_Aggregate.PromoteFromSubspace(in,fin);
_poly(_Linop,fin,fout);
_Aggregate.ProjectToSubspace(out,fout);
}
};
// Make serializable Lanczos params
template<class Fobj,class CComplex,int nbasis>
class CoarseFineIRL
{
public:
typedef iVector<CComplex,nbasis > CoarseSiteVector;
typedef Lattice<CComplex> CoarseScalar; // used for inner products on fine field
typedef Lattice<CoarseSiteVector> CoarseField;
typedef Lattice<Fobj> FineField;
private:
GridBase *_CoarseGrid;
GridBase *_FineGrid;
int _checkerboard;
LinearOperatorBase<FineField> & _FineOp;
Aggregation<Fobj,CComplex,nbasis> _Aggregate;
public:
CoarseFineIRL(GridBase *FineGrid,
GridBase *CoarseGrid,
LinearOperatorBase<FineField> &FineOp,
int checkerboard) :
_CoarseGrid(CoarseGrid),
_FineGrid(FineGrid),
_Aggregate(CoarseGrid,FineGrid,checkerboard),
_FineOp(FineOp),
_checkerboard(checkerboard)
{};
template<typename T> static RealD normalise(T& v)
{
RealD nn = norm2(v);
nn = ::sqrt(nn);
v = v * (1.0/nn);
return nn;
}
void testFine(void)
{
int Nk = nbasis;
_Aggregate.subspace.resize(Nk,_FineGrid);
_Aggregate.subspace[0]=1.0;
_Aggregate.subspace[0].checkerboard=_checkerboard;
normalise(_Aggregate.subspace[0]);
PlainHermOp<FineField> Op(_FineOp);
for(int k=1;k<Nk;k++){
Op(_Aggregate.subspace[k-1],_Aggregate.subspace[k]);
normalise(_Aggregate.subspace[k]);
std::cout << GridLogMessage << "testFine subspace "<<k<<" " <<norm2(_Aggregate.subspace[k])<<std::endl;
}
for(int k=0;k<Nk;k++){
std::cout << GridLogMessage << "testFine subspace "<<k<<" cb " <<_Aggregate.subspace[k].checkerboard<<std::endl;
}
_Aggregate.Orthogonalise();
}
void calcFine(RealD alpha, RealD beta,int Npoly,int Nm,RealD resid,
RealD MaxIt, RealD betastp, int MinRes)
{
assert(nbasis<=Nm);
Chebyshev<FineField> Cheby(alpha,beta,Npoly);
FunctionHermOp<FineField> ChebyOp(Cheby,_FineOp);
PlainHermOp<FineField> Op(_FineOp);
int Nk = nbasis;
std::vector<RealD> eval(Nm);
FineField src(_FineGrid); src=1.0; src.checkerboard = _checkerboard;
ImplicitlyRestartedLanczos<FineField> IRL(ChebyOp,Op,Nk,Nk,Nm,resid,MaxIt,betastp,MinRes);
_Aggregate.subspace.resize(Nm,_FineGrid);
IRL.calc(eval,_Aggregate.subspace,src,Nk,false);
_Aggregate.subspace.resize(Nk,_FineGrid);
for(int k=0;k<Nk;k++){
std::cout << GridLogMessage << "testFine subspace "<<k<<" cb " <<_Aggregate.subspace[k].checkerboard<<std::endl;
}
_Aggregate.Orthogonalise();
}
void calcCoarse(RealD alpha, RealD beta,int Npoly,
int Nk, int Nm,RealD resid,
RealD MaxIt, RealD betastp, int MinRes)
{
Chebyshev<FineField> Cheby(alpha,beta,Npoly);
ProjectedHermOp<Fobj,CComplex,nbasis> Op(_FineOp,_Aggregate);
ProjectedFunctionHermOp<Fobj,CComplex,nbasis> ChebyOp(Cheby,_FineOp,_Aggregate);
std::vector<RealD> eval(Nm);
std::vector<CoarseField> evec(Nm,_CoarseGrid);
CoarseField src(_CoarseGrid); src=1.0;
ImplicitlyRestartedLanczos<CoarseField> IRL(ChebyOp,ChebyOp,Nk,Nk,Nm,resid,MaxIt,betastp,MinRes);
IRL.calc(eval,evec,src,Nk,false);
// We got the evalues of the Cheby operator;
// Reconstruct eigenvalues of original operator via Chebyshev inverse
for (int i=0;i<Nk;i++){
RealD eval_guess;
if (i==0) eval_guess = 0;
else eval[i-1] = 0;
RealD eval_poly = eval[i];
RealD eval_op = Cheby.approxInv(eval_poly,eval_guess,100,1e-10);
std::cout << i << " Reconstructed eval = " << eval_op << " from quess " << eval_op << std::endl;
eval[i] = eval_op;
}
}
};
struct LanczosParams : Serializable {
public:
GRID_SERIALIZABLE_CLASS_MEMBERS(LanczosParams,
RealD, alpha,
RealD, beta,
int, Npoly,
int, Nk,
int, Nm,
RealD, resid,
int, MaxIt,
RealD, betastp,
int, MinRes);
};
struct CompressedLanczosParams : Serializable {
public:
GRID_SERIALIZABLE_CLASS_MEMBERS(CompressedLanczosParams,
LanczosParams, FineParams,
LanczosParams, CoarseParams,
std::vector<int>, blockSize,
std::string, config,
std::vector < std::complex<double> >, omega,
RealD, mass,
RealD, M5
);
};
int main (int argc, char ** argv) {
Grid_init(&argc,&argv);
CompressedLanczosParams Params;
{
Params.omega.resize(10);
Params.blockSize.resize(5);
XmlWriter writer("Params_template.xml");
write(writer,"Params",Params);
std::cout << GridLogMessage << " Written Params_template.xml" <<std::endl;
}
{
XmlReader reader("./Params.xml");
read(reader, "Params", Params);
}
int Ls = (int)Params.omega.size();
RealD mass = Params.mass;
RealD M5 = Params.M5;
std::vector<int> blockSize = Params.blockSize;
// Grids
GridCartesian * UGrid = SpaceTimeGrid::makeFourDimGrid(GridDefaultLatt(), GridDefaultSimd(Nd,vComplex::Nsimd()),GridDefaultMpi());
GridRedBlackCartesian * UrbGrid = SpaceTimeGrid::makeFourDimRedBlackGrid(UGrid);
GridCartesian * FGrid = SpaceTimeGrid::makeFiveDimGrid(Ls,UGrid);
GridRedBlackCartesian * FrbGrid = SpaceTimeGrid::makeFiveDimRedBlackGrid(Ls,UGrid);
std::vector<int> fineLatt = GridDefaultLatt();
int dims=fineLatt.size();
assert(blockSize.size()==dims+1);
std::vector<int> coarseLatt(dims);
std::vector<int> coarseLatt5d ;
for (int d=0;d<coarseLatt.size();d++){
coarseLatt[d] = fineLatt[d]/blockSize[d]; assert(coarseLatt[d]*blockSize[d]==fineLatt[d]);
}
std::cout << GridLogMessage<< " 5d coarse lattice is ";
for (int i=0;i<coarseLatt.size();i++){
std::cout << coarseLatt[i]<<"x";
}
int cLs = Ls/blockSize[dims]; assert(cLs*blockSize[dims]==Ls);
std::cout << cLs<<std::endl;
GridCartesian * CoarseGrid4 = SpaceTimeGrid::makeFourDimGrid(coarseLatt, GridDefaultSimd(Nd,vComplex::Nsimd()),GridDefaultMpi());
GridRedBlackCartesian * CoarseGrid4rb = SpaceTimeGrid::makeFourDimRedBlackGrid(CoarseGrid4);
GridCartesian * CoarseGrid5 = SpaceTimeGrid::makeFiveDimGrid(cLs,CoarseGrid4);
GridRedBlackCartesian * CoarseGrid5rb = SpaceTimeGrid::makeFourDimRedBlackGrid(CoarseGrid5);
// Gauge field
LatticeGaugeField Umu(UGrid);
// FieldMetaData header;
// NerscIO::readConfiguration(Umu,header,Params.config);
{
std::vector<int> seeds4({1,2,3,4});
GridParallelRNG RNG4(UGrid); RNG4.SeedFixedIntegers(seeds4);
SU3::HotConfiguration(RNG4, Umu);
}
std::cout << GridLogMessage << "Lattice dimensions: " << GridDefaultLatt() << " Ls: " << Ls << std::endl;
// ZMobius EO Operator
ZMobiusFermionR Ddwf(Umu, *FGrid, *FrbGrid, *UGrid, *UrbGrid, mass, M5, Params.omega,1.,0.);
SchurDiagTwoOperator<ZMobiusFermionR,LatticeFermion> HermOp(Ddwf);
// Eigenvector storage
LanczosParams fine =Params.FineParams;
LanczosParams coarse=Params.CoarseParams;
const int Nm1 = fine.Nm;
const int Nm2 = coarse.Nm;
std::cout << GridLogMessage << "Keep " << fine.Nk << " full vectors" << std::endl;
std::cout << GridLogMessage << "Keep " << coarse.Nk << " total vectors" << std::endl;
assert(Nm2 >= Nm1);
const int nbasis= 70;
CoarseFineIRL<vSpinColourVector,vTComplex,nbasis> IRL(FrbGrid,CoarseGrid5rb,HermOp,Odd);
std::cout << GridLogMessage << "Constructed CoarseFine IRL" << std::endl;
std::cout << GridLogMessage << "Performing fine grid IRL Nk "<< nbasis<<" Nm "<<Nm1<< std::endl;
IRL.testFine();
// IRL.calcFine(fine.alpha,fine.beta,fine.Npoly,fine.Nm,fine.resid, fine.MaxIt, fine.betastp, fine.MinRes);
std::cout << GridLogMessage << "Performing coarse grid (poly) IRL " << nbasis<<" Nm "<<Nm2<< std::endl;
IRL.calcCoarse(coarse.alpha,coarse.beta,coarse.Npoly,coarse.Nk,coarse.Nm,coarse.resid, coarse.MaxIt, coarse.betastp, coarse.MinRes);
// IRL.smoothedCoarseEigenvalues();
Grid_finalize();
}
| jch1g10/Grid | tests/lanczos/Test_dwf_compressed_lanczos_reorg_synthetic.cc | C++ | gpl-2.0 | 11,689 |
import sys
#Se le pasa la flag deseada, y devuelve lo que hay que escribir en el binario. CUIDADO CON LAS BACKSLASHES; hay que escaparlas
if len(sys.argv) != 2:
print "Syntax: python2 flag.py <FLAG>"
sys.exit(0)
flag = sys.argv[1]
i = 0
j = len(flag)-1
l = j
flag2 = ""
while (i<l+1):
if i <= l/2:
c = 7
else:
c = 10
flag2 += chr(ord(flag[j])+c)
i = i+1
j = j-1
print flag2
| 0-wHiTeHand-0/CTFs | made_faqin2k18/heap/flag.py | Python | gpl-2.0 | 413 |
package arango
import (
"encoding/json"
"fmt"
)
//Cursor represents a collection of items that you can iterate over.
//This library will produce a Cursor type whenever ArangoDb produces
//a list of objects that match a query.
type Cursor struct {
db *Database
json cursorResult
}
type cursorResult struct {
Result []json.RawMessage `json:"result"`
HasMore bool `json:"hasMore"`
Count int `json:"count"`
Error bool `json:"error"`
Code int `json:"code"`
Id string `json:"id"`
}
func (c Cursor) HasMore() bool {
return len(c.json.Result) > 0 || c.json.HasMore
}
func (c Cursor) Count() int {
return c.json.Count
}
func (c Cursor) Error() bool {
return c.json.Error
}
func (c Cursor) Code() int {
return c.json.Code
}
//Next retrieves the next item from the cursor.
//According to the arango docs :
//Note that even if hasMore returns true, the next
//call might still return no documents.
//If, however, hasMore is false, then the cursor
//is exhausted. Once the hasMore attribute has a value
//of false, the client can stop.
func (c *Cursor) Next(next interface{}) error {
if len(c.json.Result) > 0 {
err := json.Unmarshal(c.json.Result[0], next)
if err != nil {
return newError(err.Error())
}
c.json.Result = c.json.Result[1:len(c.json.Result)]
return nil
} else if c.json.Id != "" {
endpoint := fmt.Sprintf("%s/cursor/%s",
c.db.serverUrl.String(),
c.json.Id,
)
var e ArangoError
response, err := c.db.session.Put(endpoint, nil, &c.json, &e)
if err != nil {
return newError(err.Error())
}
switch response.Status() {
case 200:
if len(c.json.Result) > 0 {
err := json.Unmarshal(c.json.Result[0], next)
if err != nil {
return newError(err.Error())
}
c.json.Result = c.json.Result[1:len(c.json.Result)]
}
return nil
default:
return e
}
}
return newError("You called Next on a cursor that is invalid or doesn't have anymore results to return.")
}
func (c Cursor) Close() error {
endpoint := fmt.Sprintf("%s/cursor/%s",
c.db.serverUrl.String(),
c.json.Id,
)
var e ArangoError
response, err := c.db.session.Delete(endpoint, nil, &e)
if err != nil {
return newError(err.Error())
}
switch response.Status() {
case 202:
return nil
default:
return e
}
}
| starJammer/arango | cursor.go | GO | gpl-2.0 | 2,354 |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Api\Test\Unit\Code\Generator;
use Magento\Framework\Api\ExtensibleDataInterface;
/**
* Interface for ExtensibleSample
*/
interface ExtensibleSampleInterface extends ExtensibleDataInterface
{
/**
* @return array
*/
public function getItems();
/**
* @return string
*/
public function getName();
/**
* @return int
*/
public function getCount();
/**
* @return int
*/
public function getCreatedAt();
}
| kunj1988/Magento2 | lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/ExtensibleSampleInterface.php | PHP | gpl-2.0 | 610 |
/*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 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 "QuestDef.h"
#include "GossipDef.h"
#include "ObjectMgr.h"
#include "WorldSession.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Formulas.h"
GossipMenu::GossipMenu()
{
_menuId = 0;
}
GossipMenu::~GossipMenu()
{
ClearMenu();
}
void GossipMenu::AddMenuItem(int32 menuItemId, uint8 icon, std::string const& message, uint32 sender, uint32 action, std::string const& boxMessage, uint32 boxMoney, bool coded /*= false*/)
{
ASSERT(_menuItems.size() <= GOSSIP_MAX_MENU_ITEMS);
// Find a free new id - script case
if (menuItemId == -1)
{
menuItemId = 0;
if (!_menuItems.empty())
{
for (GossipMenuItemContainer::const_iterator itr = _menuItems.begin(); itr != _menuItems.end(); ++itr)
{
if (int32(itr->first) > menuItemId)
break;
menuItemId = itr->first + 1;
}
}
}
GossipMenuItem& menuItem = _menuItems[menuItemId];
menuItem.MenuItemIcon = icon;
menuItem.Message = message;
menuItem.IsCoded = coded;
menuItem.Sender = sender;
menuItem.OptionType = action;
menuItem.BoxMessage = boxMessage;
menuItem.BoxMoney = boxMoney;
}
/**
* @name AddMenuItem
* @brief Adds a localized gossip menu item from db by menu id and menu item id.
* @param menuId Gossip menu id.
* @param menuItemId Gossip menu item id.
* @param sender Identifier of the current menu.
* @param action Custom action given to OnGossipHello.
*/
void GossipMenu::AddMenuItem(uint32 menuId, uint32 menuItemId, uint32 sender, uint32 action)
{
/// Find items for given menu id.
GossipMenuItemsMapBounds bounds = sObjectMgr->GetGossipMenuItemsMapBounds(menuId);
/// Return if there are none.
if (bounds.first == bounds.second)
return;
/// Iterate over each of them.
for (GossipMenuItemsContainer::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
/// Find the one with the given menu item id.
if (itr->second.OptionIndex != menuItemId)
continue;
/// Store texts for localization.
std::string strOptionText = itr->second.OptionText;
std::string strBoxText = itr->second.BoxText;
/// Check need of localization.
if (GetLocale() > LOCALE_enUS)
/// Find localizations from database.
if (GossipMenuItemsLocale const* no = sObjectMgr->GetGossipMenuItemsLocale(MAKE_PAIR32(menuId, menuItemId)))
{
/// Translate texts if there are any.
ObjectMgr::GetLocaleString(no->OptionText, GetLocale(), strOptionText);
ObjectMgr::GetLocaleString(no->BoxText, GetLocale(), strBoxText);
}
/// Add menu item with existing method. Menu item id -1 is also used in ADD_GOSSIP_ITEM macro.
AddMenuItem(-1, itr->second.OptionIcon, strOptionText, sender, action, strBoxText, itr->second.BoxMoney, itr->second.BoxCoded);
}
}
void GossipMenu::AddGossipMenuItemData(uint32 menuItemId, uint32 gossipActionMenuId, uint32 gossipActionPoi)
{
GossipMenuItemData& itemData = _menuItemData[menuItemId];
itemData.GossipActionMenuId = gossipActionMenuId;
itemData.GossipActionPoi = gossipActionPoi;
}
uint32 GossipMenu::GetMenuItemSender(uint32 menuItemId) const
{
GossipMenuItemContainer::const_iterator itr = _menuItems.find(menuItemId);
if (itr == _menuItems.end())
return 0;
return itr->second.Sender;
}
uint32 GossipMenu::GetMenuItemAction(uint32 menuItemId) const
{
GossipMenuItemContainer::const_iterator itr = _menuItems.find(menuItemId);
if (itr == _menuItems.end())
return 0;
return itr->second.OptionType;
}
bool GossipMenu::IsMenuItemCoded(uint32 menuItemId) const
{
GossipMenuItemContainer::const_iterator itr = _menuItems.find(menuItemId);
if (itr == _menuItems.end())
return false;
return itr->second.IsCoded;
}
void GossipMenu::ClearMenu()
{
_menuItems.clear();
_menuItemData.clear();
}
PlayerMenu::PlayerMenu(WorldSession* session) : _session(session)
{
if (_session)
_gossipMenu.SetLocale(_session->GetSessionDbLocaleIndex());
}
PlayerMenu::~PlayerMenu()
{
ClearMenus();
}
void PlayerMenu::ClearMenus()
{
_gossipMenu.ClearMenu();
_questMenu.ClearMenu();
}
void PlayerMenu::SendGossipMenu(uint32 titleTextId, uint64 objectGUID) const
{
WorldPacket data(SMSG_GOSSIP_MESSAGE, 100); // guess size
data << uint64(objectGUID);
data << uint32(_gossipMenu.GetMenuId()); // new 2.4.0
data << uint32(titleTextId);
data << uint32(_gossipMenu.GetMenuItemCount()); // max count 0x10
for (GossipMenuItemContainer::const_iterator itr = _gossipMenu.GetMenuItems().begin(); itr != _gossipMenu.GetMenuItems().end(); ++itr)
{
GossipMenuItem const& item = itr->second;
data << uint32(itr->first);
data << uint8(item.MenuItemIcon);
data << uint8(item.IsCoded); // makes pop up box password
data << uint32(item.BoxMoney); // money required to open menu, 2.0.3
data << item.Message; // text for gossip item
data << item.BoxMessage; // accept text (related to money) pop up box, 2.0.3
}
data << uint32(_questMenu.GetMenuItemCount()); // max count 0x20
for (uint32 iI = 0; iI < _questMenu.GetMenuItemCount(); ++iI)
{
QuestMenuItem const& item = _questMenu.GetItem(iI);
uint32 questID = item.QuestId;
Quest const* quest = sObjectMgr->GetQuestTemplate(questID);
data << uint32(questID);
data << uint32(item.QuestIcon);
data << int32(quest->GetQuestLevel());
data << uint32(quest->GetFlags()); // 3.3.3 quest flags
data << uint8(0); // 3.3.3 changes icon: blue question or yellow exclamation
std::string title = quest->GetTitle();
int locale = _session->GetSessionDbLocaleIndex();
if (locale >= 0)
if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(questID))
ObjectMgr::GetLocaleString(localeData->Title, locale, title);
data << title; // max 0x200
}
_session->SendPacket(&data);
}
void PlayerMenu::SendCloseGossip() const
{
WorldPacket data(SMSG_GOSSIP_COMPLETE, 0);
_session->SendPacket(&data);
}
void PlayerMenu::SendPointOfInterest(uint32 poiId) const
{
PointOfInterest const* poi = sObjectMgr->GetPointOfInterest(poiId);
if (!poi)
{
sLog->outErrorDb("Request to send non-existing POI (Id: %u), ignored.", poiId);
return;
}
std::string iconText = poi->icon_name;
int32 locale = _session->GetSessionDbLocaleIndex();
if (locale >= 0)
if (PointOfInterestLocale const* localeData = sObjectMgr->GetPointOfInterestLocale(poiId))
ObjectMgr::GetLocaleString(localeData->IconName, locale, iconText);
WorldPacket data(SMSG_GOSSIP_POI, 4 + 4 + 4 + 4 + 4 + 10); // guess size
data << uint32(poi->flags);
data << float(poi->x);
data << float(poi->y);
data << uint32(poi->icon);
data << uint32(poi->data);
data << iconText;
_session->SendPacket(&data);
}
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
QuestMenu::QuestMenu()
{
_questMenuItems.reserve(16); // can be set for max from most often sizes to speedup push_back and less memory use
}
QuestMenu::~QuestMenu()
{
ClearMenu();
}
void QuestMenu::AddMenuItem(uint32 QuestId, uint8 Icon)
{
if (!sObjectMgr->GetQuestTemplate(QuestId))
return;
ASSERT(_questMenuItems.size() <= GOSSIP_MAX_MENU_ITEMS);
QuestMenuItem questMenuItem;
questMenuItem.QuestId = QuestId;
questMenuItem.QuestIcon = Icon;
_questMenuItems.push_back(questMenuItem);
}
bool QuestMenu::HasItem(uint32 questId) const
{
for (QuestMenuItemList::const_iterator i = _questMenuItems.begin(); i != _questMenuItems.end(); ++i)
if (i->QuestId == questId)
return true;
return false;
}
void QuestMenu::ClearMenu()
{
_questMenuItems.clear();
}
void PlayerMenu::SendQuestGiverQuestList(QEmote eEmote, const std::string& Title, uint64 npcGUID)
{
WorldPacket data(SMSG_QUESTGIVER_QUEST_LIST, 100); // guess size
data << uint64(npcGUID);
data << Title;
data << uint32(eEmote._Delay); // player emote
data << uint32(eEmote._Emote); // NPC emote
size_t count_pos = data.wpos();
data << uint8 (_questMenu.GetMenuItemCount());
uint32 count = 0;
for (; count < _questMenu.GetMenuItemCount(); ++count)
{
QuestMenuItem const& qmi = _questMenu.GetItem(count);
uint32 questID = qmi.QuestId;
if (Quest const* quest = sObjectMgr->GetQuestTemplate(questID))
{
std::string title = quest->GetTitle();
int loc_idx = _session->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
if (QuestLocale const* ql = sObjectMgr->GetQuestLocale(questID))
ObjectMgr::GetLocaleString(ql->Title, loc_idx, title);
data << uint32(questID);
data << uint32(qmi.QuestIcon);
data << int32(quest->GetQuestLevel());
data << uint32(quest->GetFlags()); // 3.3.3 quest flags
data << uint8(0); // 3.3.3 changes icon: blue question or yellow exclamation
data << title;
}
}
data.put<uint8>(count_pos, count);
_session->SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_LIST NPC Guid=%u", GUID_LOPART(npcGUID));
}
void PlayerMenu::SendQuestGiverStatus(uint8 questStatus, uint64 npcGUID) const
{
WorldPacket data(SMSG_QUESTGIVER_STATUS, 9);
data << uint64(npcGUID);
data << uint8(questStatus);
_session->SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_STATUS NPC Guid=%u, status=%u", GUID_LOPART(npcGUID), questStatus);
}
void PlayerMenu::SendQuestGiverQuestDetails(Quest const* quest, uint64 npcGUID, bool activateAccept) const
{
std::string questTitle = quest->GetTitle();
std::string questDetails = quest->GetDetails();
std::string questObjectives = quest->GetObjectives();
std::string questEndText = quest->GetEndText();
int32 locale = _session->GetSessionDbLocaleIndex();
if (locale >= 0)
{
if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId()))
{
ObjectMgr::GetLocaleString(localeData->Title, locale, questTitle);
ObjectMgr::GetLocaleString(localeData->Details, locale, questDetails);
ObjectMgr::GetLocaleString(localeData->Objectives, locale, questObjectives);
ObjectMgr::GetLocaleString(localeData->EndText, locale, questEndText);
}
}
WorldPacket data(SMSG_QUESTGIVER_QUEST_DETAILS, 100); // guess size
data << uint64(npcGUID);
data << uint64(0); // wotlk, something todo with quest sharing?
data << uint32(quest->GetQuestId());
data << questTitle;
data << questDetails;
data << questObjectives;
data << uint8(activateAccept ? 1 : 0); // auto finish
data << uint32(quest->GetFlags()); // 3.3.3 questFlags
data << uint32(quest->GetSuggestedPlayers());
data << uint8(0); // IsFinished? value is sent back to server in quest accept packet
if (quest->HasFlag(QUEST_FLAGS_HIDDEN_REWARDS))
{
data << uint32(0); // Rewarded chosen items hidden
data << uint32(0); // Rewarded items hidden
data << uint32(0); // Rewarded money hidden
data << uint32(0); // Rewarded XP hidden
}
else
{
data << uint32(quest->GetRewChoiceItemsCount());
for (uint32 i=0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
{
if (!quest->RewardChoiceItemId[i])
continue;
data << uint32(quest->RewardChoiceItemId[i]);
data << uint32(quest->RewardChoiceItemCount[i]);
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RewardChoiceItemId[i]))
data << uint32(itemTemplate->DisplayInfoID);
else
data << uint32(0x00);
}
data << uint32(quest->GetRewItemsCount());
for (uint32 i=0; i < QUEST_REWARDS_COUNT; ++i)
{
if (!quest->RewardItemId[i])
continue;
data << uint32(quest->RewardItemId[i]);
data << uint32(quest->RewardItemIdCount[i]);
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RewardItemId[i]))
data << uint32(itemTemplate->DisplayInfoID);
else
data << uint32(0);
}
data << uint32(quest->GetRewOrReqMoney());
data << uint32(quest->XPValue(_session->GetPlayer()) * _session->GetPlayer()->CalculateOverrideRate(RATE_OVERRIDE_XP_QUEST, sWorld->getRate(RATE_XP_QUEST)));
}
// rewarded honor points. Multiply with 10 to satisfy client
data << 10 * Trinity::Honor::hk_honor_at_level(_session->GetPlayer()->getLevel(), quest->GetRewHonorMultiplier());
data << float(0.0f); // new 3.3.0, honor multiplier?
data << uint32(quest->GetRewSpell()); // reward spell, this spell will display (icon) (casted if RewSpellCast == 0)
data << int32(quest->GetRewSpellCast()); // casted spell
data << uint32(quest->GetCharTitleId()); // CharTitleId, new 2.4.0, player gets this title (id from CharTitles)
data << uint32(quest->GetBonusTalents()); // bonus talents
data << uint32(quest->GetRewArenaPoints()); // reward arena points
data << uint32(0); // unk
for (uint32 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
data << uint32(quest->RewardFactionId[i]);
for (uint32 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
data << int32(quest->RewardFactionValueId[i]);
for (uint32 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
data << int32(quest->RewardFactionValueIdOverride[i]);
data << uint32(QUEST_EMOTE_COUNT);
for (uint32 i = 0; i < QUEST_EMOTE_COUNT; ++i)
{
data << uint32(quest->DetailsEmote[i]);
data << uint32(quest->DetailsEmoteDelay[i]); // DetailsEmoteDelay (in ms)
}
_session->SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_QUEST_DETAILS NPCGuid=%u, questid=%u", GUID_LOPART(npcGUID), quest->GetQuestId());
}
void PlayerMenu::SendQuestQueryResponse(Quest const* quest) const
{
std::string questTitle = quest->GetTitle();
std::string questDetails = quest->GetDetails();
std::string questObjectives = quest->GetObjectives();
std::string questEndText = quest->GetEndText();
std::string questCompletedText = quest->GetCompletedText();
std::string questObjectiveText[QUEST_OBJECTIVES_COUNT];
for (uint32 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
questObjectiveText[i] = quest->ObjectiveText[i];
int32 locale = _session->GetSessionDbLocaleIndex();
if (locale >= 0)
{
if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId()))
{
ObjectMgr::GetLocaleString(localeData->Title, locale, questTitle);
ObjectMgr::GetLocaleString(localeData->Details, locale, questDetails);
ObjectMgr::GetLocaleString(localeData->Objectives, locale, questObjectives);
ObjectMgr::GetLocaleString(localeData->EndText, locale, questEndText);
ObjectMgr::GetLocaleString(localeData->CompletedText, locale, questCompletedText);
for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
ObjectMgr::GetLocaleString(localeData->ObjectiveText[i], locale, questObjectiveText[i]);
}
}
WorldPacket data(SMSG_QUEST_QUERY_RESPONSE, 100); // guess size
data << uint32(quest->GetQuestId()); // quest id
data << uint32(quest->GetQuestMethod()); // Accepted values: 0, 1 or 2. 0 == IsAutoComplete() (skip objectives/details)
data << uint32(quest->GetQuestLevel()); // may be -1, static data, in other cases must be used dynamic level: Player::GetQuestLevel (0 is not known, but assuming this is no longer valid for quest intended for client)
data << uint32(quest->GetMinLevel()); // min level
data << uint32(quest->GetZoneOrSort()); // zone or sort to display in quest log
data << uint32(quest->GetType()); // quest type
data << uint32(quest->GetSuggestedPlayers()); // suggested players count
data << uint32(quest->GetRepObjectiveFaction()); // shown in quest log as part of quest objective
data << uint32(quest->GetRepObjectiveValue()); // shown in quest log as part of quest objective
data << uint32(quest->GetRepObjectiveFaction2()); // shown in quest log as part of quest objective OPPOSITE faction
data << uint32(quest->GetRepObjectiveValue2()); // shown in quest log as part of quest objective OPPOSITE faction
data << uint32(quest->GetNextQuestInChain()); // client will request this quest from NPC, if not 0
data << uint32(quest->GetXPId()); // used for calculating rewarded experience
if (quest->HasFlag(QUEST_FLAGS_HIDDEN_REWARDS))
data << uint32(0); // Hide money rewarded
else
data << uint32(quest->GetRewOrReqMoney()); // reward money (below max lvl)
data << uint32(quest->GetRewMoneyMaxLevel()); // used in XP calculation at client
data << uint32(quest->GetRewSpell()); // reward spell, this spell will display (icon) (casted if RewSpellCast == 0)
data << int32(quest->GetRewSpellCast()); // casted spell
// rewarded honor points
data << Trinity::Honor::hk_honor_at_level(_session->GetPlayer()->getLevel(), quest->GetRewHonorMultiplier());
data << float(0); // new reward honor (multipled by ~62 at client side)
data << uint32(quest->GetSrcItemId()); // source item id
data << uint32(quest->GetFlags() & 0xFFFF); // quest flags
data << uint32(quest->GetCharTitleId()); // CharTitleId, new 2.4.0, player gets this title (id from CharTitles)
data << uint32(quest->GetPlayersSlain()); // players slain
data << uint32(quest->GetBonusTalents()); // bonus talents
data << uint32(quest->GetRewArenaPoints()); // bonus arena points
data << uint32(0); // review rep show mask
if (quest->HasFlag(QUEST_FLAGS_HIDDEN_REWARDS))
{
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
data << uint32(0) << uint32(0);
for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
data << uint32(0) << uint32(0);
}
else
{
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
{
data << uint32(quest->RewardItemId[i]);
data << uint32(quest->RewardItemIdCount[i]);
}
for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
{
data << uint32(quest->RewardChoiceItemId[i]);
data << uint32(quest->RewardChoiceItemCount[i]);
}
}
for (uint32 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward factions ids
data << uint32(quest->RewardFactionId[i]);
for (uint32 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // columnid+1 QuestFactionReward.dbc?
data << int32(quest->RewardFactionValueId[i]);
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // unk (0)
data << int32(quest->RewardFactionValueIdOverride[i]);
data << quest->GetPointMapId();
data << quest->GetPointX();
data << quest->GetPointY();
data << quest->GetPointOpt();
data << questTitle;
data << questObjectives;
data << questDetails;
data << questEndText;
data << questCompletedText; // display in quest objectives window once all objectives are completed
for (uint32 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
{
if (quest->RequiredNpcOrGo[i] < 0)
data << uint32((quest->RequiredNpcOrGo[i] * (-1)) | 0x80000000); // client expects gameobject template id in form (id|0x80000000)
else
data << uint32(quest->RequiredNpcOrGo[i]);
data << uint32(quest->RequiredNpcOrGoCount[i]);
data << uint32(quest->RequiredSourceItemId[i]);
data << uint32(0); // req source count?
}
for (uint32 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
data << uint32(quest->RequiredItemId[i]);
data << uint32(quest->RequiredItemCount[i]);
}
for (uint32 i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
data << questObjectiveText[i];
_session->SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUEST_QUERY_RESPONSE questid=%u", quest->GetQuestId());
}
void PlayerMenu::SendQuestGiverOfferReward(Quest const* quest, uint64 npcGUID, bool enableNext) const
{
std::string questTitle = quest->GetTitle();
std::string questOfferRewardText = quest->GetOfferRewardText();
int locale = _session->GetSessionDbLocaleIndex();
if (locale >= 0)
{
if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId()))
{
ObjectMgr::GetLocaleString(localeData->Title, locale, questTitle);
ObjectMgr::GetLocaleString(localeData->OfferRewardText, locale, questOfferRewardText);
}
}
WorldPacket data(SMSG_QUESTGIVER_OFFER_REWARD, 50); // guess size
data << uint64(npcGUID);
data << uint32(quest->GetQuestId());
data << questTitle;
data << questOfferRewardText;
data << uint8(enableNext ? 1 : 0); // Auto Finish
data << uint32(quest->GetFlags()); // 3.3.3 questFlags
data << uint32(quest->GetSuggestedPlayers()); // SuggestedGroupNum
uint32 emoteCount = 0;
for (uint32 i = 0; i < QUEST_EMOTE_COUNT; ++i)
{
if (quest->OfferRewardEmote[i] <= 0)
break;
++emoteCount;
}
data << emoteCount; // Emote Count
for (uint32 i = 0; i < emoteCount; ++i)
{
data << uint32(quest->OfferRewardEmoteDelay[i]); // Delay Emote
data << uint32(quest->OfferRewardEmote[i]);
}
data << uint32(quest->GetRewChoiceItemsCount());
for (uint32 i=0; i < quest->GetRewChoiceItemsCount(); ++i)
{
data << uint32(quest->RewardChoiceItemId[i]);
data << uint32(quest->RewardChoiceItemCount[i]);
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RewardChoiceItemId[i]))
data << uint32(itemTemplate->DisplayInfoID);
else
data << uint32(0);
}
data << uint32(quest->GetRewItemsCount());
for (uint32 i = 0; i < quest->GetRewItemsCount(); ++i)
{
data << uint32(quest->RewardItemId[i]);
data << uint32(quest->RewardItemIdCount[i]);
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RewardItemId[i]))
data << uint32(itemTemplate->DisplayInfoID);
else
data << uint32(0);
}
data << uint32(quest->GetRewOrReqMoney());
data << uint32(quest->XPValue(_session->GetPlayer()) * _session->GetPlayer()->CalculateOverrideRate(RATE_OVERRIDE_XP_QUEST, sWorld->getRate(RATE_XP_QUEST)));
// rewarded honor points. Multiply with 10 to satisfy client
data << 10 * Trinity::Honor::hk_honor_at_level(_session->GetPlayer()->getLevel(), quest->GetRewHonorMultiplier());
data << float(0); // unk, honor multiplier?
data << uint32(0x08); // unused by client?
data << uint32(quest->GetRewSpell()); // reward spell, this spell will display (icon) (casted if RewSpellCast == 0)
data << int32(quest->GetRewSpellCast()); // casted spell
data << uint32(0); // unknown
data << uint32(quest->GetBonusTalents()); // bonus talents
data << uint32(quest->GetRewArenaPoints()); // arena points
data << uint32(0);
for (uint32 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward factions ids
data << uint32(quest->RewardFactionId[i]);
for (uint32 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // columnid in QuestFactionReward.dbc (zero based)?
data << int32(quest->RewardFactionValueId[i]);
for (uint32 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward reputation override?
data << uint32(quest->RewardFactionValueIdOverride[i]);
_session->SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_OFFER_REWARD NPCGuid=%u, questid=%u", GUID_LOPART(npcGUID), quest->GetQuestId());
}
void PlayerMenu::SendQuestGiverRequestItems(Quest const* quest, uint64 npcGUID, bool canComplete, bool closeOnCancel) const
{
// We can always call to RequestItems, but this packet only goes out if there are actually
// items. Otherwise, we'll skip straight to the OfferReward
std::string questTitle = quest->GetTitle();
std::string requestItemsText = quest->GetRequestItemsText();
int32 locale = _session->GetSessionDbLocaleIndex();
if (locale >= 0)
{
if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId()))
{
ObjectMgr::GetLocaleString(localeData->Title, locale, questTitle);
ObjectMgr::GetLocaleString(localeData->RequestItemsText, locale, requestItemsText);
}
}
if (!quest->GetReqItemsCount() && canComplete)
{
SendQuestGiverOfferReward(quest, npcGUID, true);
return;
}
WorldPacket data(SMSG_QUESTGIVER_REQUEST_ITEMS, 50); // guess size
data << uint64(npcGUID);
data << uint32(quest->GetQuestId());
data << questTitle;
data << requestItemsText;
data << uint32(0x00); // unknown
if (canComplete)
data << quest->GetCompleteEmote();
else
data << quest->GetIncompleteEmote();
// Close Window after cancel
if (closeOnCancel)
data << uint32(0x01);
else
data << uint32(0x00);
data << uint32(quest->GetFlags()); // 3.3.3 questFlags
data << uint32(quest->GetSuggestedPlayers()); // SuggestedGroupNum
// Required Money
data << uint32(quest->GetRewOrReqMoney() < 0 ? -quest->GetRewOrReqMoney() : 0);
data << uint32(quest->GetReqItemsCount());
for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (!quest->RequiredItemId[i])
continue;
data << uint32(quest->RequiredItemId[i]);
data << uint32(quest->RequiredItemCount[i]);
if (ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(quest->RequiredItemId[i]))
data << uint32(itemTemplate->DisplayInfoID);
else
data << uint32(0);
}
if (!canComplete)
data << uint32(0x00);
else
data << uint32(0x03);
data << uint32(0x04);
data << uint32(0x08);
data << uint32(0x10);
_session->SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_QUESTGIVER_REQUEST_ITEMS NPCGuid=%u, questid=%u", GUID_LOPART(npcGUID), quest->GetQuestId());
}
| GiR-Zippo/Strawberry335 | src/server/game/Entities/Creature/GossipDef.cpp | C++ | gpl-2.0 | 29,379 |
<?php
/*
* Polish (Polski) (canonical list and phrasing)
*/
$lang = array();
//
// Date Format
// %d = day, %m = month, %y = year, %H = hour, %M = minutes
// for a complete list, see http://www.php.net/strftime
//
$lang['date_format'] = '%d/%m/%y %H:%M';
// CharSet
$lang['default_char_set'] = 'iso-8859-2';
// User-friendly names to system folders
$lang['inbox_extended'] = 'Otrzymane';
$lang['sent_extended'] = 'Wys³ane';
$lang['trash_extended'] = 'Kosz';
$lang['spam_extended'] = 'Folderu ze spamem';
$lang['drafts_extended'] = 'Projekty';
// Navigation texts
$lang['pages_text'] = 'Pages';
$lang['first_text'] = 'First';
$lang['previous_text'] = 'Poprzednia';
$lang['next_text'] = 'Nastêpna';
$lang['last_text'] = 'Last';
$lang['total_text'] = 'Total';
// Mail Server Errors
$lang['err_login_msg'] = 'błąd logowania';
$lang['err_system_msg'] = 'błąd systemowy';
$lang['error_login'] = 'Proszę sprawdzić Nazwa użytkownika lub hasło i spróbuj ponownie';
$lang['error_connect'] = 'Nie mogê po³±czyæ siê z serwerem';
$lang['error_retrieving'] = 'Nie mogê odczytaæ wiadomo¶ci';
$lang['error_session_expired'] = 'Sesja wygasła, zaloguj się ponownie';
$lang['error_other'] = 'B³±d - proszê skontaktowaæ siê z administratorem';
// Invalid name of mailbox
$lang['error_invalid_name'] = 'Z³a nazwa - u¿ywaj tylko takich znaków: A-Z, 0-9, .-';
// Validations when sending mails
$lang['error_no_recipients'] = 'Musisz podaæ odbiorcê poczty';
$lang['error_compose_invalid_mail1_s'] = 'Podany adres e-mail jest nieprawid³owy!';
$lang['error_compose_invalid_mail1_p'] = 'Podane adresy e-mail s± nieprawid³owe!';
$lang['error_compose_invalid_mail2_s'] = 'Zanim wyslesz wiadomodc,\rupewnij sie czy wszelkie dane sa prawidlowe. ';
$lang['error_compose_invalid_mail2_p'] = 'Zanim wyslesz wiadomo¶ci, \rupewnij sie czy wszelkie dane sa prawidlowe.';
// Confirmation of delete
$lang['confirm_delete'] = 'Czy jeste¶ pewien ¿e chcesz skasowaæ t± wiadomo¶æ?';
// If the message no have a subject or sender
$lang['no_subject_text'] = '[Bez tytu³u]';
$lang['no_sender_text'] = '[Nadawca nieznany]';
$lang['no_recipient_text'] = '[Odbiorca nieznany]';
// If the quota limit was exceeded
$lang['quota_exceeded'] = 'Twój limit dyskowy zosta³ przekroczony.\rProszê skasuj stare wiadomo¶ci i spróbuj ponownie';
$lang['quota_usage_info'] = 'Limit dyskowy';
$lang['quota_usage_used'] = 'Zajête';
$lang['quota_usage_of'] = 'z';
$lang['quota_usage_avail'] = 'dostêpnych';
// Menu
$lang['messages_mnu'] = 'Wiadomo¶ci';
$lang['read_menu'] = 'Read E-Mail(s)';
$lang['compose_mnu'] = 'Komponuj';
$lang['refresh_mnu'] = 'Od¶wie¿';
$lang['folders_mnu'] = 'Foldery';
$lang['search_mnu'] = 'Szukaj';
$lang['address_mnu'] = 'Adresy';
$lang['empty_trash_mnu'] = 'Opró¿nij Kosz';
$lang['prefs_mnu'] = 'Preferencje';
$lang['logoff_mnu'] = 'Wyloguj';
// Reply
$lang['reply_prefix'] = 'Odp:';
$lang['forward_prefix'] = 'Fw:';
$lang['reply_delimiter'] = '--------- Wiadomo¶æ oryginalna --------';
$lang['reply_from_hea'] = 'Od:';
$lang['reply_to_hea'] = 'Do:';
$lang['reply_cc_hea'] = 'Cc:';
$lang['reply_date_hea'] = 'Data:';
$lang['reply_subject_hea'] = 'Temat:';
// done
// page-specific vars
// [Headers]
$lang['key_hea'] = 'Typ';
$lang['value_hea'] = 'Waro¶æ';
// [Folders]
$lang['fld_name_hea'] = 'Folder';
$lang['fld_messages_hea'] = 'Wiadomo¶ci';
$lang['fld_size_hea'] = 'Rozmiar';
$lang['fld_empty_hea'] = 'Opró¿nij';
$lang['fld_delete_hea'] = 'Usuñ';
$lang['fld_total'] = 'Wszystkie:';
$lang['fld_make_new'] = 'Utwórz nowy folder';
$lang['folders_to'] = 'Foldery dla';
// [MessageList]
$lang['messages_to'] = 'Wiadomo¶ci dla ';
$lang['no_messages'] = 'Brak wiadomo¶ci w folderze';
$lang['delete_selected_mnu'] = 'Usuñ zaznaczone';
$lang['move_selected_mnu'] = 'Przenie¶ zaznaczone do';
$lang['mark_selected_mnu'] = 'Mark as read'; // FIXME: need translation
$lang['unmark_selected_mnu'] = 'Mark as unread'; // FIXME: need translation
$lang['move_selected_to_trash_mnu'] = 'Move to Trash'; // FIXME: need translation
$lang['delete_mnu'] = 'Usuñ';
$lang['move_mnu'] = 'Przenie¶ do';
$lang['subject_hea'] = 'Temat:';
$lang['from_hea'] = 'Od:';
$lang['to_hea'] = 'Do:';
$lang['date_hea'] = 'Data:';
$lang['size_hea'] = 'Rozmiar';
$lang['have_spam'] = 'You have Spam (check Spam folder)'; // FIXME: need translation
$lang['msg_you_have'] = 'Masz';
$lang['msg_message'] = 'wiadomo¶æ';
$lang['msg_messages'] = 'wiadomo¶ci';
$lang['msg_more_unread'] = 'nieprzeczytane';
$lang['msg_one_unread'] = 'nieprzeczytan±';
$lang['msg_none_unread'] = 'wszystkie przeczytane';
$lang['msg_in_the_folder'] = 'w folderze';
// [Login]
$lang['lgn_title'] = 'Logowanie';
$lang['lgn_welcome_msg'] = 'Informacje Logowania';
$lang['lng_user_email'] = 'E-mail';
$lang['lng_user_name'] = 'Login';
$lang['lng_user_pwd'] = 'Has³o';
$lang['lng_server'] = 'Server';
$lang['lng_theme'] = 'Wygl±d';
$lang['lng_language'] = 'Jêzyk';
$lang['lng_login_btn'] = 'Zaloguj >>';
$lang['lng_cookie_not_enabled'] = 'Cookies must be enabled'; // FIXME: need translation
$lang['lng_cookie_not_valid'] = 'Cookie Security Check Failed'; // FIXME: need translation
// [Newmessage]
$lang['newmsg_title'] = 'Compose mail';
$lang['to_hea'] = 'Do:';
$lang['cc_hea'] = 'Cc:';
$lang['bcc_hea'] = 'Bcc:';
$lang['subject_hea'] = 'Temat:';
$lang['address_tip'] = 'Wybierz';
$lang['attach_hea'] = 'Za³±czniki:';
$lang['attch_add_new'] = 'Dodaj nowy za³±cznik';
$lang['attch_name_hea'] = 'Nazwa';
$lang['attch_size'] = 'Rozmiar';
$lang['attch_type_hea'] = 'Typ';
$lang['attch_dele_hea'] = 'Usuñ';
$lang['attch_no_hea'] = 'Nie ma za³±czników';
$lang['add_signature'] = 'Dodaj sygnaturê';
$lang['send_text'] = 'Wy¶lij';
$lang['result_error'] = 'Wys³anie wiadomo¶ci by³o niemo¿liwe!';
$lang['result_success'] = 'Wiadomo¶æ zosta³a wys³ana';
$lang['nav_continue'] = 'Dalej';
$lang['nav_back'] = 'Powrót';
$lang['up_title'] = 'Dodawanie za³±czników';
$lang['up_information_text'] = 'Wybierz plik';
$lang['up_button_text'] = 'Dodaj';
$lang['require_receipt'] = 'Return receipt';
$lang['priority_text'] = 'Priorytet';
$lang['priority_low'] = 'Niski';
$lang['priority_normal'] = '¦redni';
$lang['priority_high'] = 'Wysoki';
// [Preferences]
$lang['prf_title'] = 'Preferencje';
$lang['prf_general_title'] = 'Informacje podstawowe';
$lang['prf_name'] = 'Nazwa';
$lang['prf_reply_to'] = 'Adres zwrotny';
$lang['prf_time_zone'] = 'Strefa czasowa';
$lang['prf_trash_title'] = 'Kosz';
$lang['prf_save_to_trash'] = 'Przenie¶ <b>usuniête</b> wiadomo¶ci do foldera';
$lang['prf_save_only_read'] = 'Zapisuj tylko <b>przeczytane</b> wiadomo¶ci w folderze';
$lang['prf_empty_on_exit'] = '<b>Opró¿nij</b> kosz przy wyj¶ciu';
$lang['prf_empty_spam_on_exit'] = '<b>Empty</b> Spam folder when you logout';
$lang['prf_unmark_read_on_exit'] = 'Reset READ messages as UNREAD when you logout';
$lang['prf_sent_title'] = 'Wys³ane wiadomo¶ci';
$lang['prf_save_sent'] = 'Zapisz <b>wys³ane</b> wiadomo¶ci w folderze ';
$lang['prf_messages_title'] = 'Wiadomo¶ci';
$lang['prf_page_limit'] = 'Liczba wiadomo¶ci na stronie';
$lang['prf_signature_title'] = 'Sygnatura';
$lang['prf_signature'] = 'Sygnatura';
$lang['prf_auto_add_sign'] = 'Dodawaj sygnaturê do wszystkich wysy³anych wiadomo¶ci ';
$lang['prf_save_button'] = 'Zapisz';
$lang['prf_display_images'] = 'Pokazuj za³±czone obrazki';
$lang['prf_default_editor_mode'] = 'Domy¶lny tryb edycji';
$lang['prf_default_editor_mode_text'] = '"Tryb tekstowy"';
$lang['prf_default_editor_mode_html'] = '"Edytor HTML (Tylko dla przegl±darek IE5 lub nowszych)"';
$lang['prf_time_to_refesh'] = 'Czêstotliwo¶æ od¶wierzania wiadomo¶ci (w minutach)';
$lang['prf_spam_level'] = 'SPAM sensitivity (0 = Disabled, 1 = Very High, 9 = Very Low)'; // FIXME: need translation
$lang['prf_auto_require_receipt'] = 'Require read receipt by default'; // FIXME: need translation
$lang['prf_keep_on_server'] = 'E-mail na serwerze przechowywać - żadnych folderów lokalnych';
$lang['prf_msg_saved'] = 'Preferences saved'; // FIXME: need translation
// filters
$lang['filter_title'] = 'Filtry';
$lang['filter_new'] = 'Utwórz filtr';
$lang['filter_desc'] = 'Wybierz kryteria wyszukiwania i działania dla przychodzących wiadomości';
$lang['filter_list'] = 'Aktualne filtry';
$lang['filter_field_from'] = 'Z';
$lang['filter_field_to'] = 'W';
$lang['filter_field_subject'] = 'Temat';
$lang['filter_field_header'] = 'Nagłówek';
$lang['filter_field_body'] = 'ciała';
$lang['filter_type_move'] = 'Ruch';
$lang['filter_type_delete'] = 'Usuń';
$lang['filter_type_mark'] = 'Mark przeczytać';
$lang['filter_add'] = 'Dodaj filtr';
$lang['filter_delete'] = 'Usuń';
$lang['filter_delete_selected'] = 'Usuń wybrane filtry';
$lang['filter_field'] = 'Filtr na pole';
$lang['filter_match'] = 'Szukaj';
$lang['filter_type'] = 'Akcja';
$lang['filter_folder'] = 'Folder docelowy';
$lang['filter_msg_nofilters'] = 'Brak dostępnych filtrów.';
$lang['filter_msg_added'] = 'Filtr dodanej';
$lang['filter_msg_deleted'] = 'Filtr usunięte';
// [Catch]
$lang['ctc_title'] = 'Dodaj adres';
$lang['ctc_information'] = 'Wy¶wietlane s± wy³±cznie kontakty, które znajduj± siê w ki±¿ce adresowej';
$lang['ctc_name'] = 'Nazwa';
$lang['ctc_email'] = 'E-mail';
$lang['ctc_no_address'] = 'Brak kontaktów w ksi±¿ce adresowej';
$lang['ctc_close'] = 'Zamknij';
$lang['ctc_save'] = 'Zapisz';
// [Readmsg]
$lang['next_mnu'] = 'Nastêpna';
$lang['previous_mnu'] = 'Poprzednia';
$lang['back_mnu'] = 'Powrót';
$lang['reply_mnu'] = 'Odpowiedz';
$lang['reply_all_mnu'] = 'Odpowiedz wszystkim';
$lang['forward_mnu'] = 'Prze¶lij dalej';
$lang['headers_mnu'] = 'Nag³ówki';
$lang['move_mnu'] = 'Przenie¶ do';
$lang['move_to_trash_mnu'] = 'Move to Trash';
$lang['delete_mnu'] = 'Usuñ';
$lang['print_mnu'] = 'Drukuj';
$lang['download_mnu'] = 'Download';
$lang['from_hea'] = 'Od:';
$lang['to_hea'] = 'Do:';
$lang['cc_hea'] = 'Cc:';
$lang['date_hea'] = 'Data:';
$lang['subject_hea'] = 'Temat:';
$lang['attach_hea'] = 'Za³±czniki:';
$lang['attch_name_hea'] = 'Nazwa';
$lang['attch_force_hea'] = 'Pobierz';
$lang['attch_type_hea'] = 'Typ';
$lang['attch_size_hea'] = 'Rozmiar';
$lang['catch_address'] = 'Dodaj do ksi±¿ki adresowej';
$lang['block_address'] = 'Block address';
// [Search]
$lang['sch_title'] = 'Search';
$lang['sch_information_text'] = 'Podaj frazê lub s³owo, którego szukasz.<br> Przeszukiwane bêd± wy³±cznie przeczytane wiadomo¶ci. ';
$lang['sch_button_text'] = 'Szukaj >>';
$lang['sch_subject_hea'] = 'Temat';
$lang['sch_from_hea'] = 'Od';
$lang['sch_date_hea'] = 'Data';
$lang['sch_body_hea'] = 'Tre¶æ';
$lang['sch_folder_hea'] = 'Folder';
$lang['sch_no_results'] = 'Nie znaleziono ¿adnych wiadomo¶ci';
// [QuickAddress]
$lang['qad_title'] = 'Ksi±¿ka adresowa';
$lang['qad_select_address'] = 'Wybierz adres';
$lang['qad_to'] = 'Do';
$lang['qad_cc'] = 'Cc';
$lang['qad_bcc'] = 'Bcc';
// [AddressBook]
// edit/display
$lang['adr_title'] = 'Ksi±¿ka adresowa';
$lang['adr_name'] = 'Nazwa';
$lang['adr_email'] = 'E-mail';
$lang['adr_street'] = 'Ulica';
$lang['adr_city'] = 'Miasto';
$lang['adr_state'] = 'Województwo';
$lang['adr_work'] = 'Praca';
$lang['adr_back'] = 'Powrót';
$lang['adr_save'] = 'Zapisz';
$lang['adr_phone'] = 'Telefon';
$lang['adr_cell'] = 'Cell';
$lang['adr_note'] = 'Notatki';
// list
$lang['adr_name_hea'] = 'Nazwa';
$lang['adr_email_hea'] = 'E-mail';
$lang['adr_edit_hea'] = 'Edytuj';
$lang['adr_expo_hea'] = 'Eksportuj';
$lang['adr_dele_hea'] = 'Usuñ';
$lang['adr_new_entry'] = 'Nowy kontakt';
$lang['addr_saved'] = 'Adres zosta³ zapisany';
$lang['addr_added'] = 'Adres zosta³ dodany';
$lang['addr_deleted'] = 'Adres zosta³ usuniêty';
// [BlockSender]
$lang['blk_title'] = 'Block sender'; // FIXME: need translation
$lang['blk_information'] = 'Only shows e-mails that are not in the filter yet';
$lang['blk_email'] = 'E-mail';
$lang['blk_no_address'] = 'No address available'; // FIXME: need translation
$lang['blk_close'] = 'Zamknij';
$lang['blk_save'] = 'Zapisz';
// [Event]
$lang['evt_title'] = 'Wydarzenie z kalendarza';
$lang['evt_save'] = 'Zapisz';
$lang['evt_delete'] = 'Usuñ';
$lang['evt_stop'] = 'Stop time'; // FIXME: need translation
$lang['evt_start'] = 'Start time'; // FIXME: need translation
| jimjag/telaen | telaen/inc/langs/pl_PL.php | PHP | gpl-2.0 | 12,330 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSmoove.Core.Entities
{
public class FilePart
{
public Guid FileId { get; set; }
public long Offset { get; set; }
public int Length { get; set; }
}
}
| Dennisenzo/D-Smoove | V1/DSmoove.Core/Entities/FilePart.cs | C# | gpl-2.0 | 316 |
<?php
namespace PpgwBundle\Controller;
use PpgwBundle\Helpers\CodeHighlighter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class TechController extends Controller
{
public function ch1Action(){
return $this->render('PpgwBundle:Tech:ch1.html.twig', array(
));
}
public function ch2Action(){
return $this->render('PpgwBundle:Tech:ch2.html.twig', array(
));
}
public function ch3Action(){
return $this->render('PpgwBundle:Tech:ch3.html.twig', array(
));
}
public function ch4Action(){
return $this->render('PpgwBundle:Tech:ch4.html.twig', array(
));
}
public function ch5Action(){
$em = $this->getDoctrine()
->getManager();
$plant = $em->getRepository('PpgwBundle:Plant')->find(1);
$ar = array();
$ar[] = 'BloggerBlogBundle::layout.html.twig';
$ar[] = 'bundles/bloggerblog/css/plant.css';
$ar[] = 'BloggerBlogBundle_plant_show';
$ar[] = 'PpgwBundle::layout.html.twig';
$ar[] = 'bundles/ppgw/css/forms.css';
$ar[] = 'bundles/ppgw/js/forms.js';
$ar[] = 'widget_container_attributes';
$ar[] = 'widget_attributes';
$ar[] = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js';
$ar[] = 'PpgwBundle_plant_index';
$ar[] = 'PpgwBundle_plant_new';
$ar[] = 'http://www.catalogueoflife.org/annual-checklist/2015/browse/';
$ar[] = 'bundles/ppgw/css/plant.css';
$ar[] = 'PpgwBundle_plant_edit';
$ar[] = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSNDcrG80wqzVn2wZRARTJEuZ3mUVSXxMiXfE6cGOvm6TOEiI_F';
$helper = $this->get('twig.highlighter');
$twig_1 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/code_snippets/ch5_snippet_1.html.twig', $ar);
$twig_2 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/Resources/views/Plant/new.html.twig', $ar);
$php_1 = $helper->highlightPhpFile('C:/WAMP/www/website/src/PpgwBundle/Entity/Plant.php');
$php_2 = $helper->highlightPhpFile('C:/WAMP/www/website/src/PpgwBundle/Form/PlantForm.php');
$twig_3 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/Resources/views/Plant/show.html.twig', $ar);
$php_3 = $helper->highlightPhpFile('C:/WAMP/www/website/src/PpgwBundle/code_snippets/ch5_snippet_3.php');
$twig_4 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/Resources/views/Plant/edit.html.twig', $ar);
$php_4 = $helper->highlightPhpFile('C:/WAMP/www/website/src/PpgwBundle/code_snippets/ch5_snippet_4.php');
return $this->render('PpgwBundle:Tech:ch5.html.twig', array(
'plant' => $plant, 'twig_1' => $twig_1, 'twig_2' => $twig_2,
'twig_3'=> $twig_3, 'php_1' => $php_1, 'php_2' => $php_2,
'php_3' => $php_3, 'twig_4' => $twig_4, 'php_4' => $php_4,
));
}
public function ch6Action(){
return $this->render('PpgwBundle:Tech:ch6.html.twig', array(
));
}
public function ch7Action(){
$ar = array();
$ar[1] = 'PpgwBundle::layout.html.twig';
$ar[2] = 'bundles/ppgw/css/plant.css';
$ar[3] = 'PpgwBundle_sort';
$ar[4] = 'PpgwBundle_plant_new';
$ar[5] = 'PpgwBundle_plant_show';
$helper = $this->get('twig.highlighter');
$twig_1 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/Resources/views/Plant/index.html.twig', $ar);
$twig_2 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/code_snippets/pagination_snippet_1.html.twig', $ar);
return $this->render('PpgwBundle:Tech:ch7.html.twig', array(
'twig_1' => $twig_1, 'twig_2' => $twig_2
));
}
public function ch8Action(){
return $this->render('PpgwBundle:Tech:ch8.html.twig', array(
));
}
public function ch9Action(){
return $this->render('PpgwBundle:Tech:ch9.html.twig', array(
));
}
public function part1Action(){
return $this->render('PpgwBundle:Tech:pt1.html.twig', array(
));
}
public function part2Action(){
return $this->render('PpgwBundle:Tech:pt2.html.twig', array(
));
}
public function part3Action(){
return $this->render('PpgwBundle:Tech:pt3.html.twig', array(
));
}
public function part4Action(){
return $this->render('PpgwBundle:Tech:pt4.html.twig', array(
));
}
public function part5Action(){
return $this->render('PpgwBundle:Tech:pt5.html.twig', array(
));
}
public function part6Action(){
return $this->render('PpgwBundle:Tech:pt6.html.twig', array(
));
}
public function introAction(){
return $this->render('PpgwBundle:Tech:intro.html.twig', array(
));
}
public function indexAction(Request $request){
return $this->render('PpgwBundle:Tech:index.html.twig', array(
));
}
public function tableOfContentsAction(){
//slugs:
$pt1 = "part-1-symfony2-configuration-and-templating";
$pt2 = "part-2-contact-page-validators-forms-and-emailing";
$pt3 = "part-3-the-blog-model-using-doctrine2-and-data-fixtures";
$pt4 = "part-4-the-comments-model-adding-comments-doctrine-repositories-and-migrations";
$pt5 = "part-5-customizing-the-view-twig-extensions-the-sidebar-and-assetic";
$pt6 = "part-6-testing-unit-and-functional-with-PHPUnit";
$ch1 = "chapter-1-symfony2-configuration-windows-wamp-netbeans-symfony2";
$ch2 = "chapter-2-symfony2-coding-standards";
$ch3 = "chapter-3-symfony2-github-working-in-teams-and-backup";
$ch4 = "chapter-4-symfony2-doctrine2";
$ch5 = "chapter-5-symfony2-index-new-edit-show-delete-actions";
$ch6 = "chapter-6-symfony2-embedded-forms";
$ch7 = "chapter-7-symfony2-pagination";
$ch8 = "chapter-8-symfony2-search";
$ch9 = "services-symfony2-answer-for-global-functions";
return $this->render('PpgwBundle:Tech:toc.html.twig', array(
'pt1' => $pt1, 'pt2' => $pt2, 'ch1' => $ch1, 'ch4' => $ch4,
'pt3' => $pt3, 'pt4' => $pt4, 'ch2' => $ch2, 'ch5' => $ch5,
'pt5' => $pt5, 'pt6' => $pt6, 'ch3' => $ch3, 'ch6' => $ch6,
'ch7' => $ch7, 'ch8' => $ch8, 'ch9' => $ch9
));
}
} | phillharmonic/propagators_world | src/PpgwBundle/Controller/TechController.php | PHP | gpl-2.0 | 6,910 |
<?php
$title = fitwp_option( 'custom_content_title' );
$content = trim( fitwp_option( 'custom_content' ) );
?>
<section id="section-custom-content" class="section-custom-content section">
<div class="inner">
<?php if( !empty( $title ) ) : ?>
<h2 class="section-title">
<?php
$suffix = noise_kses( fitwp_option( 'custom_content_suffix' ) );
$desc = noise_kses( fitwp_option( 'custom_content_subtitle' ) );
printf(
'<span>%s</span>%s%s',
noise_kses( $title ),
$suffix ? '<span class="suffix">' . $suffix . '</span>' : '',
$desc ? '<span class="desc">' . $desc . '</span>' : ''
);
?>
</h2>
<?php endif; ?>
<div class="custom-content">
<?php echo do_shortcode( wpautop( $content ) ) ?>
</div>
</div>
</section> | kevolee88/sdjammincity | wp-content/themes/noise-wp/sections/custom-content.php | PHP | gpl-2.0 | 787 |
package com.visittomm.mweather.fragments;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.visittomm.mweather.R;
import com.visittomm.mweather.interfaces.FragmentListener;
import com.visittomm.mweather.utils.Utils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.FileInputStream;
import java.util.ArrayList;
/**
* Created by monmon on 1/4/16.
*/
public class CachedCityListFragment extends Fragment {
public static final String TAG = "com.visittomm.mweather.fragments.CachedCityListFragment";
private static final String JSON_CACHE_FILE = "city-cache.json";
private Context mContext = null;
private View mView = null;
ListView mListView = null;
ArrayAdapter<String> mAdapter;
ArrayList<String> stringArrayList;
public CachedCityListFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Log.d(TAG, " =>> CachedCityListFragment");
mView = inflater.inflate(R.layout.fragment_cached_city_list, container, false);
mContext = this.getActivity();
// change toolbar title of current Fragment
Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment);
if (f instanceof CachedCityListFragment)
((AppCompatActivity) mContext).getSupportActionBar().setTitle("Mweather");
mListView = (ListView) mView.findViewById(R.id.lvCachedRecordListing);
// Read selected cities object from cache
String jsonContent = null;
try {
FileInputStream jsonCache = mContext.openFileInput(JSON_CACHE_FILE);
jsonContent = Utils.readStream(jsonCache);
JSONArray jsonArray = new JSONArray(jsonContent);
stringArrayList = new ArrayList<String>();
for(int i=0;i<jsonArray.length();i++){
JSONObject json_data = jsonArray.getJSONObject(i);
stringArrayList.add(json_data.getString("name")); // add to arraylist
}
} catch (Exception exception) {
Log.e(TAG, exception.getMessage());
}
mAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_2, android.R.id.text2, stringArrayList);
mListView.setAdapter(mAdapter);
onCityClick();
checkAddEditBtnClick();
return mView;
}
private void onCityClick() {
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
@Override
public void run() {
view.setAlpha(1);
}
});
String value = (String)parent.getItemAtPosition(position);
Log.d(TAG, "clicked value >> " + value);
WeatherDetailFragment fragment = new WeatherDetailFragment();
Bundle fragBundle = new Bundle();
fragBundle.putString("selectedCity", value);
fragment.setArguments(fragBundle);
FragmentListener fragmentListener = (FragmentListener) getActivity();
fragmentListener.startMainFragment(fragment, true);
}
});
}
private void checkAddEditBtnClick() {
Button myButton = (Button) mView.findViewById(R.id.addEditCity);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CityListFragment fragment = new CityListFragment();
FragmentListener fragmentListener = (FragmentListener) getActivity();
fragmentListener.startMainFragment(fragment, true);
}
});
}
}
| kankaungmalay/Mweather | app/src/main/java/com/visittomm/mweather/fragments/CachedCityListFragment.java | Java | gpl-2.0 | 4,581 |
import subprocess
import sys
import numpy as np
import fluidfoam
import matplotlib.pyplot as plt
plt.ion()
############### Plot properties #####################
import matplotlib.ticker as mticker
from matplotlib.ticker import StrMethodFormatter, NullFormatter
from matplotlib import rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
label_size = 20
legend_size = 12
fontsize=25
linewidth=2
plt.rcParams['xtick.labelsize'] = label_size
plt.rcParams['ytick.labelsize'] = label_size
plt.rcParams['legend.fontsize'] = legend_size
plt.rcParams['lines.linewidth'] = linewidth
plt.rcParams['axes.labelsize'] = fontsize
####################################################
######################
# Load DEM data
######################
zDEM, phiDEM, vxPDEM, vxFDEM, TDEM = np.loadtxt('DATA/BedloadTurbDEM.txt', unpack=True)
######################
#Read SedFoam results
######################
sol = '../1DBedLoadTurb/'
try:
proc = subprocess.Popen(
["foamListTimes", "-latestTime", "-case", sol],
stdout=subprocess.PIPE,)
except:
print("foamListTimes : command not found")
print("Do you have load OpenFoam environement?")
sys.exit(0)
output = proc.stdout.read() #to obtain the output of function foamListTimes from the subprocess
timeStep = output.decode().rstrip().split('\n')[0] #Some management on the output to obtain a number
#Read the data
X, Y, Z = fluidfoam.readmesh(sol)
z = Y
phi = fluidfoam.readscalar(sol, timeStep, 'alpha_a')
vxPart = fluidfoam.readvector(sol, timeStep, 'Ua')[0]
vxFluid = fluidfoam.readvector(sol, timeStep, 'Ub')[0]
T = fluidfoam.readscalar(sol, timeStep, 'Theta')
######################
#Plot results
######################
d = 0.006 #6mm diameter particles
plt.figure(figsize=[10,5])
plt.subplot(141)
plt.plot(phiDEM, zDEM/d, 'k--', label=r'DEM')
plt.plot(phi, z/d, label=r'SedFoam')
plt.xlabel(r'$\phi$', fontsize=25)
plt.ylabel(r'$\frac{z}{d}$', fontsize=30, rotation=True, horizontalalignment='right')
plt.grid()
plt.ylim([-1.525, 32.025])
plt.legend()
plt.subplot(142)
I = np.where(phiDEM>0.001)[0]
plt.plot(vxPDEM[I], zDEM[I]/d, 'r--')
I = np.where(phi>0.001)[0]
plt.plot(vxPart[I], z[I]/d, 'r', label=r'$v_x^p$')
plt.plot(vxFDEM, zDEM/d, 'b--')
plt.plot(vxFluid, z/d, 'b', label=r'$u_x^f$')
plt.xlabel(r'$v_x^p$, $u_x^f$', fontsize=25)
plt.ylim([-1.525, 32.025])
plt.grid()
plt.legend()
ax = plt.gca()
ax.set_yticklabels([])
plt.legend()
plt.subplot(143)
plt.plot(phiDEM*vxPDEM, zDEM/d, 'k--', label=r'DEM')
plt.plot(phi*vxPart, z/d, label=r'SedFoam')
plt.xlabel(r'$q = \phi v_x^p$', fontsize=25)
plt.grid()
plt.ylim([-1.525, 32.025])
ax = plt.gca()
ax.set_yticklabels([])
plt.subplot(144)
I = np.where(phiDEM>0.001)[0]
plt.plot(TDEM[I], zDEM[I]/d, 'k--', label=r'DEM')
I = np.where(phi>0.001)[0]
plt.plot(T[I], z[I]/d, label=r'SedFoam')
plt.xlabel(r'$T$', fontsize=25)
plt.grid()
plt.ylim([-1.525, 32.025])
ax = plt.gca()
ax.set_yticklabels([])
plt.savefig('Figures/res_TutoBedloadTurb.png', bbox_inches='tight')
plt.show(block=True)
| SedFoam/sedfoam | tutorials/Py/plot_tuto1DBedLoadTurb.py | Python | gpl-2.0 | 3,062 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Handles table search tab
*
* display table search form, create SQL query from form data
* and include sql.php to execute it
*
* @package PhpMyAdmin
*/
/**
* Gets some core libraries
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/mysql_charsets.lib.php';
require_once 'libraries/TableSearch.class.php';
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('makegrid.js');
$scripts->addFile('sql.js');
$scripts->addFile('tbl_select.js');
$scripts->addFile('tbl_change.js');
$scripts->addFile('jquery/timepicker.js');
$scripts->addFile('gis_data_editor.js');
$post_params = array(
'ajax_request',
'session_max_rows'
);
foreach ($post_params as $one_post_param) {
if (isset($_POST[$one_post_param])) {
$GLOBALS[$one_post_param] = $_POST[$one_post_param];
}
}
$table_search = new PMA_TableSearch($db, $table, "normal");
/**
* Not selection yet required -> displays the selection form
*/
if (! isset($_POST['columnsToDisplay']) && ! isset($_POST['displayAllColumns'])) {
// Gets some core libraries
include_once 'libraries/tbl_common.inc.php';
//$err_url = 'tbl_select.php' . $err_url;
$url_query .= '&goto=tbl_select.php&back=tbl_select.php';
/**
* Gets table's information
*/
include_once 'libraries/tbl_info.inc.php';
if (! isset($goto)) {
$goto = $GLOBALS['cfg']['DefaultTabTable'];
}
// Defines the url to return to in case of error in the next sql statement
$err_url = $goto . '?' . PMA_generate_common_url($db, $table);
// Displays the table search form
$response->addHTML($table_search->getSelectionForm($goto));
} else {
/**
* Selection criteria have been submitted -> do the work
*/
$sql_query = $table_search->buildSqlQuery();
include 'sql.php';
}
?>
| gurjitdhillon/phpmyadmin | tbl_select.php | PHP | gpl-2.0 | 1,950 |
class AddUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password
t.timestamps null: false
end
end
end
| djtaylor333/Rurukish | db/migrate/20150827030252_add_users.rb | Ruby | gpl-2.0 | 236 |
package me.tomkent.chemcraft.Blocks;
import me.tomkent.chemcraft.ChemCraft;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
public class oreBarium extends Block{
private static String blockName = "Barium Ore";
private static String blockTexture = "missing";
private static String blockNameSafe = "oreBarium";
public oreBarium()
{
super(Material.rock);
setBlockName(ChemCraft.MODID + "_" + blockNameSafe);
setCreativeTab(ChemCraft.tabChemcraft);
setBlockTextureName("chemcraft:" + blockTexture);
setHarvestLevel("pickaxe", 1);
setHardness(5F);
}
}
| tommykent1210/ChemCraft | Development/src/main/java/me/tomkent/chemcraft/Blocks/oreBarium.java | Java | gpl-2.0 | 655 |
<div id="container" class="row-fluid">
<?php $this->load->view('sidebar'); ?>
<div id="main-content">
<!-- BEGIN PAGE CONTAINER-->
<div class="container-fluid">
<!-- BEGIN PAGE HEADER-->
<div class="row-fluid">
<div class="span12">
<?php $this->load->view('msg'); ?>
<h3 class="page-title">
Add Sale Payment
<small>Please enter the information below.</small>
</h3>
</div>
<div class="span12">
<form class="form-horizontal" method="post" action="<?php echo current_url(); ?>">
<div class="control-group">
<label class="control-label">Customer</label>
<div class="controls">
<select name="customer_id" class="span6 chzn-select" data-placeholder="Choose a Category" tabindex="1">
<?php foreach ($customers->result() as $customer)
{
?>
<option value="<?php echo $customer->id; ?>"><?php echo $customer->name; ?></option>
<?php
} ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">SO Reference(Optional)</label>
<div class="controls">
<input type="text" name="reference_so" data-placement="right"
data-original-title="SO Reference is an optional field, e.g(Sale Order No - 01010)"
placeholder="SO Reference" class="input-xlarge tooltips" />
<!-- <span class="help-inline">Some hint here</span> -->
</div>
</div>
<div class="control-group">
<label class="control-label">Date</label>
<div class="controls">
<input type="date" name="date" class="input-xlarge" required/>
<!-- <span class="help-inline">Some hint here</span> -->
</div>
</div>
<div class="control-group">
<label class="control-label">Amount</label>
<div class="controls">
<input type="text" name="amount" data-placement="right"
data-original-title="Amount paying to Supplier"
placeholder="Amount" class="input-xlarge tooltips" required/>
</div>
</div>
<div class="control-group">
<label class="control-label">NOTE(Optional)</label>
<div class="controls">
<textarea name="note"></textarea>
<!-- <span class="help-inline">Some hint here</span> -->
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Submit" class="btn btn-primary" id="pulsate-hover" />
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<?php $this->load->view('scripts'); ?>
<script type="text/javascript">
$(function(){
$(".chzn-select").chosen();
});
</script> | huzaifa007/Toughinventory | application/views/sale/add_salepayment.php | PHP | gpl-2.0 | 3,898 |
<?php
// ads
td_demo_media::add_image_to_media_gallery('td_wedding_smartlist_ad', "http://demo_content.tagdiv.com/Newspaper_6/wedding/banner-smartlist.jpg");
td_demo_media::add_image_to_media_gallery('td_wedding_sidebar_ad', "http://demo_content.tagdiv.com/Newspaper_6/wedding/banner-sidebar.jpg");
td_demo_media::add_image_to_media_gallery('td_homepage_big_ad', "http://demo_content.tagdiv.com/Newspaper_6/wedding/big-ad.jpg"); | duongnguyen92/game.tvd12.com | wp-content/themes/Newspaper/includes/demos/wedding/td_media_6.php | PHP | gpl-2.0 | 469 |
<?php
class MP_AdminPage extends MP_adminpage_list_
{
const screen = MailPress_page_wp_cron;
const capability = 'MailPress_manage_wp_cron';
const help_url = 'http://blog.mailpress.org/tutorials/add-ons/wp_cron/';
const file = __FILE__;
const add_form_id = 'add';
const list_id = 'the-list';
const tr_prefix_id = 'wpcron';
//// Redirect ////
public static function redirect()
{
if ( !empty($_REQUEST['action']) && ($_REQUEST['action'] != -1)) $action = $_REQUEST['action'];
elseif ( !empty($_REQUEST['action2']) && ($_REQUEST['action2'] != -1) ) $action = $_REQUEST['action2'];
if (!isset($action)) return;
$url_parms = self::get_url_parms(array('paged', 'id', 'sig', 'next_run'));
$checked = (isset($_GET['checked'])) ? $_GET['checked'] : array();
$count = str_replace('bulk-', '', $action);
$count .= 'd';
$$count = 0;
switch($action)
{
case 'bulk-delete' :
$crons = _get_cron_array();
foreach($checked as $id )
{
$x = explode('::', $id);
if( isset( $crons[$x[2]][$x[0]][$x[1]] ) )
{
wp_unschedule_event($x[2], $x[0], $crons[$x[2]][$x[0]][$x[1]]['args']);
$$count++;
}
}
$url_parms['message'] = ($$count <= 1) ? 3 : 4;
if ($$count) $url_parms[$count] = $$count;
self::mp_redirect( self::url(MailPress_wp_cron, $url_parms) );
break;
case 'add':
$_POST['args'] = json_decode(stripslashes($_POST['args']), true);
if( !is_array($_POST['args']) ) $_POST['args'] = array();
$_POST['next_run'] = strtotime($_POST['next_run']);
if( $_POST['next_run'] === false || $_POST['next_run'] == -1 ) $_POST['next_run'] = time();
if( $_POST['schedule'] == '_oneoff' )
$e = wp_schedule_single_event($_POST['next_run'], $_POST['name'], $_POST['args']) === NULL;
else
$e = wp_schedule_event( $_POST['next_run'], $_POST['schedule'], $_POST['name'], $_POST['args']) === NULL;
$url_parms['message'] = ( $e ) ? 1 : 91;
self::mp_redirect( self::url(MailPress_wp_cron, $url_parms) );
break;
case 'edited':
unset($_GET['action']);
if (!isset($_POST['cancel']))
{
$crons = _get_cron_array();
$x = explode('::', $_POST['id']);
if( isset( $crons[$x[2]][$x[0]][$x[1]] ) )
wp_unschedule_event($x[2], $x[0], $crons[$x[2]][$x[0]][$x[1]]['args']);
$_POST['args'] = json_decode(stripslashes($_POST['args']), true);
if( !is_array($_POST['args']) ) $_POST['args'] = array();
$_POST['next_run'] = strtotime($_POST['next_run']);
if( $_POST['next_run'] === false || $_POST['next_run'] == -1 ) $_POST['next_run'] = time();
if( $_POST['schedule'] == '_oneoff' )
$e = wp_schedule_single_event($_POST['next_run'], $_POST['name'], $_POST['args']) === NULL;
else
$e = wp_schedule_event( $_POST['next_run'], $_POST['schedule'], $_POST['name'], $_POST['args']) === NULL;
$url_parms['message'] = ( $e ) ? 2 : 92 ;
}
unset($url_parms['id'], $url_parms['sig'], $url_parms['next_run']);
self::mp_redirect( self::url(MailPress_wp_cron, $url_parms) );
break;
case 'do_now':
unset($_GET['action']);
$e = false;
$crons = _get_cron_array();
foreach( $crons as $time => $cron )
{
if( isset( $cron[$_GET['id']][$_GET['sig']] ) )
{
wp_schedule_single_event(time()-1, $_GET['id'], $cron[$_GET['id']][$_GET['sig']]['args']);
spawn_cron();
$e = true;
break;
}
}
$url_parms['message'] = ( $e ) ? 5 : 95 ;
unset($url_parms['id'], $url_parms['sig'], $url_parms['next_run']);
self::mp_redirect( self::url(MailPress_wp_cron, $url_parms) );
break;
case 'delete':
$crons = _get_cron_array();
if( isset( $crons[$url_parms['next_run']][$url_parms['id']][$url_parms['sig']] ) )
wp_unschedule_event($url_parms['next_run'], $url_parms['id'], $crons[$url_parms['next_run']][$url_parms['id']][$url_parms['sig']]['args']);
unset($url_parms['id'], $url_parms['sig'], $url_parms['next_run']);
$url_parms['message'] = 3;
self::mp_redirect( self::url(MailPress_wp_cron, $url_parms) );
break;
}
}
//// Styles ////
public static function print_styles($styles = array())
{
wp_register_style ( self::screen, '/' . MP_PATH . 'mp-admin/css/wp_cron.css' );
$styles[] = self::screen;
parent::print_styles($styles);
}
//// Scripts ////
public static function print_scripts($scripts = array())
{
$scripts = apply_filters('MailPress_autorefresh_js', $scripts);
parent::print_scripts($scripts);
}
//// Columns ////
public static function get_columns()
{
$columns = array( 'cb' => "<input type='checkbox' />",
'name' => __('Hook name', MP_TXTDOM),
'next' => __('Next run', MP_TXTDOM),
'rec' => __('Recurrence',MP_TXTDOM),
'args' => __('Arguments', MP_TXTDOM),
);
return $columns;
}
//// List ////
public static function get_list($args)
{
extract($args);
$wp_crons = array();
$crons = _get_cron_array();
if (!$crons) $crons = array();
foreach($crons as $time => $cron)
{
foreach($cron as $hook => $dings)
{
foreach($dings as $sig => $data)
{
$wp_crons[] = array( 'hook' => $hook,
'time' => $time,
'sig' => $sig,
'data' => $data
);
}
}
}
$total = count($wp_crons);
$rows = array_slice ($wp_crons, $start, $_per_page);
return array($rows, $total);
}
//// Row ////
public static function get_row($wp_cron, $url_parms)
{
static $row_class = '';
// url's
$args = array();
$args['id'] = $wp_cron['hook'];
$args['sig'] = $wp_cron['sig'];
$args['next_run'] = $wp_cron['time'];
$id = $args['id'] . '::' . $args['sig'] . '::' . $args['next_run'];
$args['action'] = 'delete';
$delete_url = esc_url(self::url( MailPress_wp_cron, array_merge($args, $url_parms), 'delete-cron_' . $args['id'] . '_' . $args['sig'] . '_' . $args['next_run']));
$args['action'] = 'do_now';
$do_now_url = esc_url(self::url( MailPress_wp_cron, array_merge($args, $url_parms)));
$args['action'] = 'edit';
$edit_url = esc_url(self::url( MailPress_wp_cron, array_merge($args, $url_parms)));
// actions
$actions = array();
$actions['edit'] = "<a href='$edit_url'>" . __('Edit') . "</a>";
$actions['do_now'] = "<a href='$do_now_url'>" . __('Do now', MP_TXTDOM) . "</a>";
$actions['delete'] = "<a href='$delete_url'>" . __('Delete') . "</a>";
$row_class = (" class='alternate'" == $row_class) ? '' : " class='alternate'";
$out = '';
$out .= "<tr id='wp_cron::$id' $row_class>";
$columns = self::get_columns();
$hidden = self::get_hidden_columns();
foreach ( $columns as $column_name => $column_display_name )
{
$class = "class='$column_name column-$column_name'";
$style = '';
if ( in_array($column_name, $hidden) ) $style .= 'display:none;';
$style = ' style="' . $style . '"';
$attributes = "$class$style";
$out .= "<td $attributes>";
switch ($column_name)
{
case 'cb':
$out .= "<input type='checkbox' name='checked[]' value='$id' />";
break;
case 'name':
$out .= $wp_cron['hook'];
$out .= self::get_actions($actions);
break;
case 'args':
$out .= json_encode($wp_cron['data']['args']);
break;
case 'next':
$timestamp = $wp_cron['time'];
$time_since = self::time_since($timestamp);
$next_date = date_i18n( 'D Y/m/d H:i:s', strtotime(get_date_from_gmt(gmdate('Y-m-d H:i:s', $timestamp))));
$next_date = str_replace(' ', ' ', $next_date);
$out .= "$timestamp <abbr title=\"{$time_since}\">{$next_date}</abbr>";
break;
case 'rec':
$out .= ($wp_cron['data']['schedule']) ? ('<abbr title="' . sprintf(__('%1$s sec.'), $wp_cron['data']['interval']) . '">' . self::interval($wp_cron['data']['interval']) . '</abbr>') : __('Non-repeating', MP_TXTDOM);
break;
}
$out .= '</td>';
}
$out .= "</tr>\n";
return $out;
}
public static function time_since($newer_date)
{
return self::interval( $newer_date - current_time('timestamp', 'gmt') );
}
public static function interval( $since , $max = 2 )
{
// array of time period chunks
$chunks = array ( array(60 * 60 * 24 * 365 , __('%s year', MP_TXTDOM), __('%s years', MP_TXTDOM)),
array(60 * 60 * 24 * 30 , __('%s month', MP_TXTDOM), __('%s months', MP_TXTDOM)),
array(60 * 60 * 24 * 7, __('%s week', MP_TXTDOM), __('%s weeks', MP_TXTDOM)),
array(60 * 60 * 24 , __('%s day', MP_TXTDOM), __('%s days', MP_TXTDOM)),
array(60 * 60 , __('%s hour', MP_TXTDOM), __('%s hours', MP_TXTDOM)),
array(60 , __('%s minute', MP_TXTDOM), __('%s minutes', MP_TXTDOM)),
array(1 , __('%s second', MP_TXTDOM), __('%s seconds', MP_TXTDOM))
);
if( $since <= 0 ) return __('now', MP_TXTDOM);
$done = $total = 0;
$output = '';
foreach($chunks as $chunk)
{
$count = floor( ($since - $total) / $chunk[0]);
if (!$count) continue;
$total += $count * $chunk[0];
if ($done) $output .= ' ';
$output .= sprintf(_n($chunk[1], $chunk[2], $count), $count);
$done++;
if ($done == $max) break;
}
return $output;
}
public static function get_schedules()
{
$schedules = array();
$x = wp_get_schedules();
uasort($x, create_function('$a,$b', 'return $a["interval"]-$b["interval"];'));
foreach( $x as $name => $data ) $schedules[$name] = $data['display'] . ' (' . self::interval($data['interval']) . ')';
$schedules['_oneoff'] = __('Non-repeating', MP_TXTDOM);
return $schedules;
}
public static function get($_hook, $_sig, $_next_run)
{
$crons = _get_cron_array();
foreach( $crons as $next_run => $cron )
{
foreach( $cron as $hook => $dings)
{
foreach( $dings as $sig => $data )
{
if( $hook == $_hook && $sig == $_sig && $next_run == $_next_run )
{
return array( 'hookname' => $hook,
'next_run' => $next_run,
'schedule' => ($data['schedule']) ? $data['schedule'] : '_oneoff',
'sig' => $sig,
'args' => $data['args']
);
}
}
}
}
}
} | iSynthetica/prime-x.loc | wp-content/plugins/mailpress/mp-admin/wp_cron.php | PHP | gpl-2.0 | 10,273 |
// nullmailer -- a simple relay-only MTA
// Copyright (C) 2018 Bruce Guenter <bruce@untroubled.org>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact me at <bruce@untroubled.org>. There is also a mailing list
// available to discuss this package. To subscribe, send an email to
// <nullmailer-subscribe@lists.untroubled.org>.
#include "config.h"
#include <stdlib.h>
#include <unistd.h>
#include "errcodes.h"
#include "fdbuf/fdbuf.h"
#include "hostname.h"
#include "itoa.h"
#include "mystring/mystring.h"
#include "netstring.h"
#include "protocol.h"
const int default_port = 628;
const int default_tls_port = -1; // No standard for QMQP over SSL exists
const char* cli_program = "qmqp";
const char* cli_help_prefix = "Send an email message via QMQP\n";
class qmqp
{
fdibuf& in;
fdobuf& out;
public:
qmqp(fdibuf& netin, fdobuf& netout);
~qmqp();
void send(fdibuf& msg, unsigned long size, const mystring& env);
};
qmqp::qmqp(fdibuf& netin, fdobuf& netout)
: in(netin), out(netout)
{
}
qmqp::~qmqp()
{
}
bool skip_envelope(fdibuf& msg)
{
if(!msg.rewind())
return false;
mystring tmp;
while(msg.getline(tmp))
if(!tmp)
break;
return msg;
}
void qmqp::send(fdibuf& msg, unsigned long size, const mystring& env)
{
if(!skip_envelope(msg))
protocol_fail(ERR_MSG_READ, "Error re-reading message");
unsigned long fullsize = strlen(itoa(size)) + 1 + size + 1 + env.length();
out << itoa(fullsize) << ":"; // Start the "outer" netstring
out << itoa(size) << ":"; // Start the message netstring
fdbuf_copy(msg, out, true); // Send out the message
out << "," // End the message netstring
<< env // The envelope is already encoded
<< ","; // End the "outer" netstring
if(!out.flush())
protocol_fail(ERR_MSG_WRITE, "Error sending message to remote");
mystring response;
if(!in.getnetstring(response))
protocol_fail(ERR_PROTO, "Response from remote was not a netstring");
switch(response[0]) {
case 'K': protocol_succ(response.c_str()+1); break;
case 'Z': protocol_fail(ERR_MSG_TEMPFAIL, response.c_str()+1); break;
case 'D': protocol_fail(ERR_MSG_PERMFAIL, response.c_str()+1); break;
default: protocol_fail(ERR_PROTO, "Invalid status byte in response");
}
}
bool compute_size(fdibuf& msg, unsigned long& size)
{
char buf[4096];
size = 0;
while(msg.read(buf, 4096))
size += msg.last_count();
if(msg.eof())
size += msg.last_count();
return size > 0;
}
bool make_envelope(fdibuf& msg, mystring& env)
{
mystring tmp;
while(msg.getline(tmp)) {
if(!tmp)
return true;
env += str2net(tmp);
}
return false;
}
bool preload_data(fdibuf& msg, unsigned long& size, mystring& env)
{
return make_envelope(msg, env) &&
compute_size(msg, size);
}
static unsigned long msg_size;
static mystring msg_envelope;
void protocol_prep(fdibuf& in)
{
if(!preload_data(in, msg_size, msg_envelope))
protocol_fail(ERR_MSG_READ, "Error reading message");
}
void protocol_starttls(fdibuf& netin, fdobuf& netout)
{
protocol_fail(ERR_USAGE, "QMQP does not support STARTTLS");
(void)netin;
(void)netout;
}
void protocol_send(fdibuf& in, fdibuf& netin, fdobuf& netout)
{
alarm(60*60); // Connection must close after an hour
qmqp conn(netin, netout);
conn.send(in, msg_size, msg_envelope);
}
| bruceg/nullmailer | protocols/qmqp.cc | C++ | gpl-2.0 | 4,011 |
<div class="messageBoxMenu">
<?php echo Html::l($language->new, 'Message', 'write');?>
</div>
<div class="messageBoxMenu">
<?php echo Html::l($language->inbox, 'Message', 'inbox');?>
</div>
<div class="messageBoxMenu messageBoxMenuActive">
<?php echo Html::l($language->alerts, 'Message', 'alerts');?>
</div>
<div class="messageBoxMenu">
<?php echo Html::l($language->archive, 'Message', 'archive');?>
</div>
<div class="messageBoxMenu">
<?php echo Html::l($language->trash, 'Message', 'trash');?>
</div>
<div class="messageBoxMenu">
<?php echo Html::l($language->outbox, 'Message', 'outbox');?>
</div><div style="clear:both;"></div>
<div class="messageBox">
<table style="width:100%;">
<tfoot>
<tr>
<th colspan="2"></th>
</tr>
</tfoot>
<tbody>
<tr>
<th style="text-align:right; padding-right:10px; width:60px;"><?php echo $language->received; ?></th>
<td><?php echo TimeHelper::weekDay($message->created).', '.TimeHelper::date($language->getCustom('/root/core/settings', 'date_format'), $message->created).', '.TimeHelper::date('H:i', $message->created); ?></td>
</tr>
<tr>
<th style="text-align:right; padding-right:10px;"><?php echo $language->from;?>:</th>
<td><?php echo $systemUserName;?></td>
</tr>
<tr>
<th style="text-align:right; padding-right:10px;"><?php echo $language->subject?>:</th>
<td><?php echo $message->subject; ?></td>
</tr>
</tbody>
</table>
<div class="msgBodyDisplayBox">
<?php echo Bbcode::parse($message->message); ?>
</div>
</div>
| lockdoc/sweany | usr/plugins/Message/pages/view/read_alert.tpl.php | PHP | gpl-2.0 | 1,531 |
<?php
/* --------------------------------------------------------------
AdminContentView.inc.php 2011-04-27 gambio
Gambio GmbH
http://www.gambio.de
Copyright (c) 2011 Gambio GmbH
Released under the GNU General Public License (Version 2)
[http://www.gnu.org/licenses/gpl-2.0.html]
--------------------------------------------------------------
based on:
(c) 2000-2001 The Exchange Project (earlier name of osCommerce)
(c) 2002-2003 osCommercebased on original files FROM OSCommerce CVS 2.2 2002/08/28 02:14:35 www.oscommerce.com
(c) 2003 nextcommerce (admin.php,v 1.12 2003/08/13); www.nextcommerce.org
(c) 2003 XT-Commerce - community made shopping http://www.xt-commerce.com ($Id: admin.php 1262 2005-09-30 10:00:32Z mz $)
Released under the GNU General Public License
---------------------------------------------------------------------------------------*/
// include needed functions
require_once(DIR_FS_INC . 'xtc_image_button.inc.php');
class AdminContentView extends ContentView
{
function AdminContentView()
{
$this->set_content_template('boxes/box_admin.html');
$this->set_caching_enabled(false);
}
function get_html($p_coo_product)
{
global $cPath;
$t_orders_contents = '';
$t_orders_status_validating = xtc_db_num_rows(xtc_db_query("SELECT orders_status FROM " . TABLE_ORDERS ." where orders_status ='0'"));
$t_url = "'".xtc_href_link_admin(FILENAME_ORDERS, 'SELECTed_box=customers&status=0', 'NONSSL')."'";
if($_SESSION['style_edit_mode'] == 'edit')
{
$t_orders_contents .= '<a href="#" onclick="if(confirm(\'' . ADMIN_LINK_INFO_TEXT . '\')){window.location.href='.$t_url.'; return false;} return false;">' . TEXT_VALIDATING . '</a>: ' . $t_orders_status_validating . '<br />';
}
else
{
$t_orders_contents .= '<a href="#" onclick="window.location.href='.$t_url.'; return false;">' . TEXT_VALIDATING . '</a>: ' . $t_orders_status_validating . '<br />';
}
$t_result = xtc_db_query("SELECT
orders_status_name,
orders_status_id
FROM " . TABLE_ORDERS_STATUS . "
WHERE language_id = '" . (int)$_SESSION['languages_id'] . "'");
while($t_orders_status_array = xtc_db_fetch_array($t_result))
{
$t_result2 = xtc_db_query("SELECT count(*) AS count
FROM " . TABLE_ORDERS . "
WHERE orders_status = '" . $t_orders_status_array['orders_status_id'] . "'");
$t_orders_pending_array = xtc_db_fetch_array($t_result2);
$t_url = "'".xtc_href_link_admin(FILENAME_ORDERS, 'selected_box=customers&status=' . $t_orders_status_array['orders_status_id'], 'NONSSL')."'";
if($_SESSION['style_edit_mode'] == 'edit')
{
$t_orders_contents .= '<a href="#" onclick="if(confirm(\'' . ADMIN_LINK_INFO_TEXT . '\')){window.location.href='.$t_url.'; return false;} return false;">' . $t_orders_status_array['orders_status_name'] . '</a>: ' . $t_orders_pending_array['count'] . '<br />';
}
else
{
$t_orders_contents .= '<a href="#" onclick="window.location.href='.$t_url.'; return false;">' . $t_orders_status_array['orders_status_name'] . '</a>: ' . $t_orders_pending_array['count'] . '<br />';
}
}
$t_orders_contents = substr($t_orders_contents, 0, -6);
$t_result3 = xtc_db_query("SELECT count(*) AS count FROM " . TABLE_CUSTOMERS);
$t_customers_array = xtc_db_fetch_array($t_result3);
$t_result4 = xtc_db_query("SELECT count(*) AS count FROM " . TABLE_PRODUCTS . " where products_status = '1'");
$t_products_array = xtc_db_fetch_array($t_result4);
$t_result5 = xtc_db_query("SELECT count(*) AS count FROM " . TABLE_REVIEWS);
$t_reviews_array = xtc_db_fetch_array($t_result5);
$t_admin_image = '<a href="' . xtc_href_link_admin(FILENAME_START,'', 'NONSSL').'">'.xtc_image_button('button_admin.gif', IMAGE_BUTTON_ADMIN).'</a>';
$this->set_content_data('BUTTON_ADMIN_URL', xtc_href_link_admin(FILENAME_START,'', 'NONSSL'));
if($p_coo_product->isProduct())
{
if($_SESSION['style_edit_mode'] == 'edit')
{
$t_admin_link='<a href="' . xtc_href_link_admin(FILENAME_EDIT_PRODUCTS, 'cPath=' . $cPath . '&pID=' . $p_coo_product->data['products_id'], 'NONSSL') . '&action=new_product' . '" onclick="if(confirm(\'' . ADMIN_LINK_INFO_TEXT . '\')){window.open(this.href); return false;} return false;">' . xtc_image_button('edit_product.gif', IMAGE_BUTTON_PRODUCT_EDIT, 'style="margin-top:4px"') . '</a>';
}
else
{
$t_admin_link='<a href="' . xtc_href_link_admin(FILENAME_EDIT_PRODUCTS, 'cPath=' . $cPath . '&pID=' . $p_coo_product->data['products_id'], 'NONSSL') . '&action=new_product' . '" onclick="window.open(this.href); return false;">' . xtc_image_button('edit_product.gif', IMAGE_BUTTON_PRODUCT_EDIT, 'style="margin-top:4px"') . '</a>';
}
$this->set_content_data('BUTTON_EDIT_PRODUCT_URL', xtc_href_link_admin(FILENAME_EDIT_PRODUCTS, 'cPath=' . $cPath . '&pID=' . $p_coo_product->data['products_id'] . '&action=new_product', 'NONSSL'));
}
$t_content= '<strong>' . BOX_TITLE_STATISTICS . '</strong><br />' . $t_orders_contents . '<br />' .
BOX_ENTRY_CUSTOMERS . ' ' . $t_customers_array['count'] . '<br />' .
BOX_ENTRY_PRODUCTS . ' ' . $t_products_array['count'] . '<br />' .
BOX_ENTRY_REVIEWS . ' ' . $t_reviews_array['count'] .'<br />';
if($_SESSION['style_edit_mode'] == 'edit')
{
$this->set_content_data('ADMIN_LINK_INFO', ADMIN_LINK_INFO_TEXT);
}
$this->set_content_data('CONTENT', $t_content);
$t_html_output = $this->build_html();
return $t_html_output;
}
}
?> | pobbes/gambio | templates/sh-webshop/source/classes/AdminContentView.inc.php | PHP | gpl-2.0 | 5,537 |
using UnityEngine;
public class ItemSpawnEffector : MonoBehaviour
{
public float xzAngle = 0;
public float xzSpeed = 0;
float _time = 1.5f;
float _elapsed;
float _frequency;
float _prevSin;
Collider _collider;
void Start()
{
_frequency = Mathf.PI * 2 * 0.5f / _time;
_prevSin = Mathf.Sin(_elapsed * _frequency);
_collider = GetComponent<Collider>();
_collider.enabled = false;
}
void Update()
{
if (_elapsed / _frequency < _time)
{
var y = (Mathf.Sin(_elapsed) - _prevSin);
var xzDelta = xzSpeed * Time.deltaTime * 2;
transform.position += new Vector3(Mathf.Sin(xzAngle) * xzDelta, y * 2f, Mathf.Cos(xzAngle) * xzDelta);
_prevSin = Mathf.Sin(_elapsed);
_elapsed += Time.deltaTime * _frequency;
}
else
{
_collider.enabled = true;
enabled = false;
}
}
} | Lobo-Prix/TeraTale | TeraTale/Assets/Games/Entities/Items/ItemSpawnEffector.cs | C# | gpl-2.0 | 973 |
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2009-2013 Kai Willadsen <kai.willadsen@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import math
from gi.repository import Gtk
from meld.misc import get_common_theme
from meld.settings import meldsettings
# Rounded rectangle corner radius for culled changes display
RADIUS = 3
class LinkMap(Gtk.DrawingArea):
__gtype_name__ = "LinkMap"
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed)
def associate(self, filediff, left_view, right_view):
self.filediff = filediff
self.views = [left_view, right_view]
if self.get_direction() == Gtk.TextDirection.RTL:
self.views.reverse()
self.view_indices = [filediff.textview.index(t) for t in self.views]
self.on_setting_changed(meldsettings, 'style-scheme')
def on_setting_changed(self, settings, key):
if key == 'style-scheme':
self.fill_colors, self.line_colors = get_common_theme()
def do_draw(self, context):
if not self.filediff:
return
context.set_line_width(1.0)
allocation = self.get_allocation()
pix_start = [t.get_visible_rect().y for t in self.views]
y_offset = [
t.translate_coordinates(self, 0, 0)[1] + 1 for t in self.views]
clip_y = min(y_offset) - 1
clip_height = max(t.get_visible_rect().height for t in self.views) + 2
context.rectangle(0, clip_y, allocation.width, clip_height)
context.clip()
height = allocation.height
visible = [self.views[0].get_line_num_for_y(pix_start[0]),
self.views[0].get_line_num_for_y(pix_start[0] + height),
self.views[1].get_line_num_for_y(pix_start[1]),
self.views[1].get_line_num_for_y(pix_start[1] + height)]
wtotal = allocation.width
# For bezier control points
x_steps = [-0.5, (1. / 3) * wtotal, (2. / 3) * wtotal, wtotal + 0.5]
q_rad = math.pi / 2
left, right = self.view_indices
view_offset_line = lambda v, l: (self.views[v].get_y_for_line_num(l) -
pix_start[v] + y_offset[v])
for c in self.filediff.linediffer.pair_changes(left, right, visible):
# f and t are short for "from" and "to"
f0, f1 = [view_offset_line(0, l) for l in c[1:3]]
t0, t1 = [view_offset_line(1, l) for l in c[3:5]]
# We want the last pixel of the previous line
f1 = f1 if f1 == f0 else f1 - 1
t1 = t1 if t1 == t0 else t1 - 1
# If either endpoint is completely off-screen, we cull for clarity
if (t0 < 0 and t1 < 0) or (t0 > height and t1 > height):
if f0 == f1:
continue
context.arc(x_steps[0], f0 - 0.5 + RADIUS, RADIUS, -q_rad, 0)
context.arc(x_steps[0], f1 - 0.5 - RADIUS, RADIUS, 0, q_rad)
context.close_path()
elif (f0 < 0 and f1 < 0) or (f0 > height and f1 > height):
if t0 == t1:
continue
context.arc_negative(x_steps[3], t0 - 0.5 + RADIUS, RADIUS,
-q_rad, q_rad * 2)
context.arc_negative(x_steps[3], t1 - 0.5 - RADIUS, RADIUS,
q_rad * 2, q_rad)
context.close_path()
else:
context.move_to(x_steps[0], f0 - 0.5)
context.curve_to(x_steps[1], f0 - 0.5,
x_steps[2], t0 - 0.5,
x_steps[3], t0 - 0.5)
context.line_to(x_steps[3], t1 - 0.5)
context.curve_to(x_steps[2], t1 - 0.5,
x_steps[1], f1 - 0.5,
x_steps[0], f1 - 0.5)
context.close_path()
context.set_source_rgba(*self.fill_colors[c[0]])
context.fill_preserve()
chunk_idx = self.filediff.linediffer.locate_chunk(left, c[1])[0]
if chunk_idx == self.filediff.cursor.chunk:
highlight = self.fill_colors['current-chunk-highlight']
context.set_source_rgba(*highlight)
context.fill_preserve()
context.set_source_rgba(*self.line_colors[c[0]])
context.stroke()
def do_scroll_event(self, event):
self.filediff.next_diff(event.direction)
class ScrollLinkMap(Gtk.DrawingArea):
__gtype_name__ = "ScrollLinkMap"
def __init__(self):
self.melddoc = None
def associate(self, melddoc):
self.melddoc = melddoc
def do_scroll_event(self, event):
if not self.melddoc:
return
self.melddoc.next_diff(event.direction)
| Spitfire1900/meld | meld/linkmap.py | Python | gpl-2.0 | 5,512 |
package cs342.Chat.GUI.custom;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.text.*;
import java.awt.*;
import java.util.HashMap;
public class ChatArea {
private ChatPane cstmPane;
private JScrollBar vertical;
public final JScrollPane SCROLL_PANE;
private HashMap<String, StyledDocument> CONVO_TO_DOC;
public ChatArea() {
SCROLL_PANE = new JScrollPane();
CONVO_TO_DOC = new HashMap<String, StyledDocument>();
cstmPane = new ChatPane();
SCROLL_PANE.setViewportBorder(new LineBorder(new Color(0, 0, 0)));
SCROLL_PANE.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
SCROLL_PANE.setViewportView(cstmPane);
vertical = SCROLL_PANE.getVerticalScrollBar();
}
public void showChat(String entry) {
cstmPane.doc = CONVO_TO_DOC.get(entry);
cstmPane.setStyledDocument(cstmPane.doc);
}
public void createNewChat(String convo) {
CONVO_TO_DOC.put(convo, new DefaultStyledDocument());
}
public void removeChat(String convo) {
CONVO_TO_DOC.remove(convo);
}
public void clientPrint(String line, String who, String where) {
cstmPane.doc = CONVO_TO_DOC.get(where);
cstmPane.clientPrint(line, who);
setScrollBarMinimum();
}
public void serverPrint(String line, String who, String where) {
cstmPane.doc = CONVO_TO_DOC.get(where);
cstmPane.serverPrint(line, who);
setScrollBarMinimum();
}
private void setScrollBarMinimum() {
vertical.setValue( vertical.getMinimum());
}
private class ChatPane extends JTextPane {
private static final long serialVersionUID = 1L;
private StyledDocument doc;
private Style style;
private SimpleAttributeSet align;
private Color BACKGROUND = new Color(47, 79, 79);
private Color CLIENT_COLOR = new Color(255, 69, 0);
private Color SERVER_COLOR = new Color(0, 69, 255).brighter();
private Insets MARGINS = new Insets(5, 5, 5, 5);
private String FONT_NAME = "Calibri";
private int FONT_SIZE = 16;
private ChatPane() {
super();
super.setEditorKit(new WrapEditorKit());
super.setEditable(false);
super.setBackground(BACKGROUND);
super.setMargin(MARGINS);
style = this.addStyle("STYLE", null);
align = new SimpleAttributeSet();
StyleConstants.setFontFamily(style, FONT_NAME);
StyleConstants.setFontSize(style, FONT_SIZE);
StyleConstants.setBold(style, true);
}
private void clientPrint(String line, String who) {
StyleConstants.setAlignment(align, StyleConstants.ALIGN_RIGHT);
StyleConstants.setForeground(style, CLIENT_COLOR);
print(line + "\n");
}
private void serverPrint(String line, String who) {
StyleConstants.setAlignment(align, StyleConstants.ALIGN_LEFT);
StyleConstants.setForeground(style, SERVER_COLOR.brighter());
print(who + ": ");
StyleConstants.setForeground(style, SERVER_COLOR);
print(line + "\n");
}
private void print(String line) {
try {
doc.setParagraphAttributes(doc.getLength(), line.length(),
align, false);
doc.insertString(doc.getLength(), line, style);
} catch (BadLocationException e) {
}
}
}
} | TomasJuocepis/CS342-ChatApp | src/cs342/Chat/GUI/custom/ChatArea.java | Java | gpl-2.0 | 3,081 |
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require('apuesta.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<title>Apuestas</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap theme -->
<link href="css/bootstrap-theme.min.css" rel="stylesheet" />
<!-- Custom styles for this template -->
<link href="css/theme.css" rel="stylesheet" />
<link href="css/apuestas.css" rel="stylesheet" />
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body role="document">
<!-- Fixed navbar -->
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Ap</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">C</a></li>
<li><a href="apostar.php">A</a></li>
<li><a href="resultados.php">Res</a></li>
<li><a href="reglas.php">Reg</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<form id="crear" action="crear.php">
<div class="row">
<div class="col-md-3">
<label for="nombre">Nombre</label>
</div>
<div class="col-md-9">
<input id="nombre" name="nombre" type="text" />
</div>
</div>
<div class="row">
<div class="col-md-3">
<label for="participantes">Participantes</label>
<p>
Lorem ipsum.
</p>
</div>
<div class="col-md-9">
<textarea id="participantes" name="emails" rows="6"></textarea>
</div>
</div>
<p>
<button form="crear" formaction="crear.php" formmethod="post" type="submit" class="btn btn-lg btn-default">Go for it</button>
</p>
</form>
<?php
if(isset($_POST) && isset($_POST['nombre']) && isset($_POST['emails'])) {
$a = new Apuesta();
$duelo = $a->saveDuelo($_POST['nombre'], $_POST['emails']);
?>
<div class="alert alert-success">
<strong>¡Tu duelo se ha creado!</strong> (<?php echo $duelo['jugadores']; ?> participantes).
</div>
<?php
}
?>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/docs.min.js"></script>
</body>
</html>
| cgortaris/apuestasB2014 | src/crear.php | PHP | gpl-2.0 | 4,035 |
<div class="twelve columns alpha">
<h3 class="headline">Descrição do Projeto</h3><span class="line"></span><div class="clearfix"></div>
<p>A casa de energia de Itaipu foi em busca de um sistema de gerenciamento de documentos (DMS) para acompanhar a documentação de seus projetos. Em seguida, eles nos contatou e foram apresentados a eles algumas soluções possíveis.</p>
<p>Uma das possíveis soluções foi o OpenKM entre outros. E este software completamente cumprido as suas necessidades.</p>
<p>OpenKM é um aplicativo de gerenciamento de documentos baseado na web que usam padrões e tecnologias Open Source. OpenKM Fornece recursos de gerenciamento de documento completo, incluindo acompanhamento e histórico de versão de arquivo, metadados, digitalização, fluxo de trabalho, pesquisa e muito mais.</p>
<p>O celtab ajudou a migrar para esta plataforma e atualmente é responsável pela manutenção de software.</p>
<p><strong>Pesquisador:</strong> Mario Villagra</p>
</div>
<!-- Job Description -->
<div class="four columns omega">
<h3 class="headline">Detalhes do Projeto</h3><span class="line"></span><div class="clearfix"></div>
<ul style="margin: 2px 0 18px 0;" class="list-3">
<li>JavaEE</li>
<li>Tomcat</li>
</ul>
<div class="clearfix"></div>
</div> | IngCarlosColman/SiteCeltab | CONTENIDOS/Portugues/Proyectos/OpenKM-Itaipú.php | PHP | gpl-2.0 | 1,324 |
// $Revision$ $Author$ $Date$
/*
Copyright (C) 2004 Kurt Schwehr
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/// \file
/// \brief Non-graphical rendering engine for waypoints, iv files, and
/// SIM Voleon models
/// This describes how to do animation:
/// file:///sw/share/Coin/html/classSoOffscreenRenderer.html
/***************************************************************************
* INCLUDES
***************************************************************************/
// c includes
#include <cstdio>
#include <cassert>
// C++ includes
#include <iostream>
#include <fstream>
#include <sstream> // string stream
// STL includes
#include <vector>
#include <string>
//
// Inventor/Coin
//
// Top level includes
#include <Inventor/SoInteraction.h>
#include <Inventor/SoOffscreenRenderer.h>
#include <Inventor/SoOutput.h>
// Sensors
//#include <Inventor/sensors/SoTimerSensor.h>
// Actions
#include <Inventor/actions/SoWriteAction.h>
// Events
#include <Inventor/events/SoMouseButtonEvent.h>
#include <Inventor/events/SoLocation2Event.h>
#include <Inventor/events/SoKeyboardEvent.h>
// Nodes
#include <Inventor/nodes/SoEventCallback.h>
#include <Inventor/nodes/SoNode.h>
#include <Inventor/nodes/SoCamera.h>
#include <Inventor/nodes/SoPerspectiveCamera.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/nodes/SoSwitch.h>
#include <Inventor/nodes/SoPointLight.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/nodes/SoLineSet.h>
#include <Inventor/nodes/SoCoordinate3.h>
// Draggers
//#include <Inventor/draggers/SoTranslate1Dragger.h>
#include <Inventor/draggers/SoSpotLightDragger.h>
// Voleon Includes
#ifndef NO_VOLEON
#include <VolumeViz/nodes/SoVolumeRendering.h>
#endif
// local includes
#include "render_cmd.h"
#include "InventorUtilities.H"
using namespace std;
/***************************************************************************
* MACROS, DEFINES, GLOBALS
***************************************************************************/
// FIX: this needs to be a separate header
SoSeparator *MakeSoLineSet (vector<SoSpotLightDragger *> &draggerVec);
#include "debug.H" // provides FAILED_HERE, UNUSED, DebugPrintf
int debug_level=0;
/// Let the debugger find out which version is being used.
static const UNUSED char* RCSid ="$Id$";
/***************************************************************************
* SCENEINFO - the big global variable
***************************************************************************/
//#include <Inventor/nodes/SoDirectionalLight.h>
class SceneInfo {
public:
SceneInfo();
SoCamera *camera;
SoSeparator *root;
vector<SoSpotLightDragger *> draggerVec; ///< All of the draggers that have been added.
SoSwitch *draggerSwitch; ///< On/off of the separators. May add code to show one at a time
//SoDirectionalLight *headlight;
SoPointLight *headlight; ///< if this is not NULL, then move with camera
gengetopt_args_info *a; ///< a for args. These are the command line arguments
/// Use magic numbers to make sure you actually get this class when you
/// must do a cast to/from void pointer
static uint8_t nominalMagicNumber() {return(178);}
bool magicOk() const {return(nominalMagicNumber()==magicNumber);} ///< Test the class integrity
private:
uint8_t magicNumber; ///< Help make sure we have a valid SceneInfo structure
};
/// Make a SceneInfo object with all pointers set to zero and not animating
SceneInfo::SceneInfo() {
magicNumber = nominalMagicNumber();
camera = 0; root = 0; draggerSwitch = 0; draggerSwitch = 0;
a = 0;
headlight=0;
}
/***************************************************************************
* UTILITUES
***************************************************************************/
void Print (const SoCamera *camera) {
assert (camera);
const SoSFVec3f *p = &camera->position;
SbVec3f p_sb= p->getValue();
float x,y,z;
p_sb.getValue(x,y,z);
const SoSFRotation *o = &camera->orientation;
SbRotation o_sb = o->getValue();
SbVec3f axis;
float radians;
o_sb.getValue(axis,radians);
float ax,ay,az;
axis.getValue(ax,ay,az);
cout << "Camera -> pos: " << x << " " << y << " " << y << " -- rot: "
<< ax << " " << ay << " " << az << " " << radians << endl;
}
/***************************************************************************
* TIMER FOR ANIMATION
***************************************************************************/
/// \brief Return a lineset that does through all the dragger waypoints
///
/// Would be better if I did what Alex did back in `98 and use engines with
/// the draggers so the line gets automatically updated with drags
SoSeparator *MakeSoLineSet (vector<SoSpotLightDragger *> &draggerVec) {
DebugPrintf(TRACE,("MakeSoLineSet with %d waypoints\n",int(draggerVec.size())));
SoLineSet *lines = new SoLineSet;
if (!lines) {cerr << "ERROR: Unable to allocate lines"<<endl;return 0;}
SoCoordinate3 *coords = new SoCoordinate3;
if (!coords) {cerr << "ERROR: Unable to allocate lines"<<endl; lines->ref(); lines->unref();return 0;}
SoSeparator *sep = new SoSeparator;
// FIX error check
sep->addChild(coords);
sep->addChild(lines);
for (size_t i=0;i<draggerVec.size();i++) {
SbVec3f xyz(draggerVec[i]->translation.getValue());
float x, y, z;
xyz.getValue(x,y,z);
coords->point.set1Value(i,x,y,z);
}
lines->numVertices.setValue(draggerVec.size());
return(sep);
}
/// \brief Tell if a value is between 2 numbers, inclusive
/// \return \a true if v1<=check<=v2 or v2<=check<=v1
bool InRange (const float check, const float v1, const float v2) {
float a,b;
if (v1<v2) {a=v1;b=v2;} else {a=v2;b=v1;}
if (check < a || check > b) return (false);
return (true);
}
/// \brief interpolate between two draggers and render a frame to disk
bool WaypointRenderFrameToDisk (const SoSpotLightDragger *d1, const SoSpotLightDragger *d2,
const float cur_percent, SoCamera *camera,
const string &basename, const string &typeStr,
const int width, const int height,
SoNode *root, size_t &frame_num, SoPointLight *headlight
)
{
assert(d1); assert(d2);
assert(camera); assert(root);
SbVec3f pos1 = d1->translation.getValue();
SbVec3f pos2 = d2->translation.getValue();
vector<float> v1 = ToVector(pos1);
vector<float> v2 = ToVector(pos2);
vector<float> v3 = InterpolatePos (v1,v2,cur_percent);
SbVec3f pos3 = ToSbVec3f (v3);
camera->position = pos3;
SbRotation rot1 = d1->rotation.getValue();
SbRotation rot2 = d2->rotation.getValue();
SbRotation newRot = SbRotation::slerp (rot1, rot2, cur_percent);
camera->orientation = newRot;
if (headlight) { headlight->location = pos3; }
#ifndef NDEBUG
if (debug_level >= VERBOSE) Print(camera); // Show some camera locations!
#endif
DebugPrintf (TRACE,("ANIMATION: Rendering frame to disk file\n"));
SbColor background(0,0,0); // FIX: do background colors!
if (!RenderFrameToDisk (basename,typeStr, width, height, root, frame_num, background) ) {
cerr << "ERROR: unable to write frame" << endl;
return (false);
}
DebugPrintf(VERBOSE,("ANIMATION: Finished writing frame number %04d\n",int(frame_num)));
return (true);
}
/***************************************************************************
* MAIN
***************************************************************************/
int main(int argc, char *argv[])
{
bool ok=true;
gengetopt_args_info a; // a == args
if (0!=cmdline_parser(argc,argv,&a)){cerr<<"MELT DOWN: should never get here"<<endl;return (EXIT_FAILURE);}
#ifdef NDEBUG
if (a.verbosity_given) {
cerr << "Verbosity is totally ignored for optimized code. Continuing in silent mode" << endl;
}
#else // debugging
debug_level = a.verbosity_arg;
DebugPrintf(TRACE,("Debug level = %d\n",debug_level));
#endif
if (!CheckLibraryPath()) { cerr << "Bailing. Library path check failed." << endl; return(EXIT_FAILURE);}
if (a.list_given) { ListWriteFileTypes(); return (EXIT_SUCCESS); }
//
// Check range of arguments
//
if (a.percent_given)
if (!InRange(a.percent_arg,0.0,1.0)) {cerr<<"ERROR: Interval must be 0.0<=i<=1.0"<<endl; return (EXIT_FAILURE);}
//
// Init the SoDB and SimVoleon - no SoQT!
//
SoDB::init();
SoInteraction::init(); // Initialize for draggers
#ifndef NO_VOLEON
SoVolumeRendering::init();
#endif
if (a.type_given)
if (!CheckTypeValid(string(a.type_arg)))
{ cerr << "File type not valid: --type=" << a.type_arg << endl; return (EXIT_FAILURE); }
DebugPrintf(VERBOSE,("FIX: check the range on width and height!\n"));
SceneInfo *si = new SceneInfo;
si->a=&a;
si->root = new SoSeparator;
si->root->ref();
{
// Need a camera in the scene for the SoOffscreenRender to work
si->camera = new SoPerspectiveCamera;
si->root->addChild(si->camera);
si->camera->nearDistance=a.near_arg;
si->camera-> farDistance=a.far_arg;
}
if (a.headlight_flag) {
//si->headlight = new SoDirectionalLight;
si->headlight = new SoPointLight;
si->root->addChild(si->headlight);
}
// FIX: do something better with the lights
// TOP light
{ SoPointLight *pl = new SoPointLight; si->root->addChild(pl); pl->location = SbVec3f(0.0f,0.0f,50.0f); }
// BOT light
{ SoPointLight *pl = new SoPointLight; si->root->addChild(pl); pl->location = SbVec3f(0.0f,0.0f,-50.0f); }
for (size_t i=0;i<a.inputs_num;i++) {
DebugPrintf (TRACE,("Adding file: %s\n",a.inputs[i]));
SoInput mySceneInput;
if ( !mySceneInput.openFile( a.inputs[i] )) return (EXIT_FAILURE);
SoSeparator* node = SoDB::readAll(&mySceneInput);
if ( !node ) {cerr << "failed to load iv file: "<<a.inputs[i] << endl; return (EXIT_FAILURE);}
mySceneInput.closeFile();
si->root->addChild(node);
}
// Move this to the SceneInfo constructor
{
SoSwitch *s = new SoSwitch(40); // We expect a lot of children.
assert(s);
s->setName ("draggerSwitch");
s->whichChild = SO_SWITCH_ALL; // SO_SWITCH_NONE
si->root->addChild(s);
si->draggerSwitch=s;
}
if (!LoadSpotLightDraggers(string(a.waypoints_arg), (SoSeparator *)si->draggerSwitch, si->draggerVec)) {
cerr << "ERROR: failed to load waypoints. We're toast." << endl;
exit (EXIT_FAILURE);
}
si->draggerSwitch->whichChild = SO_SWITCH_NONE; // don't show our path
if (2>si->draggerVec.size()) {
cerr << "ERROR: you must have at least two waypoints in your .wpt file" << endl;
exit (EXIT_FAILURE);
}
if (a.loop_flag) {
cout << "Adding first waypoint to the end to form a loop" << endl;
si->draggerVec.push_back(si->draggerVec[0]);
}
//////////////////////////////
// ANIMATE - no timer needed!
//////////////////////////////
const string basenameStr(a.basename_arg);
const string typeStr(a.type_arg);
// -1 cause we do not want to render past last waypoint
// we are going from the current way point in wpt to the next waypoint
// FIX: don't miss last frame
for (size_t wpt=0;wpt<si->draggerVec.size()-1; wpt++) {
cout << "Now at waypoint " << wpt << " going to " << wpt+1 << endl;
SoSpotLightDragger *d1 = si->draggerVec[wpt];
SoSpotLightDragger *d2 = si->draggerVec[wpt+1];
assert (d1); assert(d2);
for (float cur_percent=0.; cur_percent < 1.0; cur_percent += a.percent_arg) {
cout << "percent: " << cur_percent << endl;
size_t frame_num;
const bool r = WaypointRenderFrameToDisk (d1,d2, cur_percent, si->camera,
basenameStr, typeStr,
a.width_arg, a.height_arg,
si->root, frame_num,
si->headlight
);
if (!r) {
cerr << "ERROR: failed to write a frame. I give up." << endl;
exit(EXIT_FAILURE);
}
} // for cur_percent
} // for wpt
// Render that last missing frame. If looping to start, we do not need this frame
if (!a.loop_flag) {
DebugPrintf (TRACE,("Rendering final frame.\n"));
size_t frame_num;
const bool r = WaypointRenderFrameToDisk (si->draggerVec[si->draggerVec.size()-1],
si->draggerVec[si->draggerVec.size()-1],
0., si->camera,
basenameStr, typeStr,
a.width_arg, a.height_arg,
si->root, frame_num,
si->headlight
);
if (!r) {
cerr << "ERROR: failed to write a frame. I give up." << endl;
exit(EXIT_FAILURE);
}
}
return (ok?EXIT_SUCCESS:EXIT_FAILURE);
}
| schwehr/density | render.C | C++ | gpl-2.0 | 13,140 |
package com.t3.server.database.businesslogic;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.t3.server.database.entities.User;
public class UserHelper {
public final static int CREATE_USER_SUCCESS = 0x0001;
public final static int CREATE_USER_EXISTED = 0x0002;
public final static int CREATE_USER_FAIL = 0x0003;
private final static String TABLE_NAME = "User";
private final static String NAME = "Name";
private final static String RATING = "Rating";
private final static String WINS = "Wins";
private final static String LOSES = "Loses";
private final static String DRAWS = "Draws";
private final static String AID = "AID";
private Connection conn;
public UserHelper() throws Exception {
conn = ConnectionFactory.getInstance();
}
/**
* @param accountId : need for get user
* @return database user object
* @throws SQLException
*/
public User getUser(int accountId) throws SQLException {
String sql = "SELECT TOP(1) * FROM [" + TABLE_NAME + "] WHERE " + AID + " = ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, accountId);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return new User(resultSet.getString(NAME),
resultSet.getInt(RATING),
resultSet.getInt(WINS),
resultSet.getInt(LOSES),
resultSet.getInt(DRAWS),
resultSet.getInt(AID));
}
return null;
}
public User getUser(String username) throws SQLException {
String sql = "SELECT TOP(1) * FROM [" + TABLE_NAME + "] WHERE " + NAME + " LIKE ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, username);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return new User(resultSet.getString(NAME),
resultSet.getInt(RATING),
resultSet.getInt(WINS),
resultSet.getInt(LOSES),
resultSet.getInt(DRAWS),
resultSet.getInt(AID));
}
return null;
}
/**
* This method for get common user for send from server to client
* @param accountId
* @return
* @throws SQLException
*/
public com.t3.common.models.User getCommonUser(int accountId) throws SQLException {
String sql = "SELECT TOP(1) * FROM [" + TABLE_NAME + "] WHERE " + AID + " = ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, accountId);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
return new com.t3.common.models.User(resultSet.getString(NAME),
resultSet.getInt(RATING),
resultSet.getInt(WINS),
resultSet.getInt(LOSES),
resultSet.getInt(DRAWS));
}
return null;
}
/**
* @param user object need to create new
* @return true if create success, false if create fail
* @throws SQLException
*/
public int create(User user) throws SQLException {
if (getUser(user.getName()) != null) {
return CREATE_USER_EXISTED;
}
String sql = "INSERT INTO [" + TABLE_NAME + "]" + " ([" + NAME + "], [" + AID + "])" +
" VALUES (?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, user.getName());
statement.setInt(2, user.getAid());
return (statement.executeUpdate() > 0) ? CREATE_USER_SUCCESS : CREATE_USER_FAIL;
}
public boolean update(com.t3.common.models.User user) throws SQLException {
String sql = "UPDATE [" + TABLE_NAME + "] SET " + RATING + " = ?, " +
WINS + " = ?, " +
LOSES + " = ?, " +
DRAWS + " = ? WHERE " + NAME + " LIKE ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, user.getRating());
statement.setInt(2, user.getWins());
statement.setInt(3, user.getLoses());
statement.setInt(4, user.getDraws());
statement.setString(5, user.getName());
return statement.executeUpdate() > 0;
}
}
| jackvt93/T3-Project--Tic---Tac---Toe-Game-Online- | T3Project/T3Server/src/com/t3/server/database/businesslogic/UserHelper.java | Java | gpl-2.0 | 4,019 |
import has from 'lodash/has';
import trim from 'lodash/trim';
import currencyFormatter from 'currency-formatter';
import { hasCurrencyCode } from '../utils/utils-settings';
import { maybeTrimHTML } from '../utils/utils-common';
import { getMoneyFormat, getShop } from '../ws/ws-shop';
import { showingLocalCurrency, getLocalCurrencyCodeCache, showingCurrencyCode } from './pricing-currency';
import { convertToLocalCurrency } from './pricing-conversion';
function priceSymbolMarkup(symbol) {
return '<span class="wps-product-price-currency" itemprop="priceCurrency">' + symbol + '</span>';
}
function priceAmountMarkup(amount) {
return '<span itemprop="price" class="wps-product-individual-price">' + amount + '</span>';
}
function priceMarkup(parts, amount) {
var priceMarkup = parts.map( ({type, value}) => {
switch (type) {
case 'currency': return priceSymbolMarkup(value) + priceAmountMarkup(amount);
default : return value;
}
});
return priceMarkup[0];
}
/*
locale currently not used
Config: {
locale: 'en-US',
countryCode: 'US',
amount: 123,
}
*/
function formatPrice(config) {
// Uses the browser locale by default
if ( !has(config, 'locale') ) {
config.locale = false;
}
var parts = new Intl.NumberFormat(config.locale, {
style: 'currency',
currency: config.countryCode,
currencyDisplay: config.currencyDisplay
}).formatToParts(config.amount);
return priceMarkup(parts, config.amount);
}
/*
"price" should always be preformatted
*/
function formatPriceToLocalCurrency(price) {
return formatPrice({
countryCode: getLocalCurrencyCodeCache(),
amount: price,
currencyDisplay: showingCurrencyCode() ? 'code' : 'symbol'
});
}
function formatPriceFromBase(price) {
return formatTotalAmount(price, maybeTrimHTML( getMoneyFormat( getShop() ) ) );
}
/*
Format product price into format from Shopify
*/
function maybeFormatPriceToLocalCurrency(price) {
if ( showingLocalCurrency() ) {
return formatPriceToLocalCurrency(price);
}
return formatPriceFromBase(price);
}
/*
Comes from Shopify
*/
function maybeAddCurrencyCodeToMoney(formatWithRealAmount) {
if ( hasCurrencyCode() ) {
return formatWithRealAmount + ' ' + getShop().currencyCode;
}
return formatWithRealAmount;
}
/*
Extract Money Format Type
*/
function extractMoneyFormatType(format) {
if (format) {
var newFormat = format;
newFormat = newFormat.split('{{').pop().split('}}').shift();
return newFormat.replace(/\s+/g, " ").trim();
} else {
return false;
}
}
/*
Formats the total amount
*/
function formatTotalAmount(amount, moneyFormat) {
var extractedMoneyFormat = extractMoneyFormatType(moneyFormat);
var formattedMoney = formatMoneyPerSetting(amount, extractedMoneyFormat, moneyFormat);
var formatWithRealAmount = replaceMoneyFormatWithRealAmount(formattedMoney, extractedMoneyFormat, moneyFormat);
formatWithRealAmount = formatWithRealAmount.replace(/ /g,'');
return maybeAddCurrencyCodeToMoney(formatWithRealAmount);
}
/*
Replace money format with real amount
*/
function replaceMoneyFormatWithRealAmount(formattedMoney, extractedMoneyFormat, moneyFormat = '') {
if (moneyFormat) {
var extractedMoneyFormat = new RegExp(extractedMoneyFormat, "g");
var finalPrice = trim(moneyFormat).replace(extractedMoneyFormat, formattedMoney);
finalPrice = finalPrice.replace(/{{/g, '');
finalPrice = finalPrice.replace(/}}/g, '');
return finalPrice;
}
}
/*
Format Money per settings
*/
function formatMoneyPerSetting(amount, format, origFormat) {
if (format === 'amount') {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: '.',
thousand: ',',
precision: 2,
format: '%v'
});
} else if (format === 'amount_no_decimals') {
amount = Number(amount);
amount = Math.round(amount);
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: '.',
thousand: ',',
precision: 0,
format: '%v'
});
} else if (format === 'amount_with_comma_separator') {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: ',',
thousand: ',',
precision: 2,
format: '%v'
});
} else if (format === 'amount_no_decimals_with_comma_separator') {
amount = Number(amount);
amount = Math.round(amount);
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: ',',
thousand: ',',
precision: 0,
format: '%v'
});
} else if (format === 'amount_with_space_separator') {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: ',',
thousand: ' ',
precision: 2,
format: '%v'
});
} else if (format === 'amount_no_decimals_with_space_separator') {
amount = Number(amount);
amount = Math.round(amount);
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: ',',
thousand: ' ',
precision: 0,
format: '%v'
});
} else if (format === 'amount_with_apostrophe_separator') {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: '.',
thousand: '\'',
precision: 2,
format: '%v'
});
} else {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: '.',
thousand: ',',
precision: 2,
format: '%v'
});
}
return string;
}
export {
formatPrice,
maybeFormatPriceToLocalCurrency
}
| arobbins/wp-shopify | public/js/app/pricing/pricing-format.js | JavaScript | gpl-2.0 | 5,602 |
var AbstractExtendedActivityDataModifier = Fiber.extend(function(base) {
return {
content: '',
isAuthorOfViewedActivity: null,
dataViews: [],
summaryGrid: null,
init: function(analysisData, appResources, userSettings, athleteId, athleteIdAuthorOfActivity, basicInfos) {
this.analysisData_ = analysisData;
this.appResources_ = appResources;
this.userSettings_ = userSettings;
this.athleteId_ = athleteId;
this.athleteIdAuthorOfActivity_ = athleteIdAuthorOfActivity;
this.basicInfos = basicInfos;
this.isAuthorOfViewedActivity = (this.athleteIdAuthorOfActivity_ == this.athleteId_);
this.speedUnitsData = this.getSpeedUnitData();
this.setDataViewsNeeded();
},
modify: function() {
_.each(this.dataViews, function(view) {
// Append result of view.render() to this.content
view.render();
this.content += view.getContent();
}.bind(this));
},
placeSummaryPanel: function(panelAdded) {
this.makeSummaryGrid(2, 4);
this.insertContentSummaryGridContent();
$('.inline-stats.section').first().after(this.summaryGrid.html()).each(function() {
// Grid placed
if (panelAdded) panelAdded();
});
},
placeExtendedStatsButton: function(buttonAdded) {
var htmlButton = '<section>';
htmlButton += '<a class="button btn-block btn-primary" id="extendedStatsButton" href="#">';
htmlButton += 'Show extended statistics';
htmlButton += '</a>';
htmlButton += '</section>';
$('.inline-stats.section').first().after(htmlButton).each(function() {
$('#extendedStatsButton').click(function() {
$.fancybox({
'width': '100%',
'height': '100%',
'autoScale': true,
'transitionIn': 'fade',
'transitionOut': 'fade',
'type': 'iframe',
'content': '<div class="stravistiXExtendedData">' + this.content + '</div>'
});
// For each view start making the assossiated graphs
_.each(this.dataViews, function(view) {
view.displayGraph();
}.bind(this));
}.bind(this));
if (buttonAdded) buttonAdded();
}.bind(this));
},
makeSummaryGrid: function(columns, rows) {
var summaryGrid = '';
summaryGrid += '<div>';
summaryGrid += '<div class="summaryGrid">';
summaryGrid += '<table>';
for (var i = 0; i < rows; i++) {
summaryGrid += '<tr>';
for (var j = 0; j < columns; j++) {
summaryGrid += '<td data-column="' + j + '" data-row="' + i + '">';
summaryGrid += '</td>';
}
summaryGrid += '</tr>';
}
summaryGrid += '</table>';
summaryGrid += '</div>';
summaryGrid += '</div>';
this.summaryGrid = $(summaryGrid);
},
insertContentAtGridPosition: function(columnId, rowId, data, title, units, userSettingKey) {
var onClickHtmlBehaviour = "onclick='javascript:window.open(\"" + this.appResources_.settingsLink + "#/commonSettings?viewOptionHelperId=" + userSettingKey + "\",\"_blank\");'";
if (this.summaryGrid) {
var content = '<span class="summaryGridDataContainer" ' + onClickHtmlBehaviour + '>' + data + ' <span class="summaryGridUnits">' + units + '</span><br /><span class="summaryGridTitle">' + title + '</span></span>';
this.summaryGrid.find('[data-column=' + columnId + '][data-row=' + rowId + ']').html(content);
} else {
console.error('Grid is not initialized');
}
},
insertContentSummaryGridContent: function() {
// Insert summary data
var moveRatio = '-';
if (this.analysisData_.moveRatio && this.userSettings_.displayActivityRatio) {
moveRatio = this.analysisData_.moveRatio.toFixed(2);
}
this.insertContentAtGridPosition(0, 0, moveRatio, 'Move Ratio', '', 'displayActivityRatio');
// ...
var TRIMP = activityHeartRateReserve = '-';
var activityHeartRateReserveUnit = '%';
if (this.analysisData_.heartRateData && this.userSettings_.displayAdvancedHrData) {
TRIMP = this.analysisData_.heartRateData.TRIMP.toFixed(0) + ' <span class="summarySubGridTitle">(' + this.analysisData_.heartRateData.TRIMPPerHour.toFixed(0) + ' / hour)</span>';
activityHeartRateReserve = this.analysisData_.heartRateData.activityHeartRateReserve.toFixed(0);
activityHeartRateReserveUnit = '% <span class="summarySubGridTitle">(Max: ' + this.analysisData_.heartRateData.activityHeartRateReserveMax.toFixed(0) + '% @ ' + this.analysisData_.heartRateData.maxHeartRate + 'bpm)</span>';
}
this.insertContentAtGridPosition(0, 1, TRIMP, 'TRaining IMPulse', '', 'displayAdvancedHrData');
this.insertContentAtGridPosition(1, 1, activityHeartRateReserve, 'Heart Rate Reserve Avg', activityHeartRateReserveUnit, 'displayAdvancedHrData');
// ...
var climbTime = '-';
var climbTimeExtra = '';
if (this.analysisData_.gradeData && this.userSettings_.displayAdvancedGradeData) {
climbTime = Helper.secondsToHHMMSS(this.analysisData_.gradeData.upFlatDownInSeconds.up);
climbTimeExtra = '<span class="summarySubGridTitle">(' + (this.analysisData_.gradeData.upFlatDownInSeconds.up / this.analysisData_.gradeData.upFlatDownInSeconds.total * 100).toFixed(0) + '% of time)</span>';
}
this.insertContentAtGridPosition(0, 2, climbTime, 'Time climbing', climbTimeExtra, 'displayAdvancedGradeData');
},
/**
* Affect default view needed
*/
setDataViewsNeeded: function() {
// By default we have... If data exist of course...
// Featured view
if (this.analysisData_) {
var featuredDataView = new FeaturedDataView(this.analysisData_, this.userSettings_, this.basicInfos);
featuredDataView.setAppResources(this.appResources_);
featuredDataView.setIsAuthorOfViewedActivity(this.isAuthorOfViewedActivity);
this.dataViews.push(featuredDataView);
}
// Heart view
if (this.analysisData_.heartRateData && this.userSettings_.displayAdvancedHrData) {
var heartRateDataView = new HeartRateDataView(this.analysisData_.heartRateData, 'hrr', this.userSettings_);
heartRateDataView.setAppResources(this.appResources_);
heartRateDataView.setIsAuthorOfViewedActivity(this.isAuthorOfViewedActivity);
this.dataViews.push(heartRateDataView);
}
},
getSpeedUnitData: function() {
var measurementPreference = currentAthlete.get('measurement_preference');
var units = (measurementPreference == 'meters') ? 'km' : 'mi';
var speedUnitPerhour = (measurementPreference == 'meters') ? 'km/h' : 'mi/h';
var speedUnitFactor = (speedUnitPerhour == 'km/h') ? 1 : 0.62137;
return [speedUnitPerhour, speedUnitFactor, units];
},
}
});
| nishanttotla/stravistix | hook/extension/js/modifiers/extendedActivityData/AbstractExtendedActivityDataModifier.js | JavaScript | gpl-2.0 | 7,842 |
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.IO;
using System.Web.Mvc;
namespace MathHouse.Server.Infrastructure
{
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}
public JsonSerializerSettings Settings { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("JSON GET is not allowed");
}
var response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data == null)
{
return;
}
var scriptSerializer = JsonSerializer.Create(this.Settings);
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}
} | IsfahanMathHouse/Server | Server/Infrastructure/JsonNetResult.cs | C# | gpl-2.0 | 1,384 |
<?php
/*
Plugin Name: WP Wrapper
Plugin URI: https://nabtron.com/wp-wrapper/
Description: Wrapper plugin for wordpress
Version: 1.2.5
Author: Nabtron
Author URI: https://nabtron.com/
Min WP Version: 5.0
Max WP Version: 5.8.1
*/
// declaring classes and functions
class Walker_PageDropdownnew extends Walker
{
var $tree_type = 'page';
var $db_fields = array('parent' => 'post_parent', 'id' => 'ID');
function start_el(&$output, $page, $depth = 0, $args = array(), $current_object_id = 0)
{
$pad = str_repeat(' ', $depth * 3);
$output .= "\t<option class=\"level-$depth\" value=\"$page->ID\"";
if ($page->ID == get_option("nabwrap_page"))
$output .= ' selected="selected"';
$output .= '>';
$title = esc_html($page->post_title);
$title = apply_filters('list_pages', $page->post_title, $page);
$output .= "$pad$title";
$output .= "</option>\n";
}
}
function walk_page_dropdown_treenew()
{
$args = func_get_args();
if (empty($args[2]['walker'])) // the user's options are the third parameter
$walker = new Walker_PageDropdownnew;
else
$walker = $args[2]['walker'];
return call_user_func_array(array(&$walker, 'walk'), $args);
}
function wp_dropdown_pagesnab($args = '')
{
$defaults = array(
'depth' => 0, 'child_of' => 0,
'selected' => 0, 'echo' => 1,
'name' => 'page_id', 'id' => '',
'show_option_none' => '', 'show_option_no_change' => '',
'option_none_value' => ''
);
$r = wp_parse_args($args, $defaults);
extract($r, EXTR_SKIP);
$pages = get_pages($r);
$output = '';
$name = esc_attr($name);
// Back-compat with old system where both id and name were based on $name argument
if (empty($id))
$id = $name;
if (!empty($pages)) {
$output = "<select name=\"$name\" id=\"$id\">\n";
$output .= walk_page_dropdown_treenew($pages, $depth, $r);
$output .= "</select>\n";
}
$output = apply_filters('wp_dropdown_pages', $output);
if ($echo)
echo $output;
}
function nabwrap_addlink()
{
$addlink_or_not = get_option("nabwrap_addlink");
$checked = '';
if ($addlink_or_not == '1') {
$checked = ' checked="yes" ';
}
$output = '<input type="checkbox" name="nabwrap_addlink" value="1" ' . $checked . '/>';
echo $output;
}
// Update routines
add_action('init', 'nabwrapper_init_func');
function nabwrapper_init_func()
{
if (empty($_POST['nabwrap_noncename'])) {
return;
}
if (!wp_verify_nonce($_POST['nabwrap_noncename'], plugin_basename(__FILE__))) {
return;
}
if (!current_user_can('manage_options')) {
return;
}
if ('insert' == $_POST['action_nabwrap']) {
update_option("nabwrap_url", esc_url_raw($_POST['nabwrap_url']));
update_option("nabwrap_page", sanitize_text_field($_POST['nabwrap_page']));
update_option("nabwrap_width", sanitize_text_field($_POST['nabwrap_width']));
update_option("nabwrap_height", sanitize_text_field($_POST['nabwrap_height']));
$nabwrap_border = intval($_POST['nabwrap_border']);
if (!$nabwrap_border) {
$nabwrap_border = '';
}
update_option("nabwrap_border", sanitize_text_field($nabwrap_border));
update_option("nabwrap_scroll", sanitize_text_field($_POST['nabwrap_scroll']));
update_option("nabwrap_addlink", sanitize_text_field($_POST['nabwrap_addlink'] ?? ''));
}
}
if (!class_exists('nabwrap_main')) {
class nabwrap_main
{
// PHP 4 Compatible Constructor
function nabwrap_main()
{
$this->__construct();
}
// PHP 5 Constructor
function __construct()
{
add_action('admin_menu', 'nabwrap_description_add_menu');
add_filter('the_content', 'get_nabwrapper_id');
}
}
function nabwrap_description_option_page()
{
?>
<!-- Start Options Admin area -->
<div class="wrap">
<h2>WP Wrapper Options</h2>
<div style="margin-top:20px;">
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>&updated=true">
<div style="">
<table class="form-table">
<tr>
<th scope="col" colspan="3" cellpadding="15"><strong>Settings</strong></th>
</tr>
<tr>
<th scope="row"><strong>Url</strong></th>
<td><input name="nabwrap_url" size="25" value="<?= esc_url(get_option("nabwrap_url")); ?>" type="text" />
Enter url with http:// or https://</td>
</tr>
<tr>
<th scope="row"><strong>Page</strong></th>
<td><?php wp_dropdown_pagesnab('name=nabwrap_page'); ?>
Select the page on which you want the wrapper to appear</td>
</tr>
<tr>
<th scope="row"><strong>width</strong></th>
<td><input name="nabwrap_width" size="10" value="<?= esc_attr(get_option("nabwrap_width")); ?>" type="text" />
specify width in px for the wrapper (can be in % too)</td>
</tr>
<tr>
<th scope="row"><strong>height</strong></th>
<td><input name="nabwrap_height" size="10" value="<?= esc_attr(get_option("nabwrap_height")); ?>" type="text" />
specify height in px for the wrapper (can be in % too)</td>
</tr>
<tr>
<th scope="row"><strong>border</strong></th>
<td><input name="nabwrap_border" size="10" value="<?= esc_attr(get_option("nabwrap_border")); ?>" type="text" />
Either 1 (yes) or 0 (no)</td>
</tr>
<tr>
<th scope="row"><strong>scroll</strong></th>
<td><input name="nabwrap_scroll" size="10" value="<?= esc_attr(get_option("nabwrap_scroll")); ?>" type="text" />
yes | no | auto</td>
</tr>
<tr>
<th scope="row"><strong>add link to nabtron</strong></th>
<td><?php nabwrap_addlink(); ?>
( checking this will add "Powered by <a href="http://nabtron.com/" target="_blank">Nabtron</a>" below the wrapper )</td>
</tr>
</table>
<br>
<p class="submit_nabwrap">
<input type="hidden" name="nabwrap_noncename" id="nabwrap_noncename" value="<?php echo wp_create_nonce(plugin_basename(__FILE__)); ?>" />
<input class="button button-primary" name="submit_nabwrap" type="submit" id="submit_nabwrap" value="Save Changes">
<input class="submit" name="action_nabwrap" value="insert" type="hidden" />
</p>
</form>
<br /><br />
<hr />
<center>
<h4>Developed by <a href="http://nabtron.com/" target="_blank">Nabtron</a>.</h4>
</center>
</div>
</div>
<?php
} // End function nabwrap_description_option_page()
// Admin menu Option
function nabwrap_description_add_menu()
{
add_options_page('WP Wrapper Options', 'WP Wrapper', 'manage_options', __FILE__, 'nabwrap_description_option_page');
}
function get_nabwrapper_id($content)
{
$nabwrap_page = esc_attr(get_option('nabwrap_page'));
if (is_page($nabwrap_page)) {
$nabwrap_url = esc_url(get_option('nabwrap_url'));
$nabwrap_width = esc_attr(get_option('nabwrap_width'));
$nabwrap_height = esc_attr(get_option('nabwrap_height'));
$nabwrap_border = esc_attr(get_option('nabwrap_border'));
$nabwrap_scroll = esc_attr(get_option('nabwrap_scroll'));
$nabwrap_addlink = esc_attr(get_option('nabwrap_addlink'));
if ($nabwrap_url == null) {
$nabwrap_url = "https://apple.com/";
}
$content .= '<iframe width="' . $nabwrap_width . '" height="' . $nabwrap_height . '" src="' . $nabwrap_url . '" frameBorder="' . $nabwrap_border . '" scrolling="' . $nabwrap_scroll . '"></iframe>';
if ($nabwrap_addlink == '1') {
$content .= '<p style="text-align:center">Powered by <a href="http://nabtron.com" target="_blank">Nabtron</a></p>';
}
}
return $content;
}
}
//instantiate the class
if (class_exists('nabwrap_main')) {
$nabwrap_main = new nabwrap_main();
}
// add settings link
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'wpwrapper_add_plugin_page_settings_link');
function wpwrapper_add_plugin_page_settings_link($links)
{
$links[] = '<a href="' .
admin_url('options-general.php?page=wp-wrapper/wp-wrapper.php') .
'">' . __('Settings') . '</a>';
return $links;
}
| nabtron/wp-wrapper | wp-wrapper.php | PHP | gpl-2.0 | 7,911 |
package de.jlab.android.hombot.sections;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.jlab.android.hombot.R;
import de.jlab.android.hombot.SectionFragment;
import de.jlab.android.hombot.SettingsActivity;
import de.jlab.android.hombot.common.settings.SharedSettings;
import de.jlab.android.hombot.core.HttpRequestEngine;
import de.jlab.android.hombot.common.utils.JoyTouchListener;
import de.jlab.android.hombot.utils.Colorizer;
/**
* A {@link SectionFragment} subclass.
* Activities that contain this fragment must implement the
* {@link SectionFragment.SectionInteractionListener} interface
* to handle interaction events.
* Use the {@link JoySection#newInstance} factory method to
* create an instance of this fragment.
*/
public class JoySection extends SectionFragment {
private static class ViewHolder {
Button commandMySpace;
Button commandSpiral;
Button commandTurbo;
Button commandHome;
View joy;
TextView joyLabel;
}
private ViewHolder mViewHolder;
public static JoySection newInstance(int sectionNumber) {
JoySection fragment = new JoySection();
fragment.register(sectionNumber);
return fragment;
}
private class InstaCleanHandler extends Handler {
public static final int SPIRAL = 1;
private boolean mInsta;
public InstaCleanHandler(boolean insta) {
mInsta = insta;
}
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
sendCommand(HttpRequestEngine.Command.MODE_SPIRAL);
if (mInsta) {
try {
Thread.sleep(1500);
} catch (InterruptedException ignored) {}
sendCommand(HttpRequestEngine.Command.START);
}
}
}
}
private InstaCleanHandler mInstaCleanHandler;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_section_joy, container, false);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mInstaCleanHandler = new InstaCleanHandler(sp.getBoolean(SettingsActivity.PREF_JOY_INSTACLEAN, false));
mViewHolder = new ViewHolder();
mViewHolder.commandMySpace = (Button) view.findViewById(R.id.cm_mode_myspace);
mViewHolder.commandSpiral = (Button) view.findViewById(R.id.cm_mode_spiral);
mViewHolder.commandTurbo = (Button) view.findViewById(R.id.cm_turbo);
mViewHolder.commandHome = (Button) view.findViewById(R.id.cm_home);
mViewHolder.joy = view.findViewById(R.id.ct_joy);
mViewHolder.joyLabel = (TextView)view.findViewById(R.id.ct_joy_label);
mViewHolder.commandMySpace.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendCommand(HttpRequestEngine.Command.MODE_MYSPACE);
}
});
mViewHolder.commandSpiral.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mInstaCleanHandler.hasMessages(InstaCleanHandler.SPIRAL)) {
mInstaCleanHandler.sendEmptyMessage(InstaCleanHandler.SPIRAL);
}
}
});
mViewHolder.commandTurbo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendCommand(HttpRequestEngine.Command.TURBO);
}
});
mViewHolder.commandHome.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendCommand(HttpRequestEngine.Command.HOME);
}
});
int intervalDrive = Integer.parseInt(sp.getString(SharedSettings.PREF_JOY_INTERVAL_DRIVE, "800"));
int intervalTurn = Integer.parseInt(sp.getString(SharedSettings.PREF_JOY_INTERVAL_TURN, "800"));
mViewHolder.joy.setOnTouchListener(new JoyTouchListener(intervalDrive, intervalTurn, new JoyTouchListener.PushListener[]{
new JoyTouchListener.PushListener() {
@Override
public void onPush() {
sendCommand(HttpRequestEngine.Command.JOY_FORWARD);
Log.d("MOT", "F");
}
@Override
public void onRelease() {
sendCommand(HttpRequestEngine.Command.JOY_RELEASE);
Log.d("MOT", "-");
}
},
new JoyTouchListener.PushListener() {
@Override
public void onPush() {
sendCommand(HttpRequestEngine.Command.JOY_RIGHT);
Log.d("MOT", "R");
}
@Override
public void onRelease() {
sendCommand(HttpRequestEngine.Command.JOY_RELEASE);
Log.d("MOT", "-");
}
},
new JoyTouchListener.PushListener() {
@Override
public void onPush() {
sendCommand(HttpRequestEngine.Command.JOY_BACK);
Log.d("MOT", "B");
}
@Override
public void onRelease() {
sendCommand(HttpRequestEngine.Command.JOY_RELEASE);
Log.d("MOT", "-");
}
},
new JoyTouchListener.PushListener() {
@Override
public void onPush() {
sendCommand(HttpRequestEngine.Command.JOY_LEFT);
Log.d("MOT", "L");
}
@Override
public void onRelease() {
sendCommand(HttpRequestEngine.Command.JOY_RELEASE);
Log.d("MOT", "-");
}
},
new JoyTouchListener.PushListener() {
@Override
public void onPush() {
sendCommand(HttpRequestEngine.Command.PAUSE);
Log.d("MOT", "P");
}
@Override
public void onRelease() { /* NO RELEASE FOR CENTER COMMAND */ }
}
}));
// MAKE JOYPAD "SQUARE" ACCORDING TO THE SMALLER AVAILABLE DIMENSION FIXME BUGGY ON ORIENTATION CHANGE
if (mViewHolder.joy.getViewTreeObserver().isAlive()) {
mViewHolder.joy.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int finalSize = Math.min(mViewHolder.joy.getMeasuredWidth(), mViewHolder.joy.getMeasuredHeight());
mViewHolder.joy.setLayoutParams(new RelativeLayout.LayoutParams(finalSize, finalSize));
view.invalidate();
}
});
}
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Colorizer colorizer = getColorizer();
int textColor = colorizer.getColorText();
colorizer.colorizeButton(mViewHolder.commandHome, textColor);
colorizer.colorizeButton(mViewHolder.commandSpiral, textColor);
colorizer.colorizeButton(mViewHolder.commandMySpace, textColor);
colorizer.colorizeButton(mViewHolder.commandTurbo, textColor);
mViewHolder.joy.getBackground().setColorFilter(textColor, PorterDuff.Mode.SRC_ATOP);
mViewHolder.joyLabel.setTextColor(textColor);
}
}
| rampage128/hombot-control | mobile/src/main/java/de/jlab/android/hombot/sections/JoySection.java | Java | gpl-2.0 | 8,519 |
import csv, sqlite3
con = sqlite3.connect("toto.db") # change to 'sqlite:///your_filename.db'
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);") # use your column names here
with open('data.csv','r') as fin: # `with` statement available in 2.5+
# csv.DictReader uses first line in file for column headings by default
dr = csv.DictReader(fin) # comma is default delimiter
to_db = [(i['col1'], i['col2']) for i in dr]
cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()
con.close()
| fccagou/tools | python/sql/csv-to-sql.py | Python | gpl-2.0 | 537 |
<?php
/**
* @version $Id$
* @package Joomla.Installation
* @copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* Joomla Installation HTML Helper Class.
*
* @static
* @package Joomla.Installation
* @since 1.6
*/
class JHtmlInstallation
{
/**
*/
static function stepbar($on = 1)
{
$html = '<h1>'.JText::_('Steps').'</h1>' .
'<div class="step-'.($on == 1 ? 'on' : 'off').'">'.JText::_('Instl_Step_1_Label').'</div>' .
'<div class="step-'.($on == 2 ? 'on' : 'off').'">'.JText::_('Instl_Step_2_Label').'</div>' .
'<div class="step-'.($on == 3 ? 'on' : 'off').'">'.JText::_('Instl_Step_3_Label').'</div>' .
'<div class="step-'.($on == 4 ? 'on' : 'off').'">'.JText::_('Instl_Step_4_Label').'</div>' .
'<div class="step-'.($on == 5 ? 'on' : 'off').'">'.JText::_('Instl_Step_5_Label').'</div>' .
'<div class="step-'.($on == 6 ? 'on' : 'off').'">'.JText::_('Instl_Step_6_Label').'</div>' .
'<div class="step-'.($on == 7 ? 'on' : 'off').'">'.JText::_('Instl_Step_7_Label') .'</div>';
return $html;
}
} | joebushi/joomla | installation/helpers/html/installation.php | PHP | gpl-2.0 | 1,146 |
<?php
/**
* @package WPSEO\Admin
*/
if ( ! defined( 'WPSEO_VERSION' ) ) {
header( 'Status: 403 Forbidden' );
header( 'HTTP/1.1 403 Forbidden' );
exit();
}
/**
* @todo [JRF => testers] Extensively test the export & import of the (new) settings!
* If that all works fine, getting testers to export before and after upgrade will make testing easier.
*
* @todo [Yoast] The import for the RSS Footer plugin checks for data already entered via WP SEO,
* the other import routines should do that too.
*/
$yform = Yoast_Form::get_instance();
$replace = false;
if ( isset( $_POST['import'] ) || isset( $_GET['import'] ) ) {
check_admin_referer( 'wpseo-import' );
if ( isset( $_POST['wpseo']['deleteolddata'] ) && $_POST['wpseo']['deleteolddata'] == 'on' ) {
$replace = true;
}
if ( isset( $_POST['wpseo']['importwoo'] ) ) {
$import = new WPSEO_Import_WooThemes_SEO( $replace );
}
if ( isset( $_POST['wpseo']['importaioseo'] ) || isset( $_GET['importaioseo'] ) ) {
$import = new WPSEO_Import_AIOSEO( $replace );
}
if ( isset( $_POST['wpseo']['importheadspace'] ) ) {
$import = new WPSEO_Import_External( $replace );
$import->import_headspace();
}
if ( isset( $_POST['wpseo']['importrobotsmeta'] ) || isset( $_GET['importrobotsmeta'] ) ) {
$import = new WPSEO_Import_External( $replace );
$import->import_robots_meta();
}
if ( isset( $_POST['wpseo']['importrssfooter'] ) ) {
$import = new WPSEO_Import_External( $replace );
$import->import_rss_footer();
}
if ( isset( $_POST['wpseo']['importbreadcrumbs'] ) ) {
$import = new WPSEO_Import_External( $replace );
$import->import_yoast_breadcrumbs();
}
// Allow custom import actions
do_action( 'wpseo_handle_import' );
}
if ( isset( $_FILES['settings_import_file'] ) ) {
check_admin_referer( 'wpseo-import-file' );
$import = new WPSEO_Import();
}
if ( isset( $import ) ) {
/**
* Allow customization of import&export message
* @api string $msg The message.
*/
$msg = apply_filters( 'wpseo_import_message', $import->msg );
// Check if we've deleted old data and adjust message to match it
if ( $replace ) {
$msg .= ' ' . __( 'The old data of the imported plugin was deleted successfully.', 'wordpress-seo' );
}
if ( $msg != '' ) {
echo '<div id="message" class="message updated" style="width:94%;"><p>', $msg, '</p></div>';
}
}
?>
<br/><br/>
<h2 class="nav-tab-wrapper" id="wpseo-tabs">
<a class="nav-tab nav-tab-active" id="wpseo-import-tab"
href="#top#wpseo-import"><?php _e( 'Import', 'wordpress-seo' ); ?></a>
<a class="nav-tab" id="wpseo-export-tab" href="#top#wpseo-export"><?php _e( 'Export', 'wordpress-seo' ); ?></a>
<a class="nav-tab" id="import-seo-tab"
href="#top#import-seo"><?php _e( 'Import from other SEO plugins', 'wordpress-seo' ); ?></a>
<a class="nav-tab" id="import-other-tab"
href="#top#import-other"><?php _e( 'Import from other plugins', 'wordpress-seo' ); ?></a>
<?php
/**
* Allow adding a custom import tab header
*/
do_action( 'wpseo_import_tab_header' );
?>
</h2>
<div id="wpseo-import" class="wpseotab">
<p><?php _e( 'Import settings by locating <em>settings.zip</em> and clicking "Import settings"', 'wordpress-seo' ); ?></p>
<form
action="<?php echo esc_attr( admin_url( 'admin.php?page=wpseo_tools&tool=import-export#top#wpseo-import' ) ); ?>"
method="post" enctype="multipart/form-data"
accept-charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>">
<?php wp_nonce_field( 'wpseo-import-file', '_wpnonce', true, true ); ?>
<input type="file" name="settings_import_file" accept="application/x-zip,application/x-zip-compressed,application/zip" />
<input type="hidden" name="action" value="wp_handle_upload"/><br/>
<br/>
<input type="submit" class="button-primary" value="<?php _e( 'Import settings', 'wordpress-seo' ); ?>"/>
</form>
</div>
<div id="wpseo-export" class="wpseotab">
<p><?php _e( 'Export your SEO settings here, to import them again later or to import them on another site.', 'wordpress-seo' ); ?></p>
<?php $yform->checkbox( 'include_taxonomy_meta', __( 'Include Taxonomy Metadata', 'wordpress-seo' ) ); ?><br/>
<button class="button-primary" id="export-button">Export your SEO settings</button>
<script>
var wpseo_export_nonce = '<?php echo wp_create_nonce( 'wpseo-export' ); ?>';
</script>
</div>
<div id="import-seo" class="wpseotab">
<p><?php _e( 'No doubt you\'ve used an SEO plugin before if this site isn\'t new. Let\'s make it easy on you, you can import the data below. If you want, you can import first, check if it was imported correctly, and then import & delete. No duplicate data will be imported.', 'wordpress-seo' ); ?></p>
<p><?php printf( __( 'If you\'ve used another SEO plugin, try the %sSEO Data Transporter%s plugin to move your data into this plugin, it rocks!', 'wordpress-seo' ), '<a href="https://wordpress.org/plugins/seo-data-transporter/">', '</a>' ); ?></p>
<form
action="<?php echo esc_attr( admin_url( 'admin.php?page=wpseo_tools&tool=import-export#top#import-seo' ) ); ?>"
method="post" accept-charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>">
<?php
wp_nonce_field( 'wpseo-import', '_wpnonce', true, true );
$yform->checkbox( 'importheadspace', __( 'Import from HeadSpace2?', 'wordpress-seo' ) );
$yform->checkbox( 'importaioseo', __( 'Import from All-in-One SEO?', 'wordpress-seo' ) );
$yform->checkbox( 'importwoo', __( 'Import from WooThemes SEO framework?', 'wordpress-seo' ) );
?>
<br/>
<?php
$yform->checkbox( 'deleteolddata', __( 'Delete the old data after import? (recommended)', 'wordpress-seo' ) );
?>
<br/>
<input type="submit" class="button-primary" name="import"
value="<?php _e( 'Import', 'wordpress-seo' ); ?>"/>
</form>
<br/>
<br/>
</div>
<div id="import-other" class="wpseotab">
<p><?php _e( 'If you want to import data from (by now ancient) Yoast plugins, you can do so here:', 'wordpress-seo' ); ?></p>
<form
action="<?php echo esc_attr( admin_url( 'admin.php?page=wpseo_tools&tool=import-export#top#import-other' ) ); ?>"
method="post" accept-charset="<?php echo esc_attr( get_bloginfo( 'charset' ) ); ?>">
<?php
wp_nonce_field( 'wpseo-import', '_wpnonce', true, true );
$yform->checkbox( 'importrobotsmeta', __( 'Import from Robots Meta (by Yoast)?', 'wordpress-seo' ) );
$yform->checkbox( 'importrssfooter', __( 'Import from RSS Footer (by Yoast)?', 'wordpress-seo' ) );
$yform->checkbox( 'importbreadcrumbs', __( 'Import from Yoast Breadcrumbs?', 'wordpress-seo' ) );
/**
* Allow option of importing from other 'other' plugins
* @api string $content The content containing all import and export methods
*/
echo apply_filters( 'wpseo_import_other_plugins', '' );
?>
<br/>
<input type="submit" class="button-primary" name="import" value="<?php _e( 'Import', 'wordpress-seo' ); ?>"/>
</form>
<br/>
</div>
<?php
/**
* Allow adding a custom import tab
*/
do_action( 'wpseo_import_tab_content' );
| NETLINK/WP-SEO | admin/views/tool-import-export.php | PHP | gpl-2.0 | 7,176 |
<?php
namespace Drupal\m_learning\Welcome;
use Drupal\Core\KeyValueStore\KeyValueFactory;
class WelcomeGenerator
{
/**
* @var KeyValueFactory
*/
private $keyValueFactory;
private $useCache;
public function __construct(KeyValueFactory $keyValueFactory, $useCache)
{
$this->keyValueFactory = $keyValueFactory;
$this->useCache = $useCache;
}
public function getWelcome($name) {
$key = 'welcome_' . $name;
$store = $this->keyValueFactory->get('welcome');
if ($this->useCache && $store->has($key)) {
return $store->get($key);
}
sleep(2);
$string = 'Welcome ' . $name . ' on first drupal 8 page.';
if ($this->useCache) {
$store->set($key, $string);
}
return $string;
}
} | piontuso/eys | modules/m_learning/src/Welcome/WelcomeGenerator.php | PHP | gpl-2.0 | 751 |
# select the data using the like API
# use the python 3.5 as default
import sqlite3
def select_data(db_name, table_name, condition):
"find all the data with the same kind"
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("SELECT title, releaseYear FROM {0} WHERE title LIKE ?".format(table_name), (condition,))
result = cursor.fetchall()
return result
def select_from_multi(db_name, table_name, conditon):
"select from multiple tables"
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("SELECT title, genreName FROM {0}, {1} WHERE title=? AND genreName IN (?,?)".format(table_name[0], table_name[1]), (condition[0], condition[1], condition[2]))
result = cursor.fetchall()
return result
if __name__ == '__main__':
db_name = "movie.db"
table_name = "film"
condition = "Die Hard%"
result = select_data(db_name, table_name, condition)
print(result)
table_name = ("film", "genre")
condition = ("Die Hard", "Action", "Thriller")
result = select_from_multi(db_name, table_name, condition)
print(result)
| smileboywtu/SQLite3 | coffee-shop/demon/select-like.py | Python | gpl-2.0 | 1,166 |
/*
* Copyright (c) 2013, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#undef IMPL
#include "config.h"
#include <WebCore/CharacterData.h>
#include "DOMException.h"
#include <WebCore/Element.h>
#include <WebCore/JSMainThreadExecState.h>
#include <wtf/RefPtr.h>
#include <wtf/GetPtr.h>
#include "JavaDOMUtils.h"
#include <wtf/java/JavaEnv.h>
using namespace WebCore;
extern "C" {
#define IMPL (static_cast<CharacterData*>(jlong_to_ptr(peer)))
// Attributes
JNIEXPORT jstring JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_getDataImpl(JNIEnv* env, jclass, jlong peer)
{
WebCore::JSMainThreadNullState state;
return JavaReturn<String>(env, IMPL->data());
}
JNIEXPORT void JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_setDataImpl(JNIEnv* env, jclass, jlong peer, jstring value)
{
WebCore::JSMainThreadNullState state;
IMPL->setData(String(env, value));
}
JNIEXPORT jint JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_getLengthImpl(JNIEnv*, jclass, jlong peer)
{
WebCore::JSMainThreadNullState state;
return IMPL->length();
}
JNIEXPORT jlong JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_getPreviousElementSiblingImpl(JNIEnv* env, jclass, jlong peer)
{
WebCore::JSMainThreadNullState state;
return JavaReturn<Element>(env, WTF::getPtr(IMPL->previousElementSibling()));
}
JNIEXPORT jlong JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_getNextElementSiblingImpl(JNIEnv* env, jclass, jlong peer)
{
WebCore::JSMainThreadNullState state;
return JavaReturn<Element>(env, WTF::getPtr(IMPL->nextElementSibling()));
}
// Functions
JNIEXPORT jstring JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_substringDataImpl(JNIEnv* env, jclass, jlong peer
, jint offset
, jint length)
{
WebCore::JSMainThreadNullState state;
return JavaReturn<String>(env, raiseOnDOMError(env, IMPL->substringData(offset
, length)));
}
JNIEXPORT void JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_appendDataImpl(JNIEnv* env, jclass, jlong peer
, jstring data)
{
WebCore::JSMainThreadNullState state;
IMPL->appendData(String(env, data));
}
JNIEXPORT void JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_insertDataImpl(JNIEnv* env, jclass, jlong peer
, jint offset
, jstring data)
{
WebCore::JSMainThreadNullState state;
raiseOnDOMError(env, IMPL->insertData(offset
, String(env, data)));
}
JNIEXPORT void JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_deleteDataImpl(JNIEnv* env, jclass, jlong peer
, jint offset
, jint length)
{
WebCore::JSMainThreadNullState state;
raiseOnDOMError(env, IMPL->deleteData(offset
, length));
}
JNIEXPORT void JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_replaceDataImpl(JNIEnv* env, jclass, jlong peer
, jint offset
, jint length
, jstring data)
{
WebCore::JSMainThreadNullState state;
raiseOnDOMError(env, IMPL->replaceData(offset
, length
, String(env, data)));
}
JNIEXPORT void JNICALL Java_com_sun_webkit_dom_CharacterDataImpl_removeImpl(JNIEnv* env, jclass, jlong peer)
{
WebCore::JSMainThreadNullState state;
raiseOnDOMError(env, IMPL->remove());
}
}
| teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Source/WebCore/bindings/java/dom3/JavaCharacterData.cpp | C++ | gpl-2.0 | 4,340 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace FDF.WebApp.Controllers
{
[Route("api/")]
public class HomeController : Controller
{
// GET: api/home
[HttpGet]
public string Get(string name)
{
return $"Hello, {name.Replace("+", " ")}";
}
}
}
| n9niwas/Food-delivery-feedbacks | FoodDeliveryFeedbacks/FDF.WebApp/Controllers/HomeController.cs | C# | gpl-2.0 | 400 |
// Generated on 02/23/2017 16:53:35
using System;
using System.Collections.Generic;
using System.Linq;
using DarkSoul.Network.Protocol.Types;
using DarkSoul.Network.Protocol.Message;
using DarkSoul.Core.Interfaces;
using DarkSoul.Core.IO;
namespace DarkSoul.Network.Protocol.Messages
{
public class EmoteListMessage : NetworkMessage
{
public override ushort Id => 5689;
public IEnumerable<byte> emoteIds;
public EmoteListMessage()
{
}
public EmoteListMessage(IEnumerable<byte> emoteIds)
{
this.emoteIds = emoteIds;
}
public override void Serialize(IWriter writer)
{
writer.WriteShort((short)emoteIds.Count());
foreach (var entry in emoteIds)
{
writer.WriteByte(entry);
}
}
public override void Deserialize(IReader reader)
{
var limit = reader.ReadUShort();
emoteIds = new byte[limit];
for (int i = 0; i < limit; i++)
{
(emoteIds as byte[])[i] = reader.ReadByte();
}
}
}
} | LDOpenSource/DarkSoul | DarkSoul.Network/Protocol/Message/Messages/game/context/roleplay/emote/EmoteListMessage.cs | C# | gpl-2.0 | 1,220 |
package com.fifino.gptw.screens;
import android.graphics.Point;
import com.fifino.framework.assets.Assets;
import com.fifino.framework.entities.MenuItem;
import com.fifino.gptw.flags.AutoRun;
import com.fifino.gptw.helpers.GPTWResources;
import com.kilobolt.framework.Game;
import com.kilobolt.framework.Graphics;
import com.kilobolt.framework.Image;
import com.kilobolt.framework.Input.TouchEvent;
import com.kilobolt.framework.implementation.AndroidImage;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class LoadingScreen extends GPTWScreen implements AutoRun {
boolean doneLoading = false;
public LoadingScreen(Game game) {
super(game);
this.state = GameState.Running;
}
Point last = null;
@Override
protected void drawRunningUI(List<TouchEvent> touchEvents, float deltaTime){
Graphics g = game.getGraphics();
loadingScreen.draw(g);
if(last != null){
g.drawCircle(last.x, last.y, 50, paintB);
}
}
@Override
protected void updateRunning(List<TouchEvent> touchEvents, float deltaTime) {
int len = touchEvents.size();
TouchEvent event = null;
if (len > 0) {
for (int i = 0; i < len; i++) {
if (touchEvents.size() < len) {
// Handles out of bounds exception for the list getting empty
// after getting the size.
return;
}
event = touchEvents.get(i);
last = new Point(event.x, event.y);
// if (event.type == TouchEvent.TOUCH_DOWN) {
// state = GameState.GameOver;
// }
}
}
if(!doneLoading){
doneLoading = true;
loadMenuScreen();
}
}
private void loadMenuScreen(){
this.state = GameState.Paused;
MainMenu menuScreen = new MainMenu(game);
this.game.setScreen(menuScreen);
}
/**
* Initializes the main loading screen asset.
*/
@Override
protected void initializeAssets() {
Graphics g = game.getGraphics();
String key = "loading";
if(Assets.getImage(key) == null){
Image bgImage = g.newImage(Assets.IMAGES_PATH + "/loading.png", Graphics.ImageFormat.RGB565);
Assets.addImage(key, bgImage);
}
}
MenuItem loadingScreen;
@Override
protected void setupEntities() {
AndroidImage image = Assets.getAndroidImage("loading");
loadingScreen = new MenuItem(image, 0, 0);
doneLoading = false;
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
@Override
public void backButton() {
System.exit(0);
}
}
| ppartida/com.fifino.gptw | src/main/java/com/fifino/gptw/screens/LoadingScreen.java | Java | gpl-2.0 | 2,852 |
/*
* IRIS -- Intelligent Roadway Information System
* Copyright (C) 2008-2015 Minnesota Department of Transportation
*
* 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.
*/
package us.mn.state.dot.tms.server.comm.ntcip;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import us.mn.state.dot.tms.EventType;
import us.mn.state.dot.tms.server.DMSImpl;
import us.mn.state.dot.tms.server.comm.CommMessage;
import us.mn.state.dot.tms.server.comm.PriorityLevel;
import us.mn.state.dot.tms.server.comm.ntcip.mib1203.*;
import static us.mn.state.dot.tms.server.comm.ntcip.mib1203.MIB1203.*;
import us.mn.state.dot.tms.server.comm.snmp.ASN1Enum;
import us.mn.state.dot.tms.server.comm.snmp.ASN1Integer;
/**
* Operation to incorporate brightness feedback for a DMS.
*
* @author Douglas Lau
*/
public class OpUpdateDMSBrightness extends OpDMS {
/** Event type (DMS_BRIGHT_GOOD, DMS_BRIGHT_LOW or DMS_BRIGHT_HIGH) */
private final EventType event_type;
/** Illumination control */
private final ASN1Enum<DmsIllumControl> control =
new ASN1Enum<DmsIllumControl>(DmsIllumControl.class,
dmsIllumControl.node);
/** Maximum photocell level */
private final ASN1Integer max_level =
dmsIllumMaxPhotocellLevel.makeInt();
/** Photocell level status */
private final ASN1Integer p_level =
dmsIllumPhotocellLevelStatus.makeInt();
/** Light output status */
private final ASN1Integer light = dmsIllumLightOutputStatus.makeInt();
/** Total number of supported brightness levels */
private final ASN1Integer b_levels = dmsIllumNumBrightLevels.makeInt();
/** Brightness table */
private final DmsIllumBrightnessValues brightness =
new DmsIllumBrightnessValues();
/** Create a new DMS brightness feedback operation */
public OpUpdateDMSBrightness(DMSImpl d, EventType et) {
super(PriorityLevel.COMMAND, d);
event_type = et;
}
/** Create the second phase of the operation */
@Override
protected Phase phaseTwo() {
return new QueryBrightness();
}
/** Phase to query the brightness status */
protected class QueryBrightness extends Phase {
/** Query the DMS brightness status */
protected Phase poll(CommMessage mess) throws IOException {
mess.add(max_level);
mess.add(p_level);
mess.add(light);
mess.queryProps();
logQuery(max_level);
logQuery(p_level);
logQuery(light);
dms.feedbackBrightness(event_type,
p_level.getInteger(), light.getInteger());
return new QueryBrightnessTable();
}
}
/** Phase to get the brightness table */
protected class QueryBrightnessTable extends Phase {
/** Get the brightness table */
protected Phase poll(CommMessage mess) throws IOException {
mess.add(b_levels);
mess.add(brightness);
mess.add(control);
mess.queryProps();
logQuery(b_levels);
logQuery(brightness);
logQuery(control);
if (control.getEnum() == DmsIllumControl.photocell)
return new SetManualControl();
else
return new SetBrightnessTable();
}
}
/** Phase to set manual control mode */
protected class SetManualControl extends Phase {
/** Set the manual control mode */
protected Phase poll(CommMessage mess) throws IOException {
control.setEnum(DmsIllumControl.manual);
mess.add(control);
logStore(control);
mess.storeProps();
return new SetBrightnessTable();
}
}
/** Phase to set a new brightness table */
protected class SetBrightnessTable extends Phase {
/** Set the brightness table */
protected Phase poll(CommMessage mess) throws IOException {
// NOTE: if the existing table is not valid, don't mess
// with it. This check is needed for a certain
// vendor, which has a wacky brightness table.
if (brightness.isValid()) {
brightness.setTable(calculateTable());
mess.add(brightness);
logStore(brightness);
mess.storeProps();
}
return new SetPhotocellControl();
}
}
/** Calculate a new brightness table */
private BrightnessLevel[] calculateTable() {
BrightnessLevel[] table = brightness.getTable();
dms.queryBrightnessFeedback(new BrightnessTable(table));
return table;
}
/** Phase to set photocell control mode */
protected class SetPhotocellControl extends Phase {
/** Set the photocell control mode */
protected Phase poll(CommMessage mess) throws IOException {
control.setEnum(DmsIllumControl.photocell);
mess.add(control);
logStore(control);
mess.storeProps();
return null;
}
}
}
| SRF-Consulting/NDOR-IRIS | src/us/mn/state/dot/tms/server/comm/ntcip/OpUpdateDMSBrightness.java | Java | gpl-2.0 | 4,901 |
/*
* Copyright (C) 2000 by Ian Reinhart Geiser <geiseri@kde.org>
*
* Licensed under the Artistic License.
*/
#include "kdcoplistview.h"
#include "kdcoplistview.moc"
#include <kdebug.h>
#include <qdragobject.h>
#include <qstringlist.h>
#include <qregexp.h>
KDCOPListView::KDCOPListView(QWidget *parent, const char *name) : KListView(parent, name)
{
kdDebug() << "Building new list." << endl;
setDragEnabled(true);
}
KDCOPListView::~KDCOPListView()
{
}
QDragObject *KDCOPListView::dragObject()
{
kdDebug() << "Drag object called... " << endl;
if(!currentItem())
return 0;
else
return new QTextDrag(encode(this->selectedItem()), this);
}
void KDCOPListView::setMode(const QString &theMode)
{
mode = theMode;
}
QString KDCOPListView::encode(QListViewItem *theCode)
{
DCOPBrowserItem *item = static_cast< DCOPBrowserItem * >(theCode);
if(item->type() != DCOPBrowserItem::Function)
return "";
DCOPBrowserFunctionItem *fitem = static_cast< DCOPBrowserFunctionItem * >(item);
QString function = QString::fromUtf8(fitem->function());
QString application = QString::fromUtf8(fitem->app());
QString object = QString::fromUtf8(fitem->object());
kdDebug() << function << endl;
QString returnType = function.section(' ', 0, 0);
QString returnCode = "";
QString normalisedSignature;
QStringList types;
QStringList names;
QString unNormalisedSignature(function);
int s = unNormalisedSignature.find(' ');
if(s < 0)
s = 0;
else
s++;
unNormalisedSignature = unNormalisedSignature.mid(s);
int left = unNormalisedSignature.find('(');
int right = unNormalisedSignature.findRev(')');
if(-1 == left)
{
// Fucked up function signature.
return "";
}
if(left > 0 && left + 1 < right - 1)
{
types = QStringList::split(',', unNormalisedSignature.mid(left + 1, right - left - 1));
for(QStringList::Iterator it = types.begin(); it != types.end(); ++it)
{
(*it) = (*it).stripWhiteSpace();
int s = (*it).find(' ');
if(-1 != s)
{
names.append((*it).mid(s + 1));
(*it) = (*it).left(s);
}
}
}
if(mode == "C++")
{
QString args;
for(unsigned int i = 0; i < names.count(); i++)
{
args += types[i] + " " + names[i] + ";\n";
}
QString dcopRef = "DCOPRef m_" + application + object + "(\"" + application + "\",\"" + object + "\");\n";
QString stringNames = names.join(",");
QString stringTypes = types.join(",");
if(returnType != "void")
returnType += " return" + returnType + " =";
else
returnType = "";
returnCode =
args + dcopRef + returnType + "m_" + application + object + ".call(\"" + unNormalisedSignature.left(left) + "(" + stringTypes + ")\"";
if(!stringNames.isEmpty())
returnCode += ", ";
returnCode += stringNames + ");\n";
}
else if(mode == "Shell")
{
returnCode = "dcop " + application + " " + object + " " + unNormalisedSignature.left(left) + " " + names.join(" ");
}
else if(mode == "Python")
{
QString setup;
setup = "m_" + application + object + " = dcop.DCOPObject( \"" + application + "\",\"" + object + "\")\n";
for(unsigned int i = 0; i < names.count(); i++)
{
setup += names[i] + " #set value here.\n";
}
returnCode =
setup + "reply" + returnType + " = m_" + application + object + "." + unNormalisedSignature.left(left) + "(" + names.join(",") + ")\n";
}
return returnCode;
}
QString KDCOPListView::getCurrentCode() const
{
// fixing warning
return QString::null;
}
| serghei/kde3-kdebase | kdcop/kdcoplistview.cpp | C++ | gpl-2.0 | 3,862 |
<?php
/*
Template Name: Embedded Shiri Register Page 2015
*/
?>
<?php
get_header('noMenu');
wp_enqueue_script('nadlan-fileUpload', get_template_directory_uri() . '/js/nadlan-fileUpload.js', array('jquery'), false, true);
wp_enqueue_script('nadlan-register', get_template_directory_uri() . '/js/nadlan-register-a-15.js', array('jquery'), false, true);
wp_enqueue_script('tooltip', get_template_directory_uri() . '/js/tooltip.js', array('jquery'), false, true);
$signup="667";
$signupWithPayment="663";
$signupPaymentError="665";
//check if qa
if(strpos(home_url( '/' ),"cambium")>-1){
$signup="639";
$signupWithPayment="641";
$signupPaymentError="643";
}
// 1. Facebook MediaID=36433
// 2. Google MediaID=33703
// 3. Gmail MediaID=47906
// 4. Linkedin MediaID=47905
// 5. Calcalist MediaID=32276
?>
<script>
var domain = "<?php echo home_url( '/' ); ?>";
var signupNum= "<?php echo $signup; ?>";
</script>
<?php while (have_posts()) : the_post(); ?>
<?php $categories = get_the_category(); ?>
<div class="heading">
<div class="container">
<h1><?php the_title() ?></h1>
</div>
</div>
<div class="container" style="position: relative;">
<!--<div>לעזרה בהרשמה 074-7290200</div><br>-->
<?php
//echo do_shortcode('[pelecard_pay_button value="2" item_name=" כניסה לועידה - עיר הנדלן " button_class="my-class" button_text="Pay Now"]');
?>
<div id="contact-phone-btn">לעזרה בהרשמה<br>074-7290200</div>
<div id="nadlan-mask"><div id="nadlan-loader"></div></div>
<form id="nadlan-register-form">
<div class="register-step" id="step-1">
<?php the_content(); ?>
<div class="row" class="register-hotel">
<div class="col-sm-11">
<label>מלון</label><br>
<select id="register-hotel">
<option value="">בחר מלון</option>
<option value="1" text="רויאל ביץ">רויאל ביץ'</option>
<option value="2" text="רויאל גארדן">רויאל גארדן</option>
<option value="3" text="ספורט">ספורט</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-11">
<label>הרשמה לכנס ללא לינה</label><br>
<select id="register-day">
<option value="">בחר תאריך</option>
<option value="1">01/12/2015 - יום ג'</option>
<option value="2">02/12/2015 - יום ד'</option>
<option value="3">03/12/2015 - יום ה'</option>
<option value="4">הרשמה לכל הימים</option>
</select>
</div>
</div>
<div class="row" class="register-room-type">
<div class="col-sm-11">
<label>סוג חדר</label>
<span class="remark"> (הודעה: לתשומת ליבך חדרי טריפל מכילים מטה זוגית אחת וספה נפתחת)</span><br>
<select id="register-room-type">
<option value="">בחר סוג חדר</option>
<option value="1" text="יחיד">יחיד</option>
<option value="2" text="זוגי">זוגי</option>
<option value="3" text="טריפל">טריפל </option>
<!--<option value="0">מבקר יום ללא לינה</option>-->
</select>
</div>
</div>
<div class="row" class="register-bed-type">
<div class="col-sm-11">
<label>סוג מיטה</label>
<span class="remark"> (* איננו מתחייבים כי נוכל לספק את בקשתך אך נשתדל לפעול עלפיה)</span><br>
<select id="register-bed-type">
<option value="2" text="זוגית">זוגית</option>
<option value="1" text="נפרדות">נפרדות</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-11">
<button id="next-to-step-2" class="btn btn-secondary">הבא</button>
</div>
</div>
</div>
<div class="register-step" id="step-2">
<label>פרטי המבקרים</label><br>
<div id="details1">
<label>מבקר ראשון:</label><br>
<div class="row">
<div class="col-sm-6">
<input id="Fname1" type="text" value="" placeholder="שם פרטי">
</div>
<div class="col-sm-6">
<input id="Lname1" type="text" value="" placeholder="שם משפחה">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<select id="title1">
<option value="">תואר</option>
<option value="18554">אדריכל</option>
<option value="18555">מעצב פנים</option>
<option value="18556">מנהל מכירות</option>
<option value="18557">יועץ</option>
<option value="18558">מהנדס</option>
<option value="18559">מנהל אזור</option>
<option value="18560">מנהל לקוחות</option>
<option value="18561">מנהל פיתוח עסקי</option>
<option value="18562">מנהל פרויקטים</option>
<option value="18563">מנהל/ת תיקי לקוחות</option>
<option value="18564">מנהל/ת כספים</option>
<option value="18565">רו"ח</option>
<option value="18566">שמאי</option>
<option value="18567">בנקאי</option>
<option value="18568">משרד פירסום</option>
<option value="18569">קבלן ביצוע</option>
<option value="18570">תעשיין</option>
<option value="18571">יזם</option>
<option value="18575">עו"ד</option>
<option value="18573">דר'</option>
<option value="18574">פרופ'</option>
<option value="18572">אחר</option>
</select>
</div>
<div class="col-sm-6">
<input id="id1" type="text" value="" placeholder=" ת.ז">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="companyName1" type="text" value="" placeholder="שם חברה/עסק מטעמו הגעת">
</div>
<div class="col-sm-6">
<select id="companyJob1">
<option value="">תפקיד</option>
<option value="18543">יו"ר</option>
<option value="18544">מנכ"ל</option>
<option value="18545">סמנכ"ל מכירות</option>
<option value="18546">מנהל מכירות</option>
<option value="18547">מנהל/ת שיווק</option>
<option value="18548">סמנכ"ל שיווק</option>
<option value="18549">מנהל/ת רכש</option>
<option value="18550">משנה למנכ"ל</option>
<option value="18551">מנכ"ל משותף</option>
<option value="18552">מנהל כספים</option>
<option value="18855">בעלים</option>
<option value="24163">מנהל חטיבה</option>
<option value="24162">מנהל ביצוע</option>
<option value="24161">מנהל</option>
<option value="19173">סמנכל</option>
<option value="24159">מתווך</option>
<option value="24158">מוניציפלי</option>
<option value="24157">סמנכל כספים</option>
<option value="24156">זכיין</option>
<option value="18553">אחר</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="Phone_Mobile1" type="text" value="" placeholder="טל' נייד לעדכונים במהלך הוועידה:">
</div>
<div class="col-sm-6">
<input id="Email1" type="text" value="" placeholder="אימייל">
</div>
</div>
<div class="row">
<div class="upload-imag-icon">
<input id="upload-imag1" name="upload-imag1" type="file" value="">
</div>
</div>
</div>
<div id="details2">
<label>מבקר שני:</label><br>
<div class="row">
<div class="col-sm-6">
<input id="Fname2" type="text" value="" placeholder="שם פרטי">
</div>
<div class="col-sm-6">
<input id="Lname2" type="text" value="" placeholder="שם משפחה">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<select id="title2">
<option value="">תואר</option>
<option value="18554">אדריכל</option>
<option value="18555">מעצב פנים</option>
<option value="18556">מנהל מכירות</option>
<option value="18557">יועץ</option>
<option value="18558">מהנדס</option>
<option value="18559">מנהל אזור</option>
<option value="18560">מנהל לקוחות</option>
<option value="18561">מנהל פיתוח עסקי</option>
<option value="18562">מנהל פרויקטים</option>
<option value="18563">מנהל/ת תיקי לקוחות</option>
<option value="18564">מנהל/ת כספים</option>
<option value="18565">רו"ח</option>
<option value="18566">שמאי</option>
<option value="18567">בנקאי</option>
<option value="18568">משרד פירסום</option>
<option value="18569">קבלן ביצוע</option>
<option value="18570">תעשיין</option>
<option value="18571">יזם</option>
<option value="18575">עו"ד</option>
<option value="18573">דר'</option>
<option value="18574">פרופ'</option>
<option value="18572">אחר</option>
</select>
</div>
<div class="col-sm-6">
<input id="id2" type="text" value="" placeholder=" ת.ז">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="companyName2" type="text" value="" placeholder="שם חברה/עסק מטעמו הגעת">
</div>
<div class="col-sm-6">
<select id="companyJob2">
<option value="">תפקיד</option>
<option value="18543">יו"ר</option>
<option value="18544">מנכ"ל</option>
<option value="18545">סמנכ"ל מכירות</option>
<option value="18546">מנהל מכירות</option>
<option value="18547">מנהל/ת שיווק</option>
<option value="18548">סמנכ"ל שיווק</option>
<option value="18549">מנהל/ת רכש</option>
<option value="18550">משנה למנכ"ל</option>
<option value="18551">מנכ"ל משותף</option>
<option value="18552">מנהל כספים</option>
<option value="18855">בעלים</option>
<option value="24163">מנהל חטיבה</option>
<option value="24162">מנהל ביצוע</option>
<option value="24161">מנהל</option>
<option value="19173">סמנכל</option>
<option value="24159">מתווך</option>
<option value="24158">מוניציפלי</option>
<option value="24157">סמנכל כספים</option>
<option value="24156">זכיין</option>
<option value="18553">אחר</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="Phone_Mobile2" type="text" value="" placeholder="טל' נייד לעדכונים במהלך הוועידה:">
</div>
<div class="col-sm-6">
<input id="Email2" type="text" value="" placeholder="אימייל">
</div>
</div>
<div class="row">
<div class="upload-imag-icon">
<input id="upload-imag2" type="file" value="">
</div>
</div>
</div>
<div id="details3">
<label>מבקר שלישי:</label><br>
<div class="row">
<div class="col-sm-6">
<input id="Fname3" type="text" value="" placeholder="שם פרטי">
</div>
<div class="col-sm-6">
<input id="Lname3" type="text" value="" placeholder="שם משפחה">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<select id="title3">
<option value="">תואר</option>
<option value="18554">אדריכל</option>
<option value="18555">מעצב פנים</option>
<option value="18556">מנהל מכירות</option>
<option value="18557">יועץ</option>
<option value="18558">מהנדס</option>
<option value="18559">מנהל אזור</option>
<option value="18560">מנהל לקוחות</option>
<option value="18561">מנהל פיתוח עסקי</option>
<option value="18562">מנהל פרויקטים</option>
<option value="18563">מנהל/ת תיקי לקוחות</option>
<option value="18564">מנהל/ת כספים</option>
<option value="18565">רו"ח</option>
<option value="18566">שמאי</option>
<option value="18567">בנקאי</option>
<option value="18568">משרד פירסום</option>
<option value="18569">קבלן ביצוע</option>
<option value="18570">תעשיין</option>
<option value="18571">יזם</option>
<option value="18575">עו"ד</option>
<option value="18573">דר'</option>
<option value="18574">פרופ'</option>
<option value="18572">אחר</option>
</select>
</div>
<div class="col-sm-6">
<input id="id3" type="text" value="" placeholder=" ת.ז">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="companyName3" type="text" value="" placeholder="שם חברה/עסק מטעמו הגעת">
</div>
<div class="col-sm-6">
<select id="companyJob3">
<option value="">תפקיד</option>
<option value="18543">יו"ר</option>
<option value="18544">מנכ"ל</option>
<option value="18545">סמנכ"ל מכירות</option>
<option value="18546">מנהל מכירות</option>
<option value="18547">מנהל/ת שיווק</option>
<option value="18548">סמנכ"ל שיווק</option>
<option value="18548">סמנכ"ל שיווק</option>
<option value="18549">מנהל/ת רכש</option>
<option value="18550">משנה למנכ"ל</option>
<option value="18551">מנכ"ל משותף</option>
<option value="18552">מנהל כספים</option>
<option value="18855">בעלים</option>
<option value="24163">מנהל חטיבה</option>
<option value="24162">מנהל ביצוע</option>
<option value="24161">מנהל</option>
<option value="19173">סמנכל</option>
<option value="24159">מתווך</option>
<option value="24158">מוניציפלי</option>
<option value="24157">סמנכל כספים</option>
<option value="24156">זכיין</option>
<option value="18553">אחר</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="Phone_Mobile3" type="text" value="" placeholder="טל' נייד לעדכונים במהלך הוועידה:">
</div>
<div class="col-sm-6">
<input id="Email3" type="text" value="" placeholder="אימייל">
</div>
</div>
<div class="row">
<div class="upload-imag-icon">
<input id="upload-imag3" type="file" value="">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-11">
<button id="next-to-step-3" class="btn btn-secondary">הבא</button>
</div>
</div>
</div>
<div class="register-step" id="step-3">
<label id="split-payment-label">האם לפצל את החשבונית?</label><br>
<div class="row">
<div class="col-sm-11">
<select id="split-payment">
<option value="0">לא</option>
<option value="1">כן</option>
</select>
</div>
</div>
<div class="row">
<div class="col-sm-11">
<label>סה"כ לתשלום (כולל מע"מ)</label><br>
<input id="register-sum" type="text" value="0" disabled>
</div>
</div>
<div id="payment1">
<input id="payment-checkbox-1" type="checkbox" value="payment"><label>תשלום מס' 1</label><label id="payment-name-1"></label><abbr class="nadlan-tooltip" title="נא הסר את ה V במידה ואינך מעוניין כי תצא חשבונית על מבקר זה." rel="tooltip"> ? </abbr><br>
<label>פרטי תשלום</label><br>
<div class="row">
<div class="col-sm-6">
<input id="invoiceN1" type="text" value="" placeholder="שם העסק להפקת חשבונית">
</div>
<div class="col-sm-6">
<input id="registrationNo1" type="text" value="" placeholder=" מס עוסק מורשה / ח.פ">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="registrationPhone1" type="text" value="" placeholder="טל' לבירורים בענייני הפקת החשבונית">
</div>
<div class="col-sm-6">
<input id="amount1" type="text" value="" placeholder="סכום לתשלום">
</div>
</div>
<label>כתובת לשליחת חשבונית</label><br>
<div class="row">
<div class="col-sm-6">
<select id="registrationAddressCity1">
<option value="61">צפת</option>
<option value="62">קרית
שמונה</option>
<option value="395">כפר
ורדים</option>
<option value="396">מטולה</option>
<option value="403">גן-נר</option>
<option value="405">חצור
הגלילית</option>
<option value="406">כורזים</option>
<option value="409">כפר
תבור</option>
<option value="411">מושב
נטועה</option>
<option value="415">נופית</option>
<option value="417">קיבוץ
בית זרע</option>
<option value="418">קיבוץ
גינוסר</option>
<option value="419">קיבוץ
דברת</option>
<option value="421">קיבוץ
עין הנציב</option>
<option value="426">שמשית</option>
<option value="428">שדה
יעקב</option>
<option value="430">רומי
יוסף</option>
<option value="431">קיבוץ
רבדים</option>
<option value="432">קיבוץ
גונן</option>
<option value="433">קיבוץ
בית אורן</option>
<option value="434">צובר</option>
<option value="439">מצפה
הושעיה</option>
<option value="444">מושב
ספאפה</option>
<option value="449">כינרת
קבוצה</option>
<option value="450">יסוד
המעלה</option>
<option value="451">יודפת</option>
<option value="453">גדרות</option>
<option value="455">אושרת</option>
<option value="602">אבירים</option>
<option value="603">אבן
יצחק</option>
<option value="604">אבן
מנחם</option>
<option value="607">אבני
איתן</option>
<option value="626">אורנים</option>
<option value="631">אחיהוד</option>
<option value="636">איילת
השחר</option>
<option value="639">אילניה</option>
<option value="646">אלון
הגליל</option>
<option value="651">אלי עד</option>
<option value="654">אליפלט</option>
<option value="657">אלמגור</option>
<option value="658">אלקוש</option>
<option value="662">אמנון</option>
<option value="667">אפיקים</option>
<option value="678">אשבל</option>
<option value="682">אשרת</option>
<option value="684">אתגר</option>
<option value="691">בוסתן
הגליל</option>
<option value="698">ביריה</option>
<option value="701">בית
אלפא</option>
<option value="705">בית ג'ן</option>
<option value="708">בית
הלל</option>
<option value="709">בית
העמק</option>
<option value="710">בית
השיטה</option>
<option value="711">בית
זיד</option>
<option value="713">בית
זרע</option>
<option value="720">בית
יוסף</option>
<option value="731">בית
צבי</option>
<option value="733">בית
קשת</option>
<option value="735">בית
רימון</option>
<option value="742">בן עמי</option>
<option value="752">בסמ"ה</option>
<option value="754">בענה</option>
<option value="758">בצת</option>
<option value="765">ברעם</option>
<option value="767">ברקאי</option>
<option value="788">גבעת
עוז</option>
<option value="792">גבת</option>
<option value="794">ג'דיידה-מכר</option>
<option value="798">גונן</option>
<option value="799">גורן</option>
<option value="800">גורנות
הגליל / גרנות
הגליל</option>
<option value="801">גוש
חלב</option>
<option value="807">גינוסר</option>
<option value="809">גיתה</option>
<option value="828">גניגר</option>
<option value="831">געתון</option>
<option value="832">גבע</option>
<option value="839">גשר</option>
<option value="842">דבורייה</option>
<option value="844">דברת</option>
<option value="846">דוב''ב</option>
<option value="847">דחי</option>
<option value="851">דישון</option>
<option value="852">דליה</option>
<option value="856">דן</option>
<option value="862">הודיות</option>
<option value="863">הושעיה</option>
<option value="865">הזורעים</option>
<option value="868">הילה</option>
<option value="875">הרדוף</option>
<option value="887">זרזיר</option>
<option value="899">חולתה</option>
<option value="900">חוסן</option>
<option value="907">חזון</option>
<option value="909">חלוץ</option>
<option value="912">חמאם</option>
<option value="913">חמדיה</option>
<option value="915">חניתה</option>
<option value="919">חפצי
בה</option>
<option value="925">חצרות
יוסף</option>
<option value="937">טירת
צבי</option>
<option value="942">טפחות</option>
<option value="957">יובל</option>
<option value="960">יזרעאל</option>
<option value="961">יחיעם</option>
<option value="967">יסעור</option>
<option value="975">יפתח</option>
<option value="979">ירדנה</option>
<option value="984">ישובי
הצפון</option>
<option value="989">כאבול</option>
<option value="991">כברי</option>
<option value="992">כדורי</option>
<option value="994">כחל</option>
<option value="996">כישור</option>
<option value="997">כליל</option>
<option value="998">כלנית</option>
<option value="999">כמאנה</option>
<option value="1004">כינרת
מושבה</option>
<option value="1019">כפר
ברוך</option>
<option value="1021">כפר
גליקסון</option>
<option value="1024">כפר
החורש</option>
<option value="1026">כפר
הנוער הדתי</option>
<option value="1033">כפר
זיתים</option>
<option value="1034">כפר
זרעית</option>
<option value="1036">כפר
חיטים</option>
<option value="1038">כפר
חנניה</option>
<option value="1042">כפר
יאסיף</option>
<option value="1052">כפר
מסריק</option>
<option value="1053">כפר
מצר</option>
<option value="1066">כפר
רופין</option>
<option value="1068">כפר
שמאי</option>
<option value="1073">כרי
דשא</option>
<option value="1074">כרכום</option>
<option value="1082">לביא</option>
<option value="1083">לבנים</option>
<option value="1085">להבות
הבשן</option>
<option value="1086">להבות
חביבה</option>
<option value="1090">לימן</option>
<option value="1092">לפידות</option>
<option value="1095">מאיר
שפיה</option>
<option value="1108">מגל</option>
<option value="1113">מולדת</option>
<option value="1122">מזרעה</option>
<option value="1124">מחנה
יבור</option>
<option value="1125">מחנה
יהודית</option>
<option value="1132">מייסר</option>
<option value="1134">מירב</option>
<option value="1141">מלכישוע</option>
<option value="1145">מנות</option>
<option value="1147">מנרה</option>
<option value="1150">מסדה</option>
<option value="1151">מסילות</option>
<option value="1154">מסעדה</option>
<option value="1159">מעוז
חיים</option>
<option value="1160">מעונה</option>
<option value="1161">מעיין
ברוך</option>
<option value="1164">מעלה
גלבוע</option>
<option value="1167">מעלה
עירון</option>
<option value="1169">מענית</option>
<option value="1173">מצובה</option>
<option value="1174">מירון</option>
<option value="1175">מצפה</option>
<option value="1178">מצר</option>
<option value="1179">מתת</option>
<option value="1187">משהד</option>
<option value="1191">משמר
הירדן</option>
<option value="1202">נאות
מרדכי</option>
<option value="1203">נאעורה</option>
<option value="1209">נווה
אבות</option>
<option value="1210">נווה
אור</option>
<option value="1212">נווה
איתן</option>
<option value="1237">נח"ל
נמרוד</option>
<option value="1244">נחף</option>
<option value="1247">נטועה</option>
<option value="1250">ניין</option>
<option value="1260">ניר
דוד</option>
<option value="1273">נס
עמים</option>
<option value="1279">נתיב
השיירה</option>
<option value="1281">סאג'ור</option>
<option value="1284">סולם</option>
<option value="1287">סח'נין</option>
<option value="1288">סלמה</option>
<option value="1291">סער</option>
<option value="1293">ספסופה</option>
<option value="1295">עבדון</option>
<option value="1296">עברון</option>
<option value="1298">ע'ג'ר</option>
<option value="1299">עדי</option>
<option value="1301">עוזייר</option>
<option value="1313">עילוט</option>
<option value="1324">עין
הנצי"ב</option>
<option value="1333">עין
יעקב</option>
<option value="1336">עין
מאהל</option>
<option value="1340">עין
קנייא</option>
<option value="1342">עין
שמר</option>
<option value="1347">עלמה</option>
<option value="1349">עמוקה</option>
<option value="1351">עמיעד</option>
<option value="1354">עמיר</option>
<option value="1357">עספיא</option>
<option value="1358">עספיה</option>
<option value="1361">עראמשה</option>
<option value="1363">ערערה</option>
<option value="1370">פוריידיס</option>
<option value="1375">פסוטה</option>
<option value="1377">פקיעין</option>
<option value="1380">פרוד</option>
<option value="1386">צביה</option>
<option value="1387">צבעון</option>
<option value="1395">צוריאל</option>
<option value="1399">צנדלה</option>
<option value="1409">קדרים</option>
<option value="1415">קלע</option>
<option value="1424">ראמה</option>
<option value="1425">ראס
אל-עין</option>
<option value="1426">ראס
עלי</option>
<option value="1429">רביד</option>
<option value="1433">רוויה</option>
<option value="1435">רומנה</option>
<option value="1436">רומת
הייב</option>
<option value="1440">רם-און</option>
<option value="1443">רמות
מנשה</option>
<option value="1444">רמות
נפתלי</option>
<option value="1447">רמת
השופט</option>
<option value="1451">רמת
צבי</option>
<option value="1456">רחוב</option>
<option value="1460">רשפים</option>
<option value="1465">שבלי</option>
<option value="1466">שגב</option>
<option value="1468">שדה
אילן</option>
<option value="1469">שדה
אליהו</option>
<option value="1470">שדה
אליעזר</option>
<option value="1476">שדה
נחום</option>
<option value="1485">שדי
תרומות</option>
<option value="1487">שדמות
דבורה</option>
<option value="1491">שומרה</option>
<option value="1495">שזור</option>
<option value="1504">שלוחות</option>
<option value="1505">שמיר</option>
<option value="1508">שניר</option>
<option value="1509">שעב</option>
<option value="1512">שער
הגולן</option>
<option value="1513">שער
העמקים</option>
<option value="1514">שער
מנשה</option>
<option value="1518">שפר</option>
<option value="1519">שפרעם</option>
<option value="1522">שרונה</option>
<option value="1523">שריד</option>
<option value="1539">תל
קציר</option>
<option value="1541">תל
תאומים</option>
<option value="1954">אבטליון</option>
<option value="1955">שדה-
נחום</option>
<option value="2062">פוריה
כפר עבודה</option>
<option value="2914">נווה
זיו</option>
<option value="2939">ראש
הנקרה</option>
<option value="3365">עיילבון</option>
<option value="3369">ירכא</option>
<option value="3383">טמרה</option>
<option value="3392">דפנה</option>
<option value="3401">יפיע</option>
<option value="3467">ביכורה</option>
<option value="3468">אבו
דיאב</option>
<option value="3469">כפר
קרע</option>
<option value="3580">שמרת</option>
<option value="3583">מגאר</option>
<option value="3594">כפר
כמא</option>
<option value="3596">עראבה</option>
<option value="3598">פקיעין
חדשה</option>
<option value="3844">ג'וליס</option>
<option value="3847">ג'יש</option>
<option value="3851">כאוכב
אבו אל היגא</option>
<option value="3852">כפר
מנדא</option>
<option value="3858">מרכז
כ''ח</option>
<option value="3860">עין אל
אסד</option>
<option value="3866">מצפה
אילן</option>
<option value="3872">גבעת
חביבה</option>
<option value="3883">חורפיש</option>
<option value="3967">מרכז
אזורי מרום
הגליל</option>
<option value="3988">כעביה
טבאש חג</option>
<option value="75">דימונה</option>
<option value="76">ערד</option>
<option value="77">קרית
גת</option>
<option value="78">קרית
מלאכי</option>
<option value="80">שדרות</option>
<option value="81">נתיבות</option>
<option value="82">אופקים</option>
<option value="105">חצרים</option>
<option value="599">אביגדור</option>
<option value="606">אבן
שמואל</option>
<option value="608">אבשלום</option>
<option value="613">אוהד</option>
<option value="620">אור
הנר</option>
<option value="623">אורות</option>
<option value="625">אורים</option>
<option value="629">אחוזם</option>
<option value="635">איבים</option>
<option value="637">אילות</option>
<option value="640">איתן</option>
<option value="644">אלומה</option>
<option value="653">אליפז</option>
<option value="660">אמונים</option>
<option value="663">אמציה</option>
<option value="673">אשלים</option>
<option value="675">ארז</option>
<option value="677">אשבול</option>
<option value="681">אשל
הנשיא</option>
<option value="687">באר
טוביה</option>
<option value="690">בארי</option>
<option value="696">ביטחה</option>
<option value="703">בית
גוברין</option>
<option value="706">בית
הגדי</option>
<option value="725">בית
ניר</option>
<option value="729">בית
עזרא</option>
<option value="732">בית
קמה</option>
<option value="737">בית
שקמה</option>
<option value="748">בני
עצמון</option>
<option value="757">ביצרון</option>
<option value="762">ברור
חיל</option>
<option value="763">ברוש</option>
<option value="764">ברכיה</option>
<option value="769">בת הדר</option>
<option value="770">בת
חצור</option>
<option value="775">גבולות</option>
<option value="776">גבים</option>
<option value="778">גבעולים</option>
<option value="791">גברעם</option>
<option value="804">גיאה</option>
<option value="810">גל און</option>
<option value="811">גלאור</option>
<option value="834">גבעתי</option>
<option value="836">גת</option>
<option value="837">גרופית</option>
<option value="843">דבירה</option>
<option value="857">דקל</option>
<option value="872">הודיה</option>
<option value="873">הר
עמשא</option>
<option value="877">ורדון</option>
<option value="878">זבדיאל</option>
<option value="879">זוהר</option>
<option value="880">זיקים</option>
<option value="884">זמרת</option>
<option value="886">זרועה</option>
<option value="888">זרחיה</option>
<option value="898">חולית</option>
<option value="904">חורה</option>
<option value="911">חלץ</option>
<option value="920">חצב</option>
<option value="921">חצבה</option>
<option value="922">חצור
אשדוד</option>
<option value="939">טללים</option>
<option value="943">יבול</option>
<option value="951">יד
מרדכי</option>
<option value="952">יד נתן</option>
<option value="956">יהל</option>
<option value="963">יכיני</option>
<option value="965">ינון</option>
<option value="976">יושיביה</option>
<option value="980">ירוחם</option>
<option value="985">ישע</option>
<option value="988">יתד</option>
<option value="993">כוכב
מיכאל</option>
<option value="995">כיסופים</option>
<option value="1000">כמהין</option>
<option value="1002">כנות</option>
<option value="1005">כסיפה</option>
<option value="1029">כפר
הרי''ף</option>
<option value="1031">כפר
ורבורג</option>
<option value="1048">כפר
מימון</option>
<option value="1051">כפר
מנחם</option>
<option value="1057">כפר
סילבר</option>
<option value="1060">כפר
עזה</option>
<option value="1072">כרמים</option>
<option value="1078">כרם
שלום</option>
<option value="1080">כרמיה</option>
<option value="1084">להב</option>
<option value="1091">לכיש</option>
<option value="1093">לקיה</option>
<option value="1099">מבועים</option>
<option value="1100">מבטחים</option>
<option value="1101">מבקיעים</option>
<option value="1109">מגן</option>
<option value="1123">מחנה
בלדד</option>
<option value="1139">מלילות</option>
<option value="1142">מנוחה</option>
<option value="1153">מסלול</option>
<option value="1156">מעגלים</option>
<option value="1171">מפלסים</option>
<option value="1177">מצפה
רמון</option>
<option value="1184">מרכז
שפירא</option>
<option value="1185">משאבי
שדה</option>
<option value="1188">משואות
יצחק</option>
<option value="1192">משמר
הנגב</option>
<option value="1198">משען</option>
<option value="1201">נאות
הכיכר</option>
<option value="1204">נבטים</option>
<option value="1205">נגבה</option>
<option value="1206">נהורה</option>
<option value="1208">נוגה</option>
<option value="1216">נווה
דקלים</option>
<option value="1217">נווה
זוהר</option>
<option value="1218">נווה
חריף</option>
<option value="1222">נווה
מבטח</option>
<option value="1226">נועם</option>
<option value="1235">נח"ל
יתיר</option>
<option value="1240">נחל
עוז</option>
<option value="1241">נחלה</option>
<option value="1252">ניצן</option>
<option value="1253">ניצנה</option>
<option value="1254">ניצני
סיני</option>
<option value="1256">ניצנים</option>
<option value="1258">ניר
בנים</option>
<option value="1261">ניר
ח''ן</option>
<option value="1263">ניר
יצחק</option>
<option value="1264">ניר
ישראל</option>
<option value="1265">ניר
משה</option>
<option value="1266">ניר
עוז</option>
<option value="1267">ניר עם</option>
<option value="1269">ניר
עקיבא</option>
<option value="1270">נירים</option>
<option value="1278">נתיב
העשרה</option>
<option value="1283">סגולה</option>
<option value="1286">סופה</option>
<option value="1289">סמר</option>
<option value="1290">סעד</option>
<option value="1292">ספיר</option>
<option value="1304">עוצם</option>
<option value="1305">עזוז</option>
<option value="1306">עזר</option>
<option value="1309">עזריקם</option>
<option value="1310">עידן</option>
<option value="1314">עילון</option>
<option value="1315">עין
אובות</option>
<option value="1319">עין
גדי</option>
<option value="1321">עין
הבשור</option>
<option value="1327">עין
השלושה</option>
<option value="1330">עין
חצבה</option>
<option value="1332">עין
יהב</option>
<option value="1339">עין
צורים</option>
<option value="1344">עין
תמר</option>
<option value="1346">עלומים</option>
<option value="1352">עמיעוז</option>
<option value="1359">עוזה</option>
<option value="1365">פארן</option>
<option value="1366">פדויים</option>
<option value="1372">פטיש</option>
<option value="1376">פעמי
תש''ז</option>
<option value="1382">פרי גן</option>
<option value="1385">צאלים</option>
<option value="1389">צוחר</option>
<option value="1391">צופר</option>
<option value="1405">קדמה</option>
<option value="1410">קוממיות</option>
<option value="1412">קטורה</option>
<option value="1413">קלחים</option>
<option value="1427">רבדים</option>
<option value="1428">רביבים</option>
<option value="1432">רווחה</option>
<option value="1434">רוחמה</option>
<option value="1454">רנן</option>
<option value="1455">רעים</option>
<option value="1461">רתמים</option>
<option value="1467">שגב-שלום</option>
<option value="1471">שדה
בוקר</option>
<option value="1472">שדה
דוד</option>
<option value="1473">שדה
יואב</option>
<option value="1475">שדה
משה</option>
<option value="1478">שדה
ניצן</option>
<option value="1479">שדה
עוזיהו</option>
<option value="1480">שדה
צבי</option>
<option value="1483">שדי
אברהם</option>
<option value="1489">שובה</option>
<option value="1490">שובל</option>
<option value="1492">שוקדה</option>
<option value="1496">שחר</option>
<option value="1497">שחרות</option>
<option value="1498">שיבולים</option>
<option value="1499">שיזפון</option>
<option value="1500">שיטים</option>
<option value="1503">שלווה</option>
<option value="1507">שמרייה</option>
<option value="1517">שפיר</option>
<option value="1521">שקף</option>
<option value="1524">שרשרת</option>
<option value="1526">שתולים</option>
<option value="1528">תדהר</option>
<option value="1530">תושייה</option>
<option value="1531">תימורים</option>
<option value="1540">תל שבע</option>
<option value="1542">תלמי
אליהו</option>
<option value="1544">תלמי
ביל''ו</option>
<option value="1545">תלמי
יוסף</option>
<option value="1546">תלמי
יחיאל</option>
<option value="1547">תלמי
יפה</option>
<option value="1548">תלמים</option>
<option value="1551">תפרח</option>
<option value="1552">תקומה</option>
<option value="1774">גילת</option>
<option value="3372">קדיתא</option>
<option value="3447">קרית
חינוך שדות
נגב</option>
<option value="3473">בית
שיקמה</option>
<option value="3479">אורון</option>
<option value="3491">מדרשת
בן גוריון</option>
<option value="3492">עד
הלום</option>
<option value="3575">ניצן ב'</option>
<option value="3586">טל אור</option>
<option value="3587">אבו
ג'ווייעד</option>
<option value="3864">באר
גנים</option>
<option value="3865">בני
דקלים</option>
<option value="3867">כרמית</option>
<option value="3868">נטע</option>
<option value="3869">שומריה</option>
<option value="3870">מרחב
עם</option>
<option value="3871">דורות</option>
<option value="3993">פעמי
תש'ז</option>
<option value="114">קרית
קריניצי</option>
<option value="211">כפר
יעבץ</option>
<option value="399">חצור</option>
<option value="422">שכניהו</option>
<option value="774">גאליה</option>
<option value="786">גבעת
כ''ח</option>
<option value="803">גזר</option>
<option value="805">גיבתון</option>
<option value="817">גן
חיים</option>
<option value="821">גן
שורק</option>
<option value="822">גן
שלמה</option>
<option value="823">גנות</option>
<option value="825">גני
הדר</option>
<option value="826">גני
יוחנן</option>
<option value="883">זמר</option>
<option value="897">חולדה</option>
<option value="906">חורשים</option>
<option value="918">חפץ
חיים</option>
<option value="924">חצרות
חולדה</option>
<option value="926">חצרות
כ"ח</option>
<option value="934">טירה</option>
<option value="955">ידידיה</option>
<option value="966">יסודות</option>
<option value="970">יעף</option>
<option value="977">יציץ</option>
<option value="983">ישובי
הסביבה</option>
<option value="1017">כפר
ברא</option>
<option value="1059">כפר
עבודה</option>
<option value="1076">כרם
יבנה</option>
<option value="1097">מבוא
מודיעים</option>
<option value="1098">מבואות
ים</option>
<option value="1180">מקווה
ישראל</option>
<option value="1214">נווה
אפרים</option>
<option value="1227">נוף
איילון</option>
<option value="1228">נופך</option>
<option value="1249">נטעים</option>
<option value="1259">ניר
גלים</option>
<option value="1274">נעורים</option>
<option value="1276">נען</option>
<option value="1294">סתריה</option>
<option value="1312">עיינות</option>
<option value="1345">עינת</option>
<option value="1373">פלמחים</option>
<option value="1390">צופייה</option>
<option value="1400">צפריה</option>
<option value="1422">קרית
שלמה</option>
<option value="1442">רמות
מאיר</option>
<option value="1446">רמת
הכובש</option>
<option value="1515">שערי
אברהם</option>
<option value="1537">תל
יצחק</option>
<option value="1777">חמד</option>
<option value="3489">נווה
הרצוג</option>
<option value="84">תל
מונד</option>
<option value="91">כוכב
יאיר</option>
<option value="92">מתן</option>
<option value="93">נירית</option>
<option value="94">צור
נתן</option>
<option value="96">יישובי
השומרון</option>
<option value="144">חגור</option>
<option value="212">חרותים</option>
<option value="397">שדה
חמד</option>
<option value="445">ירחיב</option>
<option value="676">ארסוף</option>
<option value="749">בני
ציון</option>
<option value="756">בצרה</option>
<option value="824">גנות
הדר</option>
<option value="830">געש</option>
<option value="978">יקום</option>
<option value="1055">כפר
נטר</option>
<option value="1061">כפר
פינס</option>
<option value="1255">ניצני
עוז</option>
<option value="1343">עין
שריד</option>
<option value="1371">פורת</option>
<option value="1474">שדה
יצחק</option>
<option value="1516">שפיים</option>
<option value="2921">רמת
הדר</option>
<option value="2924">נווה
הדסה</option>
<option value="3108">צור
יצחק</option>
<option value="3233">לא
מצוייןשרון</option>
<option value="3380">חרוצים</option>
<option value="3483">צור
יגאל</option>
<option value="3849">ג'לג'וליה</option>
<option value="3990">כוכב
יאיר / צור
יגאל</option>
<option value="18" selected>ירושלים</option>
<option value="601">אביעזר</option>
<option value="610">אדרת</option>
<option value="641">איתנים</option>
<option value="785">גבעת
ישעיהו</option>
<option value="789">גבעת
שמש</option>
<option value="850">דייר
ראפאת</option>
<option value="874">הראל</option>
<option value="882">זכריה</option>
<option value="949">יד
השמונה</option>
<option value="954">ידידה</option>
<option value="1032">כפר
זוהרים</option>
<option value="1087">לוזית</option>
<option value="1089">שריגים</option>
<option value="1128">נחשון</option>
<option value="1152">מסילת
ציון</option>
<option value="1224">נווה
מיכאל</option>
<option value="1225">נווה
שלום</option>
<option value="1239">נחושה</option>
<option value="1280">נתיב
הל"ה</option>
<option value="1297">עגור</option>
<option value="1334">עין
כרם</option>
<option value="1401">צפרירים</option>
<option value="1482">שדות
מיכה</option>
<option value="1532">תירוש</option>
<option value="1550">תעוז</option>
<option value="1553">תרום</option>
<option value="97">אורנית</option>
<option value="213">אבני
חפץ</option>
<option value="214">אדורה</option>
<option value="216">אור
הגנוז</option>
<option value="218">אחיה</option>
<option value="219">איבי
הנחל</option>
<option value="220">איתמר</option>
<option value="221">אלון</option>
<option value="222">אלון
מורה</option>
<option value="224">אלי
סיני</option>
<option value="228">אלקנה</option>
<option value="230">ארגמן</option>
<option value="231">אריאל</option>
<option value="232">אש
קודש</option>
<option value="233">אשכולות</option>
<option value="234">בדולח</option>
<option value="235">בית-אל</option>
<option value="236">בית
אריה</option>
<option value="238">בית
חגי</option>
<option value="239">בית
חורון</option>
<option value="240">בית
יתיר</option>
<option value="241">ביתר
עילית</option>
<option value="242">בקעות</option>
<option value="244">ברוכין</option>
<option value="245">ברכה</option>
<option value="246">ברקן</option>
<option value="248">גבעון
החדשה</option>
<option value="250">גבעת
אסף</option>
<option value="251">גבעת
הראל</option>
<option value="252">גבעת
זאב</option>
<option value="253">גדיד</option>
<option value="254">גיתית</option>
<option value="255">גלגל</option>
<option value="256">גן אור</option>
<option value="258">גנים</option>
<option value="259">דוגית</option>
<option value="260">דולב</option>
<option value="264">חוות
שדה בר</option>
<option value="265">חומש</option>
<option value="266">חיננית</option>
<option value="267">חמדת</option>
<option value="268">חמרה</option>
<option value="270">חרמש</option>
<option value="271">חרשה</option>
<option value="273">טל
מנשה</option>
<option value="274">טלמון</option>
<option value="275">טנא</option>
<option value="276">ייטב</option>
<option value="277">יפית</option>
<option value="278">יצהר</option>
<option value="279">יקיר</option>
<option value="280">כדים</option>
<option value="281">כוכב
השחר</option>
<option value="282">כוכב
יעקב</option>
<option value="285">כפר
דרום</option>
<option value="286">כפר ים</option>
<option value="289">כרמל</option>
<option value="290">שני
ליבנה</option>
<option value="291">מבוא
דותן</option>
<option value="292">מבוא
חורון</option>
<option value="293">מבואות
יריחו</option>
<option value="295">מגדלים</option>
<option value="296">מגרון</option>
<option value="297">מורג</option>
<option value="299">מחולה</option>
<option value="300">מיצד -
אספר</option>
<option value="301">מכורה</option>
<option value="302">מכמש</option>
<option value="303">מעון</option>
<option value="305">מעלה
אפרים</option>
<option value="306">מעלה
חבר</option>
<option value="307">מעלה
לבונה</option>
<option value="310">מעלה
שומרון</option>
<option value="311">מצפה
אשתמוע</option>
<option value="312">מצפה
דני</option>
<option value="313">מצפה
חגית</option>
<option value="314">מצפה
יאיר</option>
<option value="316">מצפה
כרמים</option>
<option value="319">משואה</option>
<option value="320">משכיות</option>
<option value="321">נגוהות</option>
<option value="325">נוה
דקלים</option>
<option value="326">נופי
נחמיה</option>
<option value="327">נופי
פרת</option>
<option value="328">נופים</option>
<option value="330">נחליאל</option>
<option value="332">ניסנית</option>
<option value="333">נעלה</option>
<option value="334">נערן</option>
<option value="335">נצר
חזני</option>
<option value="336">נצרים</option>
<option value="337">נריה</option>
<option value="338">נתיב
הגדוד</option>
<option value="339">סוסיא</option>
<option value="340">סלעית</option>
<option value="341">סנסנה</option>
<option value="342">עדי-עד</option>
<option value="344">עטרת</option>
<option value="345">עינב</option>
<option value="346">עלי</option>
<option value="347">עלי
זהב</option>
<option value="348">עמנואל</option>
<option value="350">עפרה</option>
<option value="351">עץ
אפרים</option>
<option value="352">עצמונה</option>
<option value="353">עשהאל</option>
<option value="354">עתניאל</option>
<option value="355">פאת
שדה</option>
<option value="356">פדואל</option>
<option value="358">פסגות</option>
<option value="359">פצאל</option>
<option value="360">צופים</option>
<option value="361">קדומים</option>
<option value="362">קטיף</option>
<option value="363">קידה</option>
<option value="366">קרית
ארבע</option>
<option value="367">קרית
נטפים</option>
<option value="368">קרית
ספר</option>
<option value="369">קרני
שומרון</option>
<option value="371">רבבה</option>
<option value="372">רועי</option>
<option value="373">רותם</option>
<option value="374">רחלים</option>
<option value="375">ריחן</option>
<option value="376">רימונים</option>
<option value="377">רפיח
ים</option>
<option value="378">שא-נור</option>
<option value="379">שבות
רחל</option>
<option value="380">שבי
שומרון</option>
<option value="381">שדמות
מחולה</option>
<option value="382">שילה</option>
<option value="383">שימעה</option>
<option value="384">שירת
הים</option>
<option value="385">שליו</option>
<option value="387">שקד</option>
<option value="388">תומר</option>
<option value="390">תל
קטיפא</option>
<option value="391">תלם</option>
<option value="392">תפוח</option>
<option value="424">שערי
תקווה</option>
<option value="665">אספר</option>
<option value="755">בית אל</option>
<option value="891">חגי</option>
<option value="910">חלמיש</option>
<option value="1070">כפר
תפוח</option>
<option value="1166">מעלה
מכמש</option>
<option value="1172">מצדות
יהודה</option>
<option value="1199">מתתיהו</option>
<option value="1233">נח"ל
אלישע</option>
<option value="1234">נח"ל
חמדת</option>
<option value="1236">נח"ל
משכיות</option>
<option value="1238">נח"ל
רותם</option>
<option value="1251">ניל''י</option>
<option value="1271">נירן</option>
<option value="1275">נעמי</option>
<option value="1285">סוסיה</option>
<option value="1356">ענב</option>
<option value="1374">פני
חבר</option>
<option value="1462">שא נור</option>
<option value="1506">שמעה</option>
<option value="1703">אלפי
מנשה</option>
<option value="2919">נוה
מנחם</option>
<option value="2945">צופין</option>
<option value="3394">באקה</option>
<option value="3472">תוקוע</option>
<option value="3484">בתיר</option>
<option value="3485">בית
רחאל</option>
<option value="3848">מפעלי
ברקן</option>
<option value="3855">אל מתן</option>
<option value="3856">חוות
גלעד</option>
<option value="3857">חוות
יאיר</option>
<option value="3863">סלפית</option>
<option value="3873">מטה
בנימין</option>
<option value="3874">בית
לחם</option>
<option value="3984">עופרים</option>
<option value="612">אודם</option>
<option value="648">אלוני
הבשן</option>
<option value="659">אל רום</option>
<option value="664">אניעם</option>
<option value="671">אפיק</option>
<option value="783">גבעת
יואב</option>
<option value="894">חד נס</option>
<option value="917">חספין</option>
<option value="959">יונתן</option>
<option value="1003">כנף</option>
<option value="1040">כפר
חרוב</option>
<option value="1165">מעלה
גמלא</option>
<option value="1182">מרום
גולן</option>
<option value="1329">עין
זיוון</option>
<option value="1417">קצרין</option>
<option value="1423">קשת</option>
<option value="1449">רמת
מגשימים</option>
<option value="1510">שעל</option>
<option value="1579">בני
יהודה</option>
<option value="1581">קדמת
צבי</option>
<option value="1582">רמת
הגולן</option>
<option value="1733">אורטל</option>
<option value="1735">גשור</option>
<option value="1736">מבוא
חמה</option>
<option value="1737">מיצר</option>
<option value="1738">מצוק
עורבים</option>
<option value="1739">נאות
גולן</option>
<option value="1740">נוב</option>
<option value="1741">נווה
אטי''ב</option>
<option value="1742">נטור</option>
<option value="1743">נמרוד</option>
<option value="1744">קלע
אלון</option>
<option value="1745">רמות</option>
<option value="3854">מג'דל
שמס</option>
<option value="65">ראש
פינה</option>
<option value="243">בר
יוחאי</option>
<option value="441">מלכיה</option>
<option value="598">אביבים</option>
<option value="661">אמירים</option>
<option value="793">גדות</option>
<option value="853">דלתון</option>
<option value="860">הגושרים</option>
<option value="1015">כפר
בלום</option>
<option value="1022">כפר
גלעדי</option>
<option value="1027">כפר
הנשיא</option>
<option value="1056">כפר
סאלד</option>
<option value="1075">כרם בן
זמרה</option>
<option value="1126">מחניים</option>
<option value="1181">מרגליות</option>
<option value="1186">משגב
עם</option>
<option value="1282">סאסא</option>
<option value="1463">שאר
ישוב</option>
<option value="1477">שדה
נחמיה</option>
<option value="1771">זרעית</option>
<option value="2895">יראון</option>
<option value="2927">אילון</option>
<option value="2929">גרנות
הגליל</option>
<option value="3237">עין
זיתים</option>
<option value="3393">ורד
הגליל</option>
<option value="3402">אשדות
יעקב מאוחד</option>
<option value="3456">תל חי</option>
<option value="3546">אבטין</option>
<option value="3846">ריחאנייה</option>
<option value="3879">טובא
זנגריה</option>
<option value="3968">כדיתה</option>
<option value="23">נהריה</option>
<option value="52">עכו</option>
<option value="130">רגבה</option>
<option value="140">גשר
הזיו</option>
<option value="401">גוש
שגב</option>
<option value="427">שלומי</option>
<option value="609">אדמית</option>
<option value="672">אפק</option>
<option value="1065">כפר
ראש הנקרה</option>
<option value="1088">לוחמי
הגטאות</option>
<option value="1323">עין
המפרץ</option>
<option value="1464">שבי
ציון</option>
<option value="2916">מעלות
תרשיחא</option>
<option value="3371">אבו
סנאן</option>
<option value="3453">שלומית</option>
<option value="3590">מעיליא</option>
<option value="3845">מגדל
תפן</option>
<option value="3875">אידמית</option>
<option value="3992">ג'דידה
מכר</option>
<option value="63">נצרת
עילית</option>
<option value="64">טבריה</option>
<option value="66">נצרת</option>
<option value="129">מגדל
העמק</option>
<option value="317">מצפה
נטופה</option>
<option value="400">גבעת
אבני</option>
<option value="614">אוהלו</option>
<option value="645">אלומות</option>
<option value="674">ארבל</option>
<option value="679">אשדות
יעקב איחוד</option>
<option value="736">בית
שאן</option>
<option value="845">דגניה
א'</option>
<option value="858">האון</option>
<option value="870">הסוללים</option>
<option value="903">חוקוק</option>
<option value="944">יבנאל</option>
<option value="1105">מגדל</option>
<option value="1157">מעגן</option>
<option value="1318">עין גב</option>
<option value="1369">פוריה
עילית</option>
<option value="1397">ציפורי</option>
<option value="1768">מסד</option>
<option value="1956">סמדר</option>
<option value="1957">משמר
השלושה</option>
<option value="1958">בית גן</option>
<option value="2892">אשדות
איחוד</option>
<option value="3362">פוריה
נווה עובד</option>
<option value="3420">איכסאל</option>
<option value="3421">ריינה</option>
<option value="3422">כפר
כנא</option>
<option value="3423">טורעאן</option>
<option value="3424">בועיינה
נוג'יידאת</option>
<option value="3451">מנחמיה</option>
<option value="3486">דגניה
ב'</option>
<option value="17">יוקנעם
עילית</option>
<option value="28">עפולה</option>
<option value="67">רמת
ישי</option>
<option value="407">כפר
גדעון</option>
<option value="425">תמרת</option>
<option value="438">נהלל</option>
<option value="588">בית
שערים</option>
<option value="590">יוקנעם
מושבה</option>
<option value="618">אומן</option>
<option value="630">אחוזת
ברק</option>
<option value="647">אלוני
אבא</option>
<option value="650">אלונים</option>
<option value="722">בית
לחם הגלילית</option>
<option value="740">בלפוריה</option>
<option value="766">ברק</option>
<option value="779">גבעת
אלה</option>
<option value="795">גדיש</option>
<option value="796">גדעונה</option>
<option value="802">גזית</option>
<option value="820">גן נר</option>
<option value="864">הזורע</option>
<option value="867">היוגב</option>
<option value="890">חבר</option>
<option value="916">חנתון</option>
<option value="930">קרית
טבעון</option>
<option value="969">יעל</option>
<option value="974">יפעת</option>
<option value="1043">כפר
יהושע</option>
<option value="1044">כפר
יחזקאל</option>
<option value="1063">כפר
קיש</option>
<option value="1107">מגידו</option>
<option value="1110">מגן
שאול</option>
<option value="1111">מדרך
עוז</option>
<option value="1121">מזרע</option>
<option value="1131">מיטב</option>
<option value="1138">מלאה</option>
<option value="1146">מרחביה
מושב</option>
<option value="1193">משמר
העמק</option>
<option value="1231">נורית</option>
<option value="1262">ניר
יפה</option>
<option value="1320">עין
דור</option>
<option value="1326">עין
השופט</option>
<option value="1331">עין
חרוד איחוד</option>
<option value="1381">פרזון</option>
<option value="1445">רמת
דוד</option>
<option value="1536">תל
יוסף</option>
<option value="1538">תל
עדשים</option>
<option value="1786">קיבוץ
דליה</option>
<option value="1788">אליקים</option>
<option value="1789">עין
העמק</option>
<option value="1790">גלעד</option>
<option value="2910">דבורה</option>
<option value="2917">עמק
יזרעאל</option>
<option value="3356">אדירים</option>
<option value="3368">אביטל</option>
<option value="3427">בסמת
טבעון</option>
<option value="3439">נין</option>
<option value="3442">מרחביה
קיבוץ</option>
<option value="3464">עין
חרוד מאוחד</option>
<option value="3470">תלפית</option>
<option value="3476">מסיליה</option>
<option value="3481">גיניגר</option>
<option value="3490">מנשית
זבדה</option>
<option value="15">חיפה</option>
<option value="25">נשר</option>
<option value="68">עתלית</option>
<option value="83">טירת
כרמל</option>
<option value="436">עין
הוד</option>
<option value="699">בית
אורן</option>
<option value="771">בת
שלמה</option>
<option value="833">גבע
כרמל</option>
<option value="841">דאלית
אל כרמל</option>
<option value="855">דור</option>
<option value="859">הבונים</option>
<option value="866">החותרים</option>
<option value="1020">כפר
גלים</option>
<option value="1077">כרם
מהר''ל</option>
<option value="1104">מגדים</option>
<option value="1245">נחשולים</option>
<option value="1268">ניר
עציון</option>
<option value="1303">עופר</option>
<option value="1316">עין
איילה</option>
<option value="1335">עין
כרמל</option>
<option value="1402">צרופה</option>
<option value="3348">עוספיא</option>
<option value="3395">אום אל
פחם</option>
<option value="3437">גבעת
וולפסון</option>
<option value="3441">כעביה
טבאש חג'אג'רה</option>
<option value="3480">נווה
ים</option>
<option value="3584">מנשיה</option>
<option value="3591">אעבלין</option>
<option value="31">קרית
אתא</option>
<option value="32">קרית
ביאליק</option>
<option value="33">קרית
מוצקין</option>
<option value="34">קרית
ים</option>
<option value="429">רכסים</option>
<option value="627">אושה</option>
<option value="946">יגור</option>
<option value="1013">כפר
ביאליק</option>
<option value="1025">כפר
המכבי</option>
<option value="1039">כפר
חסידים א'</option>
<option value="1418">קריות</option>
<option value="1448">רמת
יוחנן</option>
<option value="1613">קרית
בנימין</option>
<option value="3454">קרית
חיים</option>
<option value="3455">קרית
שמואל</option>
<option value="3471">כפר
חסידים ב'</option>
<option value="13">חדרה</option>
<option value="404">גן
שמואל</option>
<option value="652">אליכין</option>
<option value="1094">מאור</option>
<option value="1112">מדרשת
רופין</option>
<option value="1652">חופים</option>
<option value="2923">פארק
תעשיות עמק
חפר</option>
<option value="3367">בית
ליד</option>
<option value="26">נתניה</option>
<option value="85">פרדסיה</option>
<option value="87">אבן
יהודה</option>
<option value="88">כפר
יונה</option>
<option value="719">בית
יהושע</option>
<option value="1511">שער
אפרים</option>
<option value="1714">אודים</option>
<option value="2938">קדימה
צורן</option>
<option value="3478">אילנות</option>
<option value="3582">מועצה
אזורית לב
השרון</option>
<option value="3589">טייבה</option>
<option value="3592">קלנסווה</option>
<option value="5">בנימינה
גבעת עדה</option>
<option value="12">זכרון
יעקב</option>
<option value="53">קיסריה</option>
<option value="454">גבעת
עדה</option>
<option value="597">אביאל</option>
<option value="621">אור
עקיבא</option>
<option value="649">אלוני
יצחק</option>
<option value="716">בית
חנניה</option>
<option value="787">גבעת
ניל''י</option>
<option value="816">גן
השומרון</option>
<option value="1130">מי עמי</option>
<option value="1158">מעגן
מיכאל</option>
<option value="1162">מעיין
צבי</option>
<option value="1196">משמרות</option>
<option value="1353">עמיקם</option>
<option value="1378">פרדס
חנה כרכור</option>
<option value="1430">רגבים</option>
<option value="1481">שדות
ים</option>
<option value="1543">תלמי
אלעזר</option>
<option value="1651">קציר
חריש</option>
<option value="2937">עין
עירון</option>
<option value="10">הרצליה</option>
<option value="39">רמת
השרון</option>
<option value="586">רשפון</option>
<option value="813">גליל
ים</option>
<option value="3440">כפר
שמריהו</option>
<option value="3547">הכפר
הירוק</option>
<option value="19">כפר
סבא</option>
<option value="40">רעננה</option>
<option value="207">צופית</option>
<option value="670">אייל</option>
<option value="702">בית
ברל</option>
<option value="1049">כפר
מל''ל</option>
<option value="1257">ניר
אליהו</option>
<option value="1441">רמות
השבים</option>
<option value="1772">גבעת
ח''ן</option>
<option value="1780">נווה
ימין</option>
<option value="1783">שדה
ורבורג</option>
<option value="2920">כפר
הדר</option>
<option value="42">תל
אביב יפו</option>
<option value="27">סביון</option>
<option value="69">קרית
אונו</option>
<option value="71">גבעת
שמואל</option>
<option value="72">גני
תקווה</option>
<option value="109">אור
יהודה</option>
<option value="688">בארות
יצחק</option>
<option value="1534">תל
השומר</option>
<option value="1776">גת
רימון</option>
<option value="1779">כפר
נופך</option>
<option value="2936">יהוד
מונוסון</option>
<option value="3986">כפר
אז''ר</option>
<option value="3987">רמת
פנקס</option>
<option value="6">בת ים</option>
<option value="14">חולון</option>
<option value="137">אזור</option>
<option value="30">פתח
תקווה</option>
<option value="115">ראש
העין</option>
<option value="131">אלעד</option>
<option value="781">גבעת
השלושה</option>
<option value="1058">כפר
סירקין</option>
<option value="1170">מעש</option>
<option value="1246">נחשונים</option>
<option value="3443">כפר
קאסם</option>
<option value="35">ראשון
לציון</option>
<option value="585">בית
דגן</option>
<option value="1035">כפר
חב"ד</option>
<option value="1194">משמר
השבעה</option>
<option value="3370">צריפין</option>
<option value="7">גבעתיים</option>
<option value="38">רמת גן</option>
<option value="128">בני
ברק</option>
<option value="22">מודיעין
מכבים רעות</option>
<option value="41">שוהם</option>
<option value="101">לפיד</option>
<option value="103">כפר
האורנים</option>
<option value="104">שילת</option>
<option value="272">חשמונאים</option>
<option value="583">מודיעין
עילית</option>
<option value="1067">כפר
רות</option>
<option value="21">לוד</option>
<option value="37">רמלה</option>
<option value="24">נס
ציונה</option>
<option value="36">רחובות</option>
<option value="127">באר
יעקב</option>
<option value="408">כפר
הנגיד</option>
<option value="715">בית
חנן</option>
<option value="727">בית
עובד</option>
<option value="1120">מזכרת
בתיה</option>
<option value="1277">נצר
סירני</option>
<option value="3581">אירוס</option>
<option value="3981">קרית
עקרון</option>
<option value="2">אשדוד</option>
<option value="79">אשקלון</option>
<option value="734">בית
רבן</option>
<option value="744">בני
דרום</option>
<option value="819">גן
יבנה</option>
<option value="2934">גן
דרום</option>
<option value="106">להבים</option>
<option value="107">עומר</option>
<option value="108">מיתר</option>
<option value="1527">תאשור</option>
<option value="1763">באר
שבע</option>
<option value="1764">רהט</option>
<option value="3391">רמת
חובב</option>
<option value="3405">גבעות
בר</option>
<option value="1">אילת</option>
<option value="237">בית
הערבה</option>
<option value="318">מצפה
שלם</option>
<option value="686">באר
אורה</option>
<option value="962">יטבתה</option>
<option value="1232">אבנת</option>
<option value="3418">צוקים</option>
<option value="3438">עבדה</option>
<option value="3576">עין
בוקק</option>
<option value="44">כרמיאל</option>
<option value="402">גילון</option>
<option value="413">משגב</option>
<option value="1396">צורית</option>
<option value="1725">חרשים</option>
<option value="1726">יובלים</option>
<option value="1727">יעד</option>
<option value="1728">קורנית</option>
<option value="1729">עצמון
שגב</option>
<option value="1730">לבון</option>
<option value="1731">מורשת</option>
<option value="1732">מנוף</option>
<option value="1748">אשחר</option>
<option value="1749">אבטליון</option>
<option value="1750">הר
חלוץ</option>
<option value="1751">הררית</option>
<option value="1752">טל אל</option>
<option value="1753">כמון</option>
<option value="1754">לוטם</option>
<option value="1755">מורן</option>
<option value="1756">מכמנים</option>
<option value="1757">מצפה
אבי''ב</option>
<option value="1758">שורשים</option>
<option value="1759">שכניה</option>
<option value="1760">רקפת</option>
<option value="1761">תובל</option>
<option value="1765">מעלה
צביה</option>
<option value="3482">כיסרא
סומיע</option>
<option value="3577">יחד</option>
<option value="3578">פלך</option>
<option value="3579">עמקה</option>
<option value="3588">מג'ד אל
כרום</option>
<option value="3850">דייר
חנא</option>
<option value="3989">עצמון</option>
<option value="3103">גפן</option>
<option value="3366">בית
חנינא</option>
<option value="3466">בטחה</option>
<option value="3553">בית
וזן</option>
<option value="3475">מצוקי
דרגות</option>
<option value="3597">לוטן</option>
<option value="3448">איטליה</option>
<option value="3449">ארה"ב</option>
<option value="3450">גרמניה</option>
<option value="4">בית
שמש</option>
<option value="683">אשתאול</option>
<option value="885">זנוח</option>
<option value="986">ישעי</option>
<option value="1127">מחסיה</option>
<option value="1243">נחם</option>
<option value="1403">צרעה</option>
<option value="3861">מפעלי
נחם הר טוב</option>
<option value="49">מבשרת
ציון</option>
<option value="116">אבו
גוש</option>
<option value="118">מוצא
עילית</option>
<option value="122">נווה
אילן</option>
<option value="123">נטף</option>
<option value="125">שורש</option>
<option value="134">מעלה
אדומים</option>
<option value="225">אלמוג</option>
<option value="261">הר אדר</option>
<option value="263">ורד
יריחו</option>
<option value="283">כפר
אדומים</option>
<option value="315">מצפה
יריחו</option>
<option value="365">קליה</option>
<option value="412">מעלה
החמישה</option>
<option value="605">אבן
ספיר</option>
<option value="622">אורה</option>
<option value="669">אפרת</option>
<option value="712">בית
זית</option>
<option value="723">בית
מאיר</option>
<option value="726">בית
נקופה</option>
<option value="761">בר
גיורא</option>
<option value="777">גבע
בנימין</option>
<option value="784">גבעת
יערים</option>
<option value="1006">כסלון-ב</option>
<option value="1116">מושבי
הסביבה</option>
<option value="1129">מטע</option>
<option value="1272">נס
הרים</option>
<option value="1337">עין
נקובא</option>
<option value="1341">עין
ראפה</option>
<option value="1348">עלמון</option>
<option value="1350">עמינדב</option>
<option value="1388">צובה</option>
<option value="1393">צור
הדסה</option>
<option value="1419">קרית
יערים</option>
<option value="1420">קרית
ענבים</option>
<option value="1452">רמת
רזיאל</option>
<option value="1453">רמת
רחל</option>
<option value="1488">שואבה</option>
<option value="1782">מוצא</option>
<option value="2988">מבוא
ביתר</option>
<option value="3574">שלומציון</option>
<option value="3593">מושבים</option>
<option value="3595">בית
חאנון</option>
<option value="8">גדרה</option>
<option value="54">יבנה</option>
<option value="592">בני
עי''ש</option>
<option value="714">בית
חלקיה</option>
<option value="948">יד
בנימין</option>
<option value="1364">עשרת</option>
<option value="3551">מפעלי
כנות</option>
<option value="3970">כפר
אביב</option>
<option value="3971">כפר
מרדכי</option>
<option value="3972">מישר</option>
<option value="3973">משגב
דב</option>
<option value="3974">שדמה</option>
<option value="3975">ערוגות</option>
<option value="3976">כפר
אחים</option>
<option value="3977">אחווה</option>
<option value="3978">בני
ראם</option>
<option value="3979">גני טל</option>
<option value="3980">גן
הדרום</option>
<option value="3991">מחנה
תל נוף</option>
<option value="971">יערה</option>
<option value="1525">שתולה</option>
<option value="209">חרות</option>
<option value="745">בני
דרור</option>
<option value="773">גאולים</option>
<option value="964">ינוב</option>
<option value="1028">כפר הס</option>
<option value="1197">משמרת</option>
<option value="1307">עזריאל</option>
<option value="1328">עין
ורד</option>
<option value="1394">צור
משה</option>
<option value="1549">תנובות</option>
<option value="1781">נורדיה</option>
<option value="112">מגשימים</option>
<option value="210">אחיעזר</option>
<option value="423">שעלבים</option>
<option value="437">ניר
צבי</option>
<option value="446">מושב
גימזו</option>
<option value="452">טל שחר</option>
<option value="594">מצליח</option>
<option value="633">אחיסמך</option>
<option value="704">בית
גמליאל</option>
<option value="718">בית
חשמונאי</option>
<option value="724">בית
נחמיה</option>
<option value="728">בית
עוזיאל</option>
<option value="730">בית
עריף</option>
<option value="741">בן
זכאי</option>
<option value="743">בן שמן</option>
<option value="746">בני
עטרות</option>
<option value="751">בניה</option>
<option value="759">בקוע</option>
<option value="768">ברקת</option>
<option value="780">גבעת
ברנר</option>
<option value="806">גיזו</option>
<option value="808">גינתון</option>
<option value="814">גמזו</option>
<option value="881">זיתן</option>
<option value="893">חדיד</option>
<option value="935">טירת
יהודה</option>
<option value="947">יגל</option>
<option value="953">יד
רמב''ם</option>
<option value="987">ישרש</option>
<option value="1010">כפר
אוריה</option>
<option value="1016">כפר בן
נון</option>
<option value="1023">כפר
דניאל</option>
<option value="1041">כפר
טרומן</option>
<option value="1069">כפר
שמואל</option>
<option value="1119">מזור</option>
<option value="1189">משמר
איילון</option>
<option value="1190">משמר
דוד</option>
<option value="1242">נחלים</option>
<option value="1308">עזריה</option>
<option value="1367">פדיה</option>
<option value="1384">פתחיה</option>
<option value="1398">צלפון</option>
<option value="1408">קדרון</option>
<option value="1439">רינתיה</option>
<option value="1762">כרמי
יוסף</option>
<option value="2915">השפלה</option>
<option value="3487">צופיה</option>
<option value="3488">קבוצת
יבנה</option>
<option value="3552">בן שמן
כפר נוער</option>
<option value="3859">קרית
שדה התעופה</option>
<option value="3862">באקה א
שרקיה</option>
<option value="3982">כפר
ביל''ו</option>
<option value="3983">בית
אלעזרי</option>
<option value="3474">הוד
השרון</option>
<option value="3962">עדנים</option>
<option value="3963">אלישמע</option>
<option value="3964">נווה
ירק</option>
<option value="3965">ירקונה</option>
<option value="3966">גני עם</option>
<option value="3985">שדי
חמד</option>
<option value="223">אלון
שבות</option>
<option value="226">אלעזר</option>
<option value="247">בת עין</option>
<option value="249">גבעות</option>
<option value="262">הר
גילה</option>
<option value="284">כפר
אלדד</option>
<option value="287">כפר
עציון</option>
<option value="288">כרמי
צור</option>
<option value="294">מגדל
עוז</option>
<option value="308">מעלה
עמוס</option>
<option value="309">מעלה
רחבעם</option>
<option value="329">נוקדים
- אל דוד</option>
<option value="357">פני
קדם</option>
<option value="370">ראש
צורים</option>
<option value="393">תקוע</option>
<option value="1215">נווה
דניאל</option>
<option value="1229">נוקדים</option>
<option value="1407">קדר</option>
<option value="3880">מצד</option>
<option value="3881">שדה
בועז</option>
<option value="3969">חרמלה</option>
<option value="89">בת חפר</option>
<option value="394">בית
הלוי</option>
<option value="600">אביחיל</option>
<option value="632">אחיטוב</option>
<option value="656">אלישיב</option>
<option value="689">בארותיים</option>
<option value="694">בורגתה</option>
<option value="695">בחן</option>
<option value="717">בית
חרות</option>
<option value="721">בית
ינאי</option>
<option value="772">גאולי
תימן</option>
<option value="782">גבעת
חיים איחוד</option>
<option value="790">גבעת
שפירא</option>
<option value="818">גן
יאשיה</option>
<option value="861">הדר עם</option>
<option value="869">המעפיל</option>
<option value="871">העוגן</option>
<option value="889">חבצלת
השרון</option>
<option value="896">חגלה</option>
<option value="902">חופית</option>
<option value="908">חיבת
ציון</option>
<option value="914">חניאל</option>
<option value="927">חרב
לאת</option>
<option value="950">יד חנה</option>
<option value="1018">כפר
הרא''ה</option>
<option value="1030">כפר
ויתקין</option>
<option value="1037">כפר
חיים</option>
<option value="1047">כפר
מונש</option>
<option value="1136">מכמורת</option>
<option value="1155">מעברות</option>
<option value="1195">משמר
השרון</option>
<option value="1302">עולש</option>
<option value="1322">עין
החורש</option>
<option value="1392">צוקי
ים</option>
<option value="1494">שושנת
העמקים</option>
<option value="1578">בת חן</option>
<option value="1715">אומץ</option>
<option value="1766">בית
יצחק שער חפר</option>
<option value="1767">ביתן
אהרן</option>
<option value="3109">כפר
ידידיה</option>
<option value="3585">גבעת
חיים מאוחד</option>
<option value="3882">בית
חזון</option>
</select>
</div>
<div class="col-sm-6">
<input id="registrationAddressStreet1" type="text" value="" placeholder="רחוב ומספר">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="registrationAddressZip1" type="text" value="" placeholder="מיקוד">
</div>
</div>
</div>
<div id="payment2">
<input id="payment-checkbox-2" type="checkbox" value="payment"><label>תשלום מס' 2</label><label id="payment-name-2"></label><abbr class="nadlan-tooltip" title="נא הסר את ה V במידה ואינך מעוניין כי תצא חשבונית על מבקר זה." rel="tooltip"> ? </abbr><br>
<label>פרטי תשלום</label><br>
<div class="row">
<div class="col-sm-6">
<input id="invoiceN2" type="text" value="" placeholder="שם העסק להפקת חשבונית">
</div>
<div class="col-sm-6">
<input id="registrationNo2" type="text" value="" placeholder=" מס עוסק מורשה / ח.פ">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="registrationAddress2" type="text" value="" placeholder="עיר רחוב ומספר">
</div>
<div class="col-sm-6">
<input id="amount2" type="text" value="" placeholder="סכום לתשלום">
</div>
</div>
</div>
<div id="payment3">
<input id="payment-checkbox-3" type="checkbox" value="payment"> <label>תשלום מס' 3</label><label id="payment-name-3"></label><abbr class="nadlan-tooltip" title="נא הסר את ה V במידה ואינך מעוניין כי תצא חשבונית על מבקר זה." rel="tooltip"> ? </abbr><br>
<label>פרטי תשלום</label><br>
<div class="row">
<div class="col-sm-6">
<input id="invoiceN3" type="text" value="" placeholder="שם העסק להפקת חשבונית">
</div>
<div class="col-sm-6">
<input id="registrationNo3" type="text" value="" placeholder=" מס עוסק מורשה / ח.פ">
</div>
</div>
<div class="row">
<div class="col-sm-6">
<input id="registrationAddress3" type="text" value="" placeholder="עיר רחוב ומספר">
</div>
<div class="col-sm-6">
<input id="amount3" type="text" value="" placeholder="סכום לתשלום">
</div>
</div>
</div>
<div id="register-paypment-area">
<!--<div class="row">
<div class="col-sm-11">
<input id="content" type="checkbox" value="content" checked>
<label>אני מעוניין לקבל תוכן פרסומי ממרכז הבנייה הישראלי </label><br>
</div>
</div>-->
<div class="row">
<div class="col-sm-11">
<input id="terms-of-use" type="checkbox" value="terms">
<label>קראתי, הבנתי ואני מסכים/ה </label>
<a href="<?php echo home_url( '/' ); ?>wp-content/themes/Tyler/siteRules_2015.pdf" target="_blank"> לתקנון האתר </a><a href="<?php echo home_url( '/' ); ?>wp-content/themes/Tyler/nadlanCityRules_2015.pdf" target="_blank">ולתקנון עיר הנדל"ן</a><br>
<label>ניתן לבטל את ההזמנה עד ה- 14 לאוקטובר בחיוב של 750 ש"ח בתוספת מע"מ למשתתף</label><br>
<label>ביטול לאחר ה-14 לאוקטובר יחוייב בדמי ביטול מלאים.</label>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<button id="siugnUp" class="btn btn-secondary">הרשם ושלם באמצעות נציג</button>
</div>
<div class="col-sm-6">
<button id="siugnUpWithPay" class="btn btn-secondary">השלם הרשמה באמצעות אשראי</button>
<!--<label id="discount-text">הרשמה באשראי דרך האתר מקנה 5% הנחה</label>-->
</div>
<!--<div class="col-sm-6">
<button id="siugnUp" class="btn btn-secondary">הרשם ושלם באמצעות נציג</button>
</div-->
<form></form>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="formPay">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value=" treut-facilitator@cambium.co.il" />
<input type="hidden" name="charset" value="utf-8">
<input type="hidden" name="item_name" value="עיר הנדלן" />
<input type="hidden" name="item_number" value="123" />
<input type="hidden" name="currency_code" value="ILS" />
<input type="hidden" name="amount" value="100" />
<input type="hidden" name="return" value="http://nadlancity.cambium-team.com/?page_id=48/#done" />
<input type="hidden" name="notify_url" value="http://nadlancity.cambium-team.com/?page_id=310" />
<input type="hidden" name="cancel_return" value="http://nadlancity.cambium-team.com/?page_id=48/#cancel" /> <br />
<!--<input type="image" name="submit" border="0"
src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif"
alt="PayPal - The safer, easier way to pay online">-->
</form>
</div>
</div>
</div>
<!--</div>-->
</form>
</div>
<?php endwhile; // end of the loop. ?>
<?php get_footer();?> | DavidSalzer/ArchitectureConvension | wp-content/themes/Tyler/registerForm_a_2015.php | PHP | gpl-2.0 | 133,811 |
<?php
/**
* @package hubzero-cms
* @copyright Copyright (c) 2005-2020 The Regents of the University of California.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Forum\Api\Controllers;
use Hubzero\Component\ApiController;
use Components\Forum\Models\UsersCategory;
use Request;
use User;
require_once dirname(dirname(__DIR__)) . '/models/usersCategory.php';
class UsersCategoriesv2_0 extends ApiController
{
/**
* Create user's categories
*
* @apiMethod POST
* @apiUri /api/v2.0/forum/userscategories/create
* @apiParameter {
* "name": "category_id",
* "description": "Forum category's ID",
* "type": "integer",
* "required": true
* }
* @apiParameter {
* "name": "user_id",
* "description": "User's ID",
* "type": "integer",
* "required": true
* }
* @return TODO
*/
public function createTask()
{
$userId = Request::getInt('userId');
$currentUserId = User::get('id');
$this->_requiresMatchingUser($currentUserId, $userId);
$categoriesIds = Request::getArray('categoriesIds');
$usersCategories = $this->_instantiateUsersCategories($categoriesIds, $currentUserId);
$errors = $this->_saveUsersCategories($usersCategories);
$arrayCategories = array_map(function($usersCategory) {
return $usersCategory->toArray();
}, $usersCategories);
$result = array(
'records' => $arrayCategories,
'errors' => $errors
);
$result['status'] = empty($errors) ? 'success' : 'error';
$this->send($result);
}
/**
* Instantiate user's categories
*
* @param array $categoriesIds
* @param integer $currentUserId
* @return array
*/
protected function _instantiateUsersCategories($categoriesIds, $currentUserId)
{
$usersCategories = array_map(function($categoryId) use ($currentUserId) {
$usersCategory = UsersCategory::blank();
$usersCategory->set(array(
'category_id' => $categoryId,
'user_id' => $currentUserId
));
return $usersCategory;
}, $categoriesIds);
return $usersCategories;
}
/**
* Save user's categories
*
* @param array $usersCategories
* @return array
*/
protected function _saveUsersCategories($usersCategories)
{
$errors = array();
foreach ($usersCategories as $usersCategory)
{
if (!$usersCategory->save())
{
$instanceErrors = $usersCategory->getErrors();
array_push($errors, $instanceErrors);
}
}
return $errors;
}
/**
* Destroys user's categories
*
* @apiMethod DELETE
* @apiUri /api/v2.0/forum/userscategories/destroy
* @apiParameter {
* "name": "category_id",
* "description": "Forum category's ID",
* "type": "integer",
* "required": true
* }
* @apiParameter {
* "name": "user_id",
* "description": "User's ID",
* "type": "integer",
* "required": true
* }
* @return TODO
*/
public function destroyTask()
{
$userId = Request::getInt('userId');
$currentUserId = User::get('id');
$this->_requiresMatchingUser($currentUserId, $userId);
$categoriesIds = Request::getArray('categoriesIds');
$usersCategories = UsersCategory::all()
->whereEquals('user_id', $userId)
->whereIn('category_id', $categoriesIds);
$errors = $this->_destroyUsersCategories($usersCategories);
$arrayCategories = $usersCategories->rows()->toArray();
$result = array(
'records' => $arrayCategories,
'errors' => $errors
);
$result['status'] = empty($errors) ? 'success' : 'error';
$this->send($result);
}
/**
* Destroy user's categories
*
* @param array $usersCategories
* @return array
*/
protected function _destroyUsersCategories($usersCategories)
{
$errors = array();
foreach ($usersCategories as $usersCategory)
{
if (!$usersCategory->destroy())
{
$instanceErrors = $usersCategory->getErrors();
array_push($errors, $instanceErrors);
}
}
return $errors;
}
/**
* Check user's id
*
* @param integer $currentUserId
* @param integer $userId
* @return void
*/
protected function _requiresMatchingUser($currentUserId, $userId)
{
if ($currentUserId !== $userId)
{
$error = array(
'status' => 'error',
'error' => 'User ID mismatch, unable to proceed.'
);
$this->send($result);
}
}
}
| hubzero/hubzero-cms | core/components/com_forum/api/controllers/userscategoriesv2_0.php | PHP | gpl-2.0 | 4,385 |
@extends('layout')
@section('content')
<ol class="breadcrumb">
<li><a href="{{ URL::to('/') }}">Home</a></li>
<li><a href="{{ URL::to('/projects') }}">Projects</a></li>
</ol>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
@if(!Request::get('q'))
<h3>All Projects</h3>
<p class="main-description">Here you'll find a list of all available projects. You can use the filters on the right-hand side to filter or search for a specific project.</p>
@else
<h3>Projects</h3>
<p>This is a list of {{$projects->getTotal()}} project(s) that contain the following search term: <strong>{{Request::get('q')}}</strong></p>
@endif
<hr/>
<form role="search">
<div class="input-group">
{{ Form::input('search', 'q', Request::get('q'), ['placeholder' => 'Search', 'class' => 'form-control']) }}
<span class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</span>
</div>
</form>
<br/>
@foreach ($projects as $project)
@include('projects.partials.projectListItem')
@endforeach
@if ($projects->getTotal() == 0)
<div class="alert alert-warning">
<p><strong>Whoops. It looks like this returned no results.</strong>
<p>You can try again by adjusting the filters or your search query.</p>
</div>
@endif
{{ $projects->appends(Request::except('page'))->links() }}
</div>
</div>
<script src="{{ URL::asset('libs/jquery.highlight/jquery.highlight-4.js') }}"></script>
<script>
$(document).ready(function() {
$('.chosen').chosen();
});
$('.searchable').highlight('{{ Request::get('q') }}');
$('.license-clickable').popover();
$("[data-toggle='tooltip']").tooltip();
</script>
@stop | nicoverbruggen/openshowcase | app/views/projects/index.blade.php | PHP | gpl-2.0 | 1,949 |
<?php
include('addtopbox.php');
include('settings.php');
function pcamp_widgets_init() {
register_sidebar( array(
'name' => __( 'Artikelübersicht-Sidebar', 'pcamp' ),
'id' => 'sidebar-side',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => "</aside>",
'before_title' => '<div class="widget-title">',
'after_title' => '</div>',
) );
register_sidebar( array(
'name' => __( 'Einzelartikel-Sidebar', 'pcamp' ),
'id' => 'sidebar-single',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => "</aside>",
'before_title' => '<div class="widget-title">',
'after_title' => '</div>',
) );
$args = array(
'parent' => 0,
'post_type' => 'page'
);
$tlpages = get_pages( $args );
if (is_array($tlpages) && (count($tlpages) > 0)) {
foreach ($tlpages as $tlpage) {
$subp = get_pages('child_of='.$tlpage->ID);
if (is_array($subp) && (count($subp) > 0)) {
register_sidebar( array(
'name' => __( 'Seitengruppe: '.$tlpage->post_title, 'pcamp' ),
'id' => 'sidebar-pagegroup-'.$tlpage->ID,
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => "</aside>",
'before_title' => '<div class="widget-title">',
'after_title' => '</div>',
) );
}
}
}
}
function register_my_menus() {
register_nav_menus(
array(
'mainmenu' => __( 'Hauptmenu' ),
'footermenu' => __( 'Footermenu' )
)
);
}
function pcamp_sidebar( $atts, $content="" ) {
global $PCAMP_SIDEBAR;
global $PCAMP_SIDEBAR_AFTER;
if (isset($atts['title'])) $array['title'] = $atts['title'];
$array['content'] = $content;
if (($atts[0] == "after")) $PCAMP_SIDEBAR_AFTER[] = $array; else $PCAMP_SIDEBAR[] = $array;
return "";
}
function breakpart() {
return "</div><div class=\"part\">";
}
add_shortcode( 'pcamp-sidebar', 'pcamp_sidebar' );
add_shortcode( 'breakpart', 'breakpart' );
add_action( 'widgets_init', 'pcamp_widgets_init' );
add_action( 'init', 'register_my_menus' );
add_filter('widget_text', 'do_shortcode');
add_theme_support('post-thumbnails');
add_image_size( 'banner', 1024, 200, true);
$args = array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption'
);
add_theme_support( 'html5', $args );
add_filter( 'the_content_more_link', 'modify_read_more_link' );
function modify_read_more_link() {
return '<a class="more-link" href="' . get_permalink() . '">weiterlesen...</a>';
}
class pcamp_Nav_Menu extends Walker_Nav_Menu {
/**
* @see Walker::start_el()
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param int $current_page Menu item ID.
* @param object $args
*/
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
$class_names = ' class="' . esc_attr( $class_names ) . '"';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
// new addition for active class on the a tag
if(in_array('current-menu-item', $classes)) {
$attributes .= ' class="active"';
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'><span>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</span></a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
/**
* Starts the list before the elements are added.
*
* @see Walker::start_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<div class=\"lvl\"><ul class=\"submenu\">\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul></div>\n";
}
}
function pcamp_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment;
extract($args, EXTR_SKIP);
if ( 'div' == $args['style'] ) {
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$add_below = 'div-comment';
}
?>
<<?php echo $tag ?> <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ) ?> id="comment-<?php comment_ID() ?>">
<?php if ( 'div' != $args['style'] ) : ?>
<div id="div-comment-<?php comment_ID() ?>" class="comment-body">
<?php endif; ?>
<div class="comment-author vcard">
<?php if ($depth > 1) { ?>
<?php printf( __( '<cite class="fn">%s</cite> <span class="says">antwortete am</span>' ), get_comment_author_link() ); ?>
<?php } else { ?>
<?php printf( __( '<cite class="fn">%s</cite> <span class="says">schrieb am</span>' ), get_comment_author_link() ); ?>
<?php } ?>
<?php
/* translators: 1: date, 2: time */
printf( __('%1$s at %2$s'), get_comment_date(), get_comment_time() ); ?>: <?php comment_reply_link( array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'], 'reply_text' => "(Antworten)" ) ) ); ?><?php edit_comment_link( __( '(Edit)' ), ' ', '' );
?>
</div>
<?php if ( $comment->comment_approved == '0' ) : ?>
<em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></em>
<br />
<?php endif; ?>
<?php comment_text(); ?>
<!--<div class="reply">
<?php comment_reply_link( array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
</div>-->
<?php if ( 'div' != $args['style'] ) : ?>
</div>
<?php endif; ?>
<?php
}
if(function_exists("register_field_group"))
{
register_field_group(array (
'id' => 'acf_steckbrief',
'title' => 'Steckbrief',
'fields' => array (
array (
'key' => 'field_5159329a6f885',
'label' => 'desc',
'name' => 'desc',
'type' => 'message',
'message' => 'Wenn Name und Bild angegeben sind, wird neben dem Artikel ein Steckbrief angezeigt. Alternativ kann der Steckbrief des Post-Autoren angezeigt werden (rechts unter "Autor-Sichtbarkeit")',
),
array (
'key' => 'field_5159319f55ff7',
'label' => 'Name des Autors',
'name' => 'text',
'type' => 'text',
'default_value' => '',
'formatting' => 'html',
),
array (
'key' => 'field_5159316655ff6',
'label' => 'Bild des Autors',
'name' => 'image_url',
'type' => 'image',
'save_format' => 'id',
'preview_size' => 'thumbnail',
),
array (
'key' => 'field_515931d755ff9',
'label' => 'Link',
'name' => 'link',
'type' => 'text',
'instructions' => 'Wenn angeben, wird die komplette Steckbrief-Box verlinkt.',
'default_value' => '',
'formatting' => 'none',
),
),
'location' => array (
'rules' => array (
array (
'param' => 'post_type',
'operator' => '==',
'value' => 'post',
'order_no' => 0,
),
),
'allorany' => 'all',
),
'options' => array (
'position' => 'normal',
'layout' => 'default',
'hide_on_screen' => array (
),
),
'menu_order' => 0,
));
}
add_action('acf/input/admin_head', 'my_acf_input_admin_head');
function my_acf_input_admin_head() {
?>
<script type="text/javascript">
jQuery(function(){
jQuery('.acf_postbox').addClass('closed');
});
</script>
<?php
}
function get_theme_dir() {
$url = get_bloginfo('template_url');
return parse_url($url, PHP_URL_PATH);
}
?>
| stoppegp/wptheme-pcamp | functions.php | PHP | gpl-2.0 | 9,167 |
package project.devices;
public abstract class Device {
protected String name;
public Device(String name){
this.name = name;
}
public String getName(){
return name;
}
}
| ireyoner/SensorDataAquisitor | src/project/devices/Device.java | Java | gpl-2.0 | 193 |
/**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files, and the ! prefix for excluding files.)
*/
// Path to public folder
var tmpPath = '.tmp/public/';
// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
// to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
'styles/bootstrap.min.css',
'styles/bootstrap-theme.css'
];
// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
// Load sails.io before everything else
'js/dependencies/sails.io.js',
'js/dependencies/angular.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/jquery.min.js',
'js/dependencies/bootstrap.min.js',
'js/dependencies/ui-bootstrap.min.js',
'js/dependencies/ui-bootstrap-tpls.min.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/smart-table.min.js',
'js/app.js'
// Dependencies like jQuery, or Angular are brought in here
// All of the rest of your client-side js files
// will be injected here in no particular order.
// Use the "exclude" operator to ignore files
// '!js/ignore/these/files/*.js'
];
// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you. If you want to use jade, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file. Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks.
var templateFilesToInject = [
'templates/**/*.html'
];
// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(transformPath);
module.exports.jsFilesToInject = jsFilesToInject.map(transformPath);
module.exports.templateFilesToInject = templateFilesToInject.map(transformPath);
// Transform paths relative to the "assets" folder to be relative to the public
// folder, preserving "exclude" operators.
function transformPath(path) {
return (path.substring(0,1) == '!') ? ('!' + tmpPath + path.substring(1)) : (tmpPath + path);
}
| libteiwm/FedShare | tasks/pipeline.js | JavaScript | gpl-2.0 | 2,692 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Martin Jansen <mj@php.net> |
// | Tomas V.V.Cox <cox@idecnet.com> |
// | Jan Lehnardt <jan@php.net> |
// | Kai Schrder <k.schroeder@php.net> |
// | Craig Constantine <cconstantine@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: Ping.php,v 1.50 2009/01/27 20:14:00 cconstantine Exp $
require_once "PEAR.php";
require_once "OS/Guess.php";
define('NET_PING_FAILED_MSG', 'execution of ping failed' );
define('NET_PING_HOST_NOT_FOUND_MSG', 'unknown host' );
define('NET_PING_INVALID_ARGUMENTS_MSG', 'invalid argument array' );
define('NET_PING_CANT_LOCATE_PING_BINARY_MSG', 'unable to locate the ping binary');
define('NET_PING_RESULT_UNSUPPORTED_BACKEND_MSG', 'Backend not Supported' );
define('NET_PING_FAILED', 0);
define('NET_PING_HOST_NOT_FOUND', 1);
define('NET_PING_INVALID_ARGUMENTS', 2);
define('NET_PING_CANT_LOCATE_PING_BINARY', 3);
define('NET_PING_RESULT_UNSUPPORTED_BACKEND', 4);
/**
* Wrapper class for ping calls
*
* Usage:
*
* <?php
* require_once "Net/Ping.php";
* $ping = Net_Ping::factory();
* if(PEAR::isError($ping)) {
* echo $ping->getMessage();
* } else {
* $ping->setArgs(array('count' => 2));
* var_dump($ping->ping('example.com'));
* }
* ?>
*
* @author Jan Lehnardt <jan@php.net>
* @version $Revision: 1.50 $
* @package Net
* @access public
*/
class Net_Ping
{
/**
* Location where the ping program is stored
*
* @var string
* @access private
*/
var $_ping_path = "";
/**
* Array with the result from the ping execution
*
* @var array
* @access private
*/
var $_result = array();
/**
* OS_Guess instance
*
* @var object
* @access private
*/
var $_OS_Guess = "";
/**
* OS_Guess->getSysname result
*
* @var string
* @access private
*/
var $_sysname = "";
/**
* Ping command arguments
*
* @var array
* @access private
*/
var $_args = array();
/**
* Indicates if an empty array was given to setArgs
*
* @var boolean
* @access private
*/
var $_noArgs = true;
/**
* Contains the argument->option relation
*
* @var array
* @access private
*/
var $_argRelation = array();
/**
* Constructor for the Class
*
* @access private
*/
function Net_Ping($ping_path, $sysname)
{
$this->_ping_path = $ping_path;
$this->_sysname = $sysname;
$this->_initArgRelation();
} /* function Net_Ping() */
/**
* Factory for Net_Ping
*
* @access public
*/
function factory()
{
$ping_path = '';
$sysname = Net_Ping::_setSystemName();
if (($ping_path = Net_Ping::_setPingPath($sysname)) == NET_PING_CANT_LOCATE_PING_BINARY) {
return PEAR::raiseError(NET_PING_CANT_LOCATE_PING_BINARY_MSG, NET_PING_CANT_LOCATE_PING_BINARY);
} else {
return new Net_Ping($ping_path, $sysname);
}
} /* function factory() */
/**
* Resolve the system name
*
* @access private
*/
function _setSystemName()
{
$OS_Guess = new OS_Guess;
$sysname = $OS_Guess->getSysname();
// Refine the sysname for different Linux bundles/vendors. (This
// should go away if OS_Guess was ever extended to give vendor
// and vendor-version guesses.)
//
// Bear in mind that $sysname is eventually used to craft a
// method name to figure out which backend gets used to parse
// the ping output. Elsewhere, we'll set $sysname back before
// that.
if ('linux' == $sysname) {
if ( file_exists('/etc/lsb-release')
&& false !== ($release=@file_get_contents('/etc/lsb-release'))
&& preg_match('/gutsy/i', $release)
) {
$sysname = 'linuxredhat9';
}
else if ( file_exists('/etc/debian_version') ) {
$sysname = 'linuxdebian';
}else if (file_exists('/etc/redhat-release')
&& false !== ($release= @file_get_contents('/etc/redhat-release'))
)
{
if (preg_match('/release 8/i', $release)) {
$sysname = 'linuxredhat8';
}elseif (preg_match('/release 9/i', $release)) {
$sysname = 'linuxredhat9';
}
}
}
return $sysname;
} /* function _setSystemName */
/**
* Set the arguments array
*
* @param array $args Hash with options
* @return mixed true or PEAR_error
* @access public
*/
function setArgs($args)
{
if (!is_array($args)) {
return PEAR::raiseError(NET_PING_INVALID_ARGUMENTS_MSG, NET_PING_INVALID_ARGUMENTS);
}
$this->_setNoArgs($args);
$this->_args = $args;
return true;
} /* function setArgs() */
/**
* Set the noArgs flag
*
* @param array $args Hash with options
* @return void
* @access private
*/
function _setNoArgs($args)
{
if (0 == count($args)) {
$this->_noArgs = true;
} else {
$this->_noArgs = false;
}
} /* function _setNoArgs() */
/**
* Sets the system's path to the ping binary
*
* @access private
*/
function _setPingPath($sysname)
{
$status = '';
$output = array();
$ping_path = '';
if ("windows" == $sysname) {
return "ping";
} else {
$ping_path = exec("which ping", $output, $status);
if (0 != $status) {
return NET_PING_CANT_LOCATE_PING_BINARY;
} else {
// be certain "which" did what we expect. (ref bug #12791)
if ( is_executable($ping_path) ) {
return $ping_path;
}
else {
return NET_PING_CANT_LOCATE_PING_BINARY;
}
}
}
} /* function _setPingPath() */
/**
* Creates the argument list according to platform differences
*
* @return string Argument line
* @access private
*/
function _createArgList()
{
$retval = array();
$timeout = "";
$iface = "";
$ttl = "";
$count = "";
$quiet = "";
$size = "";
$seq = "";
$deadline = "";
foreach($this->_args AS $option => $value) {
if(!empty($option) && isset($this->_argRelation[$this->_sysname][$option]) && NULL != $this->_argRelation[$this->_sysname][$option]) {
${$option} = $this->_argRelation[$this->_sysname][$option]." ".$value." ";
}
}
switch($this->_sysname) {
case "sunos":
if ($size || $count || $iface) {
/* $size and $count must be _both_ defined */
$seq = " -s ";
if ($size == "") {
$size = " 56 ";
}
if ($count == "") {
$count = " 5 ";
}
}
$retval['pre'] = $iface.$seq.$ttl;
$retval['post'] = $size.$count;
break;
case "freebsd":
$retval['pre'] = $quiet.$count.$ttl.$timeout;
$retval['post'] = "";
break;
case "darwin":
$retval['pre'] = $count.$timeout.$size;
$retval['post'] = "";
break;
case "netbsd":
$retval['pre'] = $quiet.$count.$iface.$size.$ttl.$timeout;
$retval['post'] = "";
break;
case "openbsd":
$retval['pre'] = $quiet.$count.$iface.$size.$ttl.$timeout;
$retval['post'] = "";
break;
case "linux":
$retval['pre'] = $quiet.$deadline.$count.$ttl.$size.$timeout;
$retval['post'] = "";
break;
case "linuxdebian":
$retval['pre'] = $quiet.$count.$ttl.$size.$timeout;
$retval['post'] = "";
$this->_sysname = 'linux'; // undo linux vendor refinement hack
break;
case "linuxredhat8":
$retval['pre'] = $iface.$ttl.$count.$quiet.$size.$deadline;
$retval['post'] = "";
$this->_sysname = 'linux'; // undo linux vendor refinement hack
break;
case "linuxredhat9":
$retval['pre'] = $timeout.$iface.$ttl.$count.$quiet.$size.$deadline;
$retval['post'] = "";
$this->_sysname = 'linux'; // undo linux vendor refinement hack
break;
case "windows":
$retval['pre'] = $count.$ttl.$timeout;
$retval['post'] = "";
break;
case "hpux":
$retval['pre'] = $ttl;
$retval['post'] = $size.$count;
break;
case "aix":
$retval['pre'] = $count.$timeout.$ttl.$size;
$retval['post'] = "";
break;
default:
$retval['pre'] = "";
$retval['post'] = "";
break;
}
return($retval);
} /* function _createArgList() */
/**
* Execute ping
*
* @param string $host hostname
* @return mixed String on error or array with the result
* @access public
*/
function ping($host)
{
if($this->_noArgs) {
$this->setArgs(array('count' => 3));
}
$argList = $this->_createArgList();
$cmd = $this->_ping_path." ".$argList['pre']." ".$host." ".$argList['post'];
// since we return a new instance of Net_Ping_Result (on
// success), users may call the ping() method repeatedly to
// perform unrelated ping tests Make sure we don't have raw data
// from a previous call laying in the _result array.
$this->_result = array();
exec($cmd, $this->_result);
if (!is_array($this->_result)) {
return PEAR::raiseError(NET_PING_FAILED_MSG, NET_PING_FAILED);
}
if (count($this->_result) == 0) {
return PEAR::raiseError(NET_PING_HOST_NOT_FOUND_MSG, NET_PING_HOST_NOT_FOUND);
}
else {
// Here we pass $this->_sysname to the factory(), but it is
// not actually used by the class. It's only maintained in
// the Net_Ping_Result class because the
// Net_Ping_Result::getSysName() method needs to be retained
// for backwards compatibility.
return Net_Ping_Result::factory($this->_result, $this->_sysname);
}
} /* function ping() */
/**
* Check if a host is up by pinging it
*
* @param string $host The host to test
* @param bool $severely If some of the packages did reach the host
* and severely is false the function will return true
* @return bool True on success or false otherwise
*
*/
function checkHost($host, $severely = true)
{
$matches = array();
$this->setArgs(array("count" => 10,
"size" => 32,
"quiet" => null,
"deadline" => 10
)
);
$res = $this->ping($host);
if (PEAR::isError($res)) {
return false;
}
if ($res->_received == 0) {
return false;
}
if ($res->_received != $res->_transmitted && $severely) {
return false;
}
return true;
} /* function checkHost() */
/**
* Output errors with PHP trigger_error(). You can silence the errors
* with prefixing a "@" sign to the function call: @Net_Ping::ping(..);
*
* @param mixed $error a PEAR error or a string with the error message
* @return bool false
* @access private
* @author Kai Schrder <k.schroeder@php.net>
*/
function _raiseError($error)
{
if (PEAR::isError($error)) {
$error = $error->getMessage();
}
trigger_error($error, E_USER_WARNING);
return false;
} /* function _raiseError() */
/**
* Creates the argument list according to platform differences
*
* @return string Argument line
* @access private
*/
function _initArgRelation()
{
$this->_argRelation["sunos"] = array(
"timeout" => NULL,
"ttl" => "-t",
"count" => " ",
"quiet" => "-q",
"size" => " ",
"iface" => "-i"
);
$this->_argRelation["freebsd"] = array (
"timeout" => "-t",
"ttl" => "-m",
"count" => "-c",
"quiet" => "-q",
"size" => NULL,
"iface" => NULL
);
$this->_argRelation["netbsd"] = array (
"timeout" => "-w",
"iface" => "-I",
"ttl" => "-T",
"count" => "-c",
"quiet" => "-q",
"size" => "-s"
);
$this->_argRelation["openbsd"] = array (
"timeout" => "-w",
"iface" => "-I",
"ttl" => "-t",
"count" => "-c",
"quiet" => "-q",
"size" => "-s"
);
$this->_argRelation["darwin"] = array (
"timeout" => "-t",
"iface" => NULL,
"ttl" => NULL,
"count" => "-c",
"quiet" => "-q",
"size" => NULL
);
$this->_argRelation["linux"] = array (
"timeout" => "-W",
"iface" => NULL,
"ttl" => "-t",
"count" => "-c",
"quiet" => "-q",
"size" => "-s",
"deadline" => "-w"
);
$this->_argRelation["linuxdebian"] = array (
"timeout" => "-W",
"iface" => NULL,
"ttl" => "-t",
"count" => "-c",
"quiet" => "-q",
"size" => "-s",
"deadline" => "-w",
);
$this->_argRelation["linuxredhat8"] = array (
"timeout" => NULL,
"iface" => "-I",
"ttl" => "-t",
"count" => "-c",
"quiet" => "-q",
"size" => "-s",
"deadline" => "-w"
);
$this->_argRelation["linuxredhat9"] = array (
"timeout" => "-W",
"iface" => "-I",
"ttl" => "-t",
"count" => "-c",
"quiet" => "-q",
"size" => "-s",
"deadline" => "-w"
);
$this->_argRelation["windows"] = array (
"timeout" => "-w",
"iface" => NULL,
"ttl" => "-i",
"count" => "-n",
"quiet" => NULL,
"size" => "-l"
);
$this->_argRelation["hpux"] = array (
"timeout" => NULL,
"iface" => NULL,
"ttl" => "-t",
"count" => "-n",
"quiet" => NULL,
"size" => " "
);
$this->_argRelation["aix"] = array (
"timeout" => "-i",
"iface" => NULL,
"ttl" => "-T",
"count" => "-c",
"quiet" => NULL,
"size" => "-s"
);
} /* function _initArgRelation() */
} /* class Net_Ping */
/**
* Container class for Net_Ping results
*
* @author Jan Lehnardt <jan@php.net>
* @version $Revision: 1.50 $
* @package Net
* @access private
*/
class Net_Ping_Result
{
/**
* ICMP sequence number and associated time in ms
*
* @var array
* @access private
*/
var $_icmp_sequence = array(); /* array($sequence_number => $time ) */
/**
* The target's IP Address
*
* @var string
* @access private
*/
var $_target_ip;
/**
* Number of bytes that are sent with each ICMP request
*
* @var int
* @access private
*/
var $_bytes_per_request;
/**
* The total number of bytes that are sent with all ICMP requests
*
* @var int
* @access private
*/
var $_bytes_total;
/**
* The ICMP request's TTL
*
* @var int
* @access private
*/
var $_ttl;
/**
* The raw Net_Ping::result
*
* @var array
* @access private
*/
var $_raw_data = array();
/**
* The Net_Ping::_sysname
*
* @var int
* @access private
*/
var $_sysname;
/**
* Statistical information about the ping
*
* @var int
* @access private
*/
var $_round_trip = array(); /* array('min' => xxx, 'avg' => yyy, 'max' => zzz) */
/**
* Constructor for the Class
*
* @access private
*/
function Net_Ping_Result($result, $sysname)
{
$this->_raw_data = $result;
// The _sysname property is no longer used by Net_Ping_result.
// The property remains for backwards compatibility so the
// getSystemName() method continues to work.
$this->_sysname = $sysname;
$this->_parseResult();
} /* function Net_Ping_Result() */
/**
* Factory for Net_Ping_Result
*
* @access public
* @param array $result Net_Ping result
* @param string $sysname OS_Guess::sysname
*/
function factory($result, $sysname)
{
return new Net_Ping_Result($result, $sysname);
} /* function factory() */
/**
* Parses the raw output from the ping utility.
*
* @access private
*/
function _parseResult()
{
// MAINTAINERS:
//
// If you're in this class fixing or extending the parser
// please add another file in the 'tests/test_parser_data/'
// directory which exemplafies the problem. And of course
// you'll want to run the 'tests/test_parser.php' (which
// contains easy how-to instructions) to make sure you haven't
// broken any existing behaviour.
// operate on a copy of the raw output since we're going to modify it
$data = $this->_raw_data;
// remove leading and trailing blank lines from output
$this->_parseResultTrimLines($data);
// separate the output into upper and lower portions,
// and trim those portions
$this->_parseResultSeparateParts($data, $upper, $lower);
$this->_parseResultTrimLines($upper);
$this->_parseResultTrimLines($lower);
// extract various things from the ping output . . .
$this->_target_ip = $this->_parseResultDetailTargetIp($upper);
$this->_bytes_per_request = $this->_parseResultDetailBytesPerRequest($upper);
$this->_ttl = $this->_parseResultDetailTtl($upper);
$this->_icmp_sequence = $this->_parseResultDetailIcmpSequence($upper);
$this->_round_trip = $this->_parseResultDetailRoundTrip($lower);
$this->_parseResultDetailTransmitted($lower);
$this->_parseResultDetailReceived($lower);
$this->_parseResultDetailLoss($lower);
if ( isset($this->_transmitted) ) {
$this->_bytes_total = $this->_transmitted * $this->_bytes_per_request;
}
} /* function _parseResult() */
/**
* determinces the number of bytes sent by ping per ICMP ECHO
*
* @access private
*/
function _parseResultDetailBytesPerRequest($upper)
{
// The ICMP ECHO REQUEST and REPLY packets should be the same
// size. So we can also find what we want in the output for any
// succesful ICMP reply which ping printed.
for ( $i=1; $i<count($upper); $i++ ) {
// anything like "64 bytes " at the front of any line in $upper??
if ( preg_match('/^\s*(\d+)\s*bytes/i', $upper[$i], $matches) ) {
return( (int)$matches[1] );
}
// anything like "bytes=64" in any line in the buffer??
if ( preg_match('/bytes=(\d+)/i', $upper[$i], $matches) ) {
return( (int)$matches[1] );
}
}
// Some flavors of ping give two numbers, as in "n(m) bytes", on
// the first line. We'll take the first number and add 8 for the
// 8 bytes of header and such in an ICMP ECHO REQUEST.
if ( preg_match('/(\d+)\(\d+\)\D+$/', $upper[0], $matches) ) {
return( (int)(8+$matches[1]) );
}
// Ok we'll just take the rightmost number on the first line. It
// could be "bytes of data" or "whole packet size". But to
// distinguish would require language-specific patterns. Most
// ping flavors just put the number of data (ie, payload) bytes
// if they don't specify both numbers as n(m). So we add 8 bytes
// for the ICMP headers.
if ( preg_match('/(\d+)\D+$/', $upper[0], $matches) ) {
return( (int)(8+$matches[1]) );
}
// then we have no idea...
return( NULL );
}
/**
* determines the round trip time (RTT) in milliseconds for each
* ICMP ECHO which returned. Note that the array is keyed with the
* sequence number of each packet; If any packets are lost, the
* corresponding sequence number will not be found in the array keys.
*
* @access private
*/
function _parseResultDetailIcmpSequence($upper)
{
// There is a great deal of variation in the per-packet output
// from various flavors of ping. There are language variations
// (time=, rtt=, zeit=, etc), field order variations, and some
// don't even generate sequence numbers.
//
// Since our goal is to build an array listing the round trip
// times of each packet, our primary concern is to locate the
// time. The best way seems to be to look for an equals
// character, a number and then 'ms'. All the "time=" versions
// of ping will match this methodology, and all the pings which
// don't show "time=" (that I've seen examples from) also match
// this methodolgy.
$results = array();
for ( $i=1; $i<count($upper); $i++ ) {
// by our definition, it's not a success line if we can't
// find the time
if ( preg_match('/=\s*([\d+\.]+)\s*ms/i', $upper[$i], $matches) ) {
// float cast deals neatly with values like "126." which
// some pings generate
$rtt = (float)$matches[1];
// does the line have an obvious sequence number?
if ( preg_match('/icmp_seq\s*=\s*([\d+]+)/i', $upper[$i], $matches) ) {
$results[$matches[1]] = $rtt;
}
else {
// we use the number of the line as the sequence number
$results[($i-1)] = $rtt;
}
}
}
return( $results );
}
/**
* Locates the "packets lost" percentage in the ping output
*
* @access private
*/
function _parseResultDetailLoss($lower)
{
for ( $i=1; $i<count($lower); $i++ ) {
if ( preg_match('/(\d+)%/', $lower[$i], $matches) ) {
$this->_loss = (int)$matches[1];
return;
}
}
}
/**
* Locates the "packets received" in the ping output
*
* @access private
*/
function _parseResultDetailReceived($lower)
{
for ( $i=1; $i<count($lower); $i++ ) {
// the second number on the line
if ( preg_match('/^\D*\d+\D+(\d+)/', $lower[$i], $matches) ) {
$this->_received = (int)$matches[1];
return;
}
}
}
/**
* determines the mininum, maximum, average and standard deviation
* of the round trip times.
*
* @access private
*/
function _parseResultDetailRoundTrip($lower)
{
// The first pattern will match a sequence of 3 or 4
// alaphabet-char strings separated with slashes without
// presuming the order. eg, "min/max/avg" and
// "min/max/avg/mdev". Some ping flavors don't have the standard
// deviation value, and some have different names for it when
// present.
$p1 = '[a-z]+/[a-z]+/[a-z]+/?[a-z]*';
// And the pattern for 3 or 4 numbers (decimal values permitted)
// separated by slashes.
$p2 = '[0-9\.]+/[0-9\.]+/[0-9\.]+/?[0-9\.]*';
$results = array();
$matches = array();
for ( $i=(count($lower)-1); $i>=0; $i-- ) {
if ( preg_match('|('.$p1.')[^0-9]+('.$p2.')|i', $lower[$i], $matches) ) {
break;
}
}
// matches?
if ( count($matches) > 0 ) {
// we want standardized keys in the array we return. Here we
// look for the values (min, max, etc) and setup the return
// hash
$fields = explode('/', $matches[1]);
$values = explode('/', $matches[2]);
for ( $i=0; $i<count($fields); $i++ ) {
if ( preg_match('/min/i', $fields[$i]) ) {
$results['min'] = (float)$values[$i];
}
else if ( preg_match('/max/i', $fields[$i]) ) {
$results['max'] = (float)$values[$i];
}
else if ( preg_match('/avg/i', $fields[$i]) ) {
$results['avg'] = (float)$values[$i];
}
else if ( preg_match('/dev/i', $fields[$i]) ) { # stddev or mdev
$results['stddev'] = (float)$values[$i];
}
}
return( $results );
}
// So we had no luck finding RTT info in a/b/c layout. Some ping
// flavors give the RTT information in an "a=1 b=2 c=3" sort of
// layout.
$p3 = '[a-z]+\s*=\s*([0-9\.]+).*';
for ( $i=(count($lower)-1); $i>=0; $i-- ) {
if ( preg_match('/min.*max/i', $lower[$i]) ) {
if ( preg_match('/'.$p3.$p3.$p3.'/i', $lower[$i], $matches) ) {
$results['min'] = $matches[1];
$results['max'] = $matches[2];
$results['avg'] = $matches[3];
}
break;
}
}
// either an array of min, max and avg from just above, or still
// the empty array from initialization way above
return( $results );
}
/**
* determinces the target IP address actually used by ping
*
* @access private
*/
function _parseResultDetailTargetIp($upper)
{
// Grab the first IP addr we can find. Most ping flavors
// put the target IP on the first line, but some only list it
// in successful ping packet lines.
for ( $i=0; $i<count($upper); $i++ ) {
if ( preg_match('/(\d+\.\d+\.\d+\.\d+)/', $upper[$i], $matches) ) {
return( $matches[0] );
}
}
// no idea...
return( NULL );
}
/**
* Locates the "packets received" in the ping output
*
* @access private
*/
function _parseResultDetailTransmitted($lower)
{
for ( $i=1; $i<count($lower); $i++ ) {
// the first number on the line
if ( preg_match('/^\D*(\d+)/', $lower[$i], $matches) ) {
$this->_transmitted = (int)$matches[1];
return;
}
}
}
/**
* determinces the time to live (TTL) actually used by ping
*
* @access private
*/
function _parseResultDetailTtl($upper)
{
//extract TTL from first icmp echo line
for ( $i=1; $i<count($upper); $i++ ) {
if ( preg_match('/ttl=(\d+)/i', $upper[$i], $matches)
&& (int)$matches[1] > 0
) {
return( (int)$matches[1] );
}
}
// No idea what ttl was used. Probably because no packets
// received in reply.
return( NULL );
}
/**
* Modifies the array to temoves leading and trailing blank lines
*
* @access private
*/
function _parseResultTrimLines(&$data)
{
if ( !is_array($data) ) {
print_r($this);
exit;
}
// Trim empty elements from the front
while ( preg_match('/^\s*$/', $data[0]) ) {
array_splice($data, 0, 1);
}
// Trim empty elements from the back
while ( preg_match('/^\s*$/', $data[(count($data)-1)]) ) {
array_splice($data, -1, 1);
}
}
/**
* Separates the upper portion (data about individual ICMP ECHO
* packets) and the lower portion (statistics about the ping
* execution as a whole.)
*
* @access private
*/
function _parseResultSeparateParts($data, &$upper, &$lower)
{
$upper = array();
$lower = array();
// find the blank line closest to the end
$dividerIndex = count($data) - 1;
while ( !preg_match('/^\s*$/', $data[$dividerIndex]) ) {
$dividerIndex--;
if ( $dividerIndex < 0 ) {
break;
}
}
// This is horrible; All the other methods assume we're able to
// separate the upper (preamble and per-packet output) and lower
// (statistics and summary output) sections.
if ( $dividerIndex < 0 ) {
$upper = $data;
$lower = $data;
return;
}
for ( $i=0; $i<$dividerIndex; $i++ ) {
$upper[] = $data[$i];
}
for ( $i=(1+$dividerIndex); $i<count($data); $i++ ) {
$lower[] = $data[$i];
}
}
/**
* Returns a Ping_Result property
*
* @param string $name property name
* @return mixed property value
* @access public
*/
function getValue($name)
{
return isset($this->$name)?$this->$name:'';
} /* function getValue() */
/**
* Accessor for $this->_target_ip;
*
* @return string IP address
* @access public
* @see Ping_Result::_target_ip
*/
function getTargetIp()
{
return $this->_target_ip;
} /* function getTargetIp() */
/**
* Accessor for $this->_icmp_sequence;
*
* @return array ICMP sequence
* @access private
* @see Ping_Result::_icmp_sequence
*/
function getICMPSequence()
{
return $this->_icmp_sequence;
} /* function getICMPSequencs() */
/**
* Accessor for $this->_bytes_per_request;
*
* @return int bytes per request
* @access private
* @see Ping_Result::_bytes_per_request
*/
function getBytesPerRequest()
{
return $this->_bytes_per_request;
} /* function getBytesPerRequest() */
/**
* Accessor for $this->_bytes_total;
*
* @return int total bytes
* @access private
* @see Ping_Result::_bytes_total
*/
function getBytesTotal()
{
return $this->_bytes_total;
} /* function getBytesTotal() */
/**
* Accessor for $this->_ttl;
*
* @return int TTL
* @access private
* @see Ping_Result::_ttl
*/
function getTTL()
{
return $this->_ttl;
} /* function getTTL() */
/**
* Accessor for $this->_raw_data;
*
* @return array raw data
* @access private
* @see Ping_Result::_raw_data
*/
function getRawData()
{
return $this->_raw_data;
} /* function getRawData() */
/**
* Accessor for $this->_sysname;
*
* @return string OS_Guess::sysname
* @access private
* @see Ping_Result::_sysname
*/
function getSystemName()
{
return $this->_sysname;
} /* function getSystemName() */
/**
* Accessor for $this->_round_trip;
*
* @return array statistical information
* @access private
* @see Ping_Result::_round_trip
*/
function getRoundTrip()
{
return $this->_round_trip;
} /* function getRoundTrip() */
/**
* Accessor for $this->_round_trip['min'];
*
* @return array statistical information
* @access private
* @see Ping_Result::_round_trip
*/
function getMin()
{
return $this->_round_trip['min'];
} /* function getMin() */
/**
* Accessor for $this->_round_trip['max'];
*
* @return array statistical information
* @access private
* @see Ping_Result::_round_trip
*/
function getMax()
{
return $this->_round_trip['max'];
} /* function getMax() */
/**
* Accessor for $this->_round_trip['stddev'];
*
* @return array statistical information
* @access private
* @see Ping_Result::_round_trip
*/
function getStddev()
{
return $this->_round_trip['stddev'];
} /* function getStddev() */
/**
* Accessor for $this->_round_tripp['avg'];
*
* @return array statistical information
* @access private
* @see Ping_Result::_round_trip
*/
function getAvg()
{
return $this->_round_trip['avg'];
} /* function getAvg() */
/**
* Accessor for $this->_transmitted;
*
* @return array statistical information
* @access private
*/
function getTransmitted()
{
return $this->_transmitted;
} /* function getTransmitted() */
/**
* Accessor for $this->_received;
*
* @return array statistical information
* @access private
*/
function getReceived()
{
return $this->_received;
} /* function getReceived() */
/**
* Accessor for $this->_loss;
*
* @return array statistical information
* @access private
*/
function getLoss()
{
return $this->_loss;
} /* function getLoss() */
} /* class Net_Ping_Result */
?>
| lucor/ortro | plugins/system/ping/lib/Pear/Net/Ping.php | PHP | gpl-2.0 | 38,812 |
<?php
/**
* @file
* Zen theme's implementation to display the basic html structure of a single
* Drupal page.
*
* Variables:
* - $css: An array of CSS files for the current page.
* - $language: (object) The language the site is being displayed in.
* $language->language contains its textual representation. $language->dir
* contains the language direction. It will either be 'ltr' or 'rtl'.
* - $rdf_namespaces: All the RDF namespace prefixes used in the HTML document.
* - $grddl_profile: A GRDDL profile allowing agents to extract the RDF data.
* - $head_title: A modified version of the page title, for use in the TITLE
* tag.
* - $head_title_array: (array) An associative array containing the string parts
* that were used to generate the $head_title variable, already prepared to be
* output as TITLE tag. The key/value pairs may contain one or more of the
* following, depending on conditions:
* - title: The title of the current page, if any.
* - name: The name of the site.
* - slogan: The slogan of the site, if any, and if there is no title.
* - $head: Markup for the HEAD section (including meta tags, keyword tags, and
* so on).
* - $styles: Style tags necessary to import all CSS files for the page.
* - $scripts: Script tags necessary to load the JavaScript files and settings
* for the page.
* - $jump_link_target: The HTML ID of the element that the "Jump to Navigation"
* link should jump to. Defaults to "main-menu".
* - $page_top: Initial markup from any modules that have altered the
* page. This variable should always be output first, before all other dynamic
* content.
* - $page: The rendered page content.
* - $page_bottom: Final closing markup from any modules that have altered the
* page. This variable should always be output last, after all other dynamic
* content.
* - $classes: String of classes that can be used to style contextually through
* CSS. It should be placed within the <body> tag. When selecting through CSS
* it's recommended that you use the body tag, e.g., "body.front". It can be
* manipulated through the variable $classes_array from preprocess functions.
* The default values can contain one or more of the following:
* - front: Page is the home page.
* - not-front: Page is not the home page.
* - logged-in: The current viewer is logged in.
* - not-logged-in: The current viewer is not logged in.
* - node-type-[node type]: When viewing a single node, the type of that node.
* For example, if the node is a Blog entry, this would be "node-type-blog".
* Note that the machine name of the content type will often be in a short
* form of the human readable label.
* The following only apply with the default sidebar_first and sidebar_second
* block regions:
* - two-sidebars: When both sidebars have content.
* - no-sidebars: When no sidebar content exists.
* - one-sidebar and sidebar-first or sidebar-second: A combination of the
* two classes when only one of the two sidebars have content.
*
* @see template_preprocess()
* @see template_preprocess_html()
* @see zen_preprocess_html()
* @see template_process()
*/
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>
<head profile="<?php print $grddl_profile; ?>">
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, minimum-scale=1, user-scalable=no" />
<?php print $styles; ?>
<?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
<div id="skip-link">
<a href="#<?php print $jump_link_target; ?>" class="element-invisible element-focusable"><?php print t('Jump to Navigation'); ?></a>
</div>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $page_bottom; ?>
</body>
</html>
| etype-services/fredericksburg | sites/all/themes/news_center/templates/html.tpl.php | PHP | gpl-2.0 | 4,146 |
package com.crazydude.navigationhandlerdemo.fragments;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.crazydude.navigationhandlerdemo.R;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ThirdFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ThirdFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ThirdFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FirstFragment.
*/
// TODO: Rename and change types and number of parameters
public static ThirdFragment newInstance(String param1, String param2) {
ThirdFragment fragment = new ThirdFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public ThirdFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
setRetainInstance(true);
Log.d("Lifecycle", "Created 3 fragment");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_third, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Lifecycle", "Destroyed 3 fragment");
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
| CrazyDude1994/android-navigation-handler | app/src/main/java/com/crazydude/navigationhandlerdemo/fragments/ThirdFragment.java | Java | gpl-2.0 | 3,525 |
<body>
<div id="container_guiga">
<h1 class="h1_guiga"> Bem-vindo! </h1>
<div id="body_guiga">
<?php
echo "hi";
echo form_open('usuario/login');
$inputEmail = array('name'=>'email',
'id'=>'email',
'style'=>'width:40%;font-size:100px');
$inputSenha = array('name'=>'senha',
'id'=>'senha',
'maxlength'=>'10',
'style'=>'width:40%;font-size:100px');
echo form_input($inputEmail);
echo form_password($inputSenha);
echo form_close();
//<button type="submit" style="width:150px;height:75px" class="btn btn-default">Logar!</button>
/*echo "<br>";
$img_delete = array(
'src' => 'assets/img/delete_32x32.png',
'alt' => 'Delete'
);
$img_detalhes = array(
'src' => 'assets/img/detalhes_32x32.png',
'alt' => 'Detalhes'
);
$img_editar = array(
'src' => 'assets/img/editar_32x32.png',
'alt' => 'Editar'
);
$this->table->set_heading(array('Nome','Ver','Editar','Excluir'));
foreach ($usuarios as $usuario){
$this->table->add_row(array(
$usuario->username,
anchor('welcome', img($img_delete)),
anchor('welcome', img($img_detalhes)),
anchor('welcome', img($img_editar))
));
}
echo $this->table->generate();
*/
?>
<h2>Hi </h2>
</div>
</body>
<!-- <table class="table-striped" > -->
<!-- <tr> -->
<!-- <td>Teste</td> -->
<!-- <td>Teste</td> -->
<!-- </tr> -->
<!-- <tr> -->
<!-- <td>Teste</td> -->
<!-- <td>Teste</td> -->
<!-- </tr> -->
<!-- </table> -->
| Frenetick/e-conference-Guilherme-4C | econference/application/views/home_deslogado.php | PHP | gpl-2.0 | 1,576 |
/*
* Copyright (C) 2016-2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 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.
*/
#include <base/stream/IStringStream.h>
#include <base/util/Random.h>
#include <base/util/Time.h>
#include <base/CPU.h>
#include <m3/stream/Standard.h>
#include "loop.h"
using namespace m3;
alignas(64) static rand_type buffer[EL_COUNT];
int main(int argc, char **argv) {
if(argc != 2)
exitmsg("Usage: " << argv[0] << " <count>");
size_t count = IStringStream::read_from<size_t>(argv[1]);
while(count > 0) {
size_t amount = Math::min(count, ARRAY_SIZE(buffer));
Time::start(0x5555);
CPU::compute(amount * 8);
// generate(buffer, amount);
Time::stop(0x5555);
cout.write(buffer, amount * sizeof(rand_type));
count -= amount;
}
return 0;
}
| TUD-OS/M3 | src/apps/coreutils/rand/rand.cc | C++ | gpl-2.0 | 1,382 |
using System;
using System.IO;
using System.Net;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.codec.wmf;
/*
* $Id: ImgWMF.cs,v 1.3 2005/08/19 16:07:53 psoares33 Exp $
* $Name: $
*
* Copyright 1999, 2000, 2001, 2002 by Paulo Soares.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
namespace iTextSharp.text {
/**
* An ImgWMF is the representation of a windows metafile
* that has to be inserted into the document
*
* @see Element
* @see Image
* @see Gif
* @see Png
*/
/// <summary>
/// An ImgWMF is the representation of a windows metafile
/// that has to be inserted into the document
/// </summary>
public class ImgWMF : Image, IElement {
// Constructors
/// <summary>
/// Constructs an ImgWMF-object
/// </summary>
/// <param name="image">a Image</param>
ImgWMF(Image image) : base(image) {}
/// <summary>
/// Constructs an ImgWMF-object, using an url.
/// </summary>
/// <param name="url">the URL where the image can be found</param>
public ImgWMF(Uri url) : base(url) {
ProcessParameters();
}
/// <summary>
/// Constructs an ImgWMF-object, using a filename.
/// </summary>
/// <param name="filename">a string-representation of the file that contains the image.</param>
public ImgWMF(string filename) : this(Image.ToURL(filename)) {}
/// <summary>
/// Constructs an ImgWMF-object from memory.
/// </summary>
/// <param name="img">the memory image</param>
public ImgWMF(byte[] img) : base((Uri)null) {
rawData = img;
originalData = img;
ProcessParameters();
}
/// <summary>
/// This method checks if the image is a valid WMF and processes some parameters.
/// </summary>
private void ProcessParameters() {
type = Element.IMGTEMPLATE;
originalType = ORIGINAL_WMF;
Stream istr = null;
try {
string errorID;
if (rawData == null){
#if !NETCF
WebRequest w = WebRequest.Create(url);
istr = w.GetResponse().GetResponseStream();
errorID = url.ToString();
#else
istr = new FileStream(url.LocalPath, FileMode.Open);
errorID="NETCF filestream";
#endif
}
else{
istr = new MemoryStream(rawData);
errorID = "Byte array";
}
InputMeta im = new InputMeta(istr);
if (im.ReadInt() != unchecked((int)0x9AC6CDD7)) {
throw new BadElementException(errorID + " is not a valid placeable windows metafile.");
}
im.ReadWord();
int left = im.ReadShort();
int top = im.ReadShort();
int right = im.ReadShort();
int bottom = im.ReadShort();
int inch = im.ReadWord();
dpiX = 72;
dpiY = 72;
scaledHeight = (float)(bottom - top) / inch * 72f;
this.Top =scaledHeight;
scaledWidth = (float)(right - left) / inch * 72f;
this.Right = scaledWidth;
}
finally {
if (istr != null) {
istr.Close();
}
plainWidth = this.Width;
plainHeight = this.Height;
}
}
/// <summary>
/// Reads the WMF into a template.
/// </summary>
/// <param name="template">the template to read to</param>
public void ReadWMF(PdfTemplate template) {
TemplateData = template;
template.Width = this.Width;
template.Height = this.Height;
Stream istr = null;
try {
if (rawData == null){
#if !NETCF
WebRequest w = WebRequest.Create(url);
istr = w.GetResponse().GetResponseStream();
#else
istr = new FileStream(url.LocalPath, FileMode.Open);
#endif
}
else{
istr = new MemoryStream(rawData);
}
MetaDo meta = new MetaDo(istr, template);
meta.ReadAll();
}
finally {
if (istr != null) {
istr.Close();
}
}
}
}
}
| hjgode/iTextSharpCF | itextsharp-4.0.1/iTextSharp/text/ImgWMF.cs | C# | gpl-2.0 | 7,021 |
package com.github.eswrapper.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.guess.core.orm.IdEntity;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* 监控记录明细Entity
* @author Joe.zhang
* @version 2016-08-05
*/
@Entity
@Table(name = "es_monitor_log_detail")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class MonitorLogDetail extends IdEntity {
/**
* 集群名
*/
@Column(name = "cluster_name")
private String clusterName;
/**
* 接点
*/
@Column(name = "node")
private String node;
/**
* 成功次数
*/
@Column(name = "success_count")
private Long successCount;
/**
* 成功TPS
*/
@Column(name = "success_tps")
private float successTps;
/**
* 失败次数
*/
@Column(name = "failure_count")
private Long failureCount;
/**
* 失败Tps
*/
@Column(name = "failure_tps")
private float failureTps;
/**
* 线程池最小值
*/
@Column(name = "concurrent_min")
private Long concurrentMin;
/**
* 线程池平均值
*/
@Column(name = "concurrent_ave")
private float concurrentAve;
/**
* 线程池最大值
*/
@Column(name = "concurrent_max")
private Long concurrentMax;
/**
* logId
*/
@Column(name = "log_id",insertable=false,updatable=false)
private Long logId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "log_id")
@NotFound(action = NotFoundAction.IGNORE)
@JsonIgnoreProperties(value = { "creater","updater","logDetails"})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private MonitorLog log;
@Column(name = "elapsed_min")
private Long elapsedMin;
/**
* 耗时平均值
*/
@Column(name = "elapsed_ave")
private float elapsedAve;
/**
* 耗时最大值
*/
@Column(name = "elapsed_max")
private Long elapsedMax;
@Column(name = "writequeue_min")
private Long writequeueMin;
/**
* 写入队列平均值
*/
@Column(name = "writequeue_ave")
private float writequeueAve;
/**
* 写入队列最大值
*/
@Column(name = "writequeue_max")
private Long writequeueMax;
@Column(name = "writepool_min")
private Long writepoolMin;
/**
* 写入队列平均值
*/
@Column(name = "writepool_ave")
private float writepoolAve;
/**
* 写入队列最大值
*/
@Column(name = "writepool_max")
private Long writepoolMax;
@Column(name = "searchqueue_min")
private Long searchqueueMin;
/**
* 写入队列平均值
*/
@Column(name = "searchqueue_ave")
private float searchqueueAve;
/**
* 写入队列最大值
*/
@Column(name = "searchqueue_max")
private Long searchqueueMax;
@Column(name = "searchpool_min")
private Long searchpoolMin;
/**
* 写入队列平均值
*/
@Column(name = "searchpool_ave")
private float searchpoolAve;
/**
* 写入队列最大值
*/
@Column(name = "searchpool_max")
private Long searchpoolMax;
public MonitorLog getLog() {
return log;
}
public void setLog(MonitorLog log) {
this.log = log;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public Long getElapsedMin() {
return elapsedMin;
}
public void setElapsedMin(Long elapsedMin) {
this.elapsedMin = elapsedMin;
}
public float getElapsedAve() {
return elapsedAve;
}
public void setElapsedAve(float elapsedAve) {
this.elapsedAve = elapsedAve;
}
public Long getElapsedMax() {
return elapsedMax;
}
public void setElapsedMax(Long elapsedMax) {
this.elapsedMax = elapsedMax;
}
public Long getWritequeueMin() {
return writequeueMin;
}
public void setWritequeueMin(Long writequeueMin) {
this.writequeueMin = writequeueMin;
}
public float getWritequeueAve() {
return writequeueAve;
}
public void setWritequeueAve(float writequeueAve) {
this.writequeueAve = writequeueAve;
}
public Long getWritequeueMax() {
return writequeueMax;
}
public void setWritequeueMax(Long writequeueMax) {
this.writequeueMax = writequeueMax;
}
public Long getWritepoolMin() {
return writepoolMin;
}
public void setWritepoolMin(Long writepoolMin) {
this.writepoolMin = writepoolMin;
}
public float getWritepoolAve() {
return writepoolAve;
}
public void setWritepoolAve(float writepoolAve) {
this.writepoolAve = writepoolAve;
}
public Long getWritepoolMax() {
return writepoolMax;
}
public void setWritepoolMax(Long writepoolMax) {
this.writepoolMax = writepoolMax;
}
public Long getSearchqueueMin() {
return searchqueueMin;
}
public void setSearchqueueMin(Long searchqueueMin) {
this.searchqueueMin = searchqueueMin;
}
public float getSearchqueueAve() {
return searchqueueAve;
}
public void setSearchqueueAve(float searchqueueAve) {
this.searchqueueAve = searchqueueAve;
}
public Long getSearchqueueMax() {
return searchqueueMax;
}
public void setSearchqueueMax(Long searchqueueMax) {
this.searchqueueMax = searchqueueMax;
}
public Long getSearchpoolMin() {
return searchpoolMin;
}
public void setSearchpoolMin(Long searchpoolMin) {
this.searchpoolMin = searchpoolMin;
}
public float getSearchpoolAve() {
return searchpoolAve;
}
public void setSearchpoolAve(float searchpoolAve) {
this.searchpoolAve = searchpoolAve;
}
public Long getSearchpoolMax() {
return searchpoolMax;
}
public void setSearchpoolMax(Long searchpoolMax) {
this.searchpoolMax = searchpoolMax;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
public Long getSuccessCount() {
return successCount;
}
public void setSuccessCount(Long successCount) {
this.successCount = successCount;
}
public float getSuccessTps() {
return successTps;
}
public void setSuccessTps(float successTps) {
this.successTps = successTps;
}
public Long getFailureCount() {
return failureCount;
}
public void setFailureCount(Long failureCount) {
this.failureCount = failureCount;
}
public float getFailureTps() {
return failureTps;
}
public void setFailureTps(float failureTps) {
this.failureTps = failureTps;
}
public Long getConcurrentMin() {
return concurrentMin;
}
public void setConcurrentMin(Long concurrentMin) {
this.concurrentMin = concurrentMin;
}
public float getConcurrentAve() {
return concurrentAve;
}
public void setConcurrentAve(float concurrentAve) {
this.concurrentAve = concurrentAve;
}
public Long getConcurrentMax() {
return concurrentMax;
}
public void setConcurrentMax(Long concurrentMax) {
this.concurrentMax = concurrentMax;
}
public Long getLogId() {
return logId;
}
public void setLogId(Long logId) {
this.logId = logId;
}
} | joezxh/DATAX-UI | eshbase-proxy/src/main/java/com/github/eswrapper/model/MonitorLogDetail.java | Java | gpl-2.0 | 7,024 |
#include <QtCore/QElapsedTimer>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QInputDialog>
#include <QtGui/QColorDialog>
#include <QtGui/QMdiSubWindow>
#include "MainWindow.h"
QtMainWindow::QtMainWindow(QApplication* app) : m_shortCutDelete(QShortcut(QKeySequence(Qt::Key_Delete), this, SLOT(editDelete())))
{
try
{
m_app = app;
this->setupUi(this);
this->setAttribute(Qt::WA_QuitOnClose);
this->setWindowTitle(QApplication::applicationName());
createActions();
createProgressBar();
readSettings();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
QtMainWindow::~QtMainWindow()
{
try
{
mdiArea->removeSubWindow(m_manager->window());
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::closeEvent(QCloseEvent *event)
{
try
{
writeSettings();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::createActions()
{
try
{
// File
connect(actionFileNew, SIGNAL(triggered()), this, SLOT(fileNew()));
connect(actionFileOpen, SIGNAL(triggered()), this, SLOT(fileOpen()));
connect(actionFileSaveAs, SIGNAL(triggered()), this, SLOT(fileSaveAs()));
connect(actionFileImport, SIGNAL(triggered()), this, SLOT(fileImport()));
connect(actionFileExport, SIGNAL(triggered()), this, SLOT(fileExport()));
connect(actionExit, SIGNAL(triggered()), this, SLOT(applicationExit()));
// Edit
connect(actionEditDelete, SIGNAL(triggered()), this, SLOT(editDelete()));
// View
connect(actionViewRenderWireframe, SIGNAL(triggered()), this, SLOT(viewWireframe()));
connect(actionViewRenderShaded, SIGNAL(triggered()), this, SLOT(viewShaded()));
connect(actionViewOrientationFront, SIGNAL(triggered()), this, SLOT(viewFront()));
connect(actionViewOrientationBack, SIGNAL(triggered()), this, SLOT(viewBack()));
connect(actionViewOrientationLeft, SIGNAL(triggered()), this, SLOT(viewLeft()));
connect(actionViewOrientationRight, SIGNAL(triggered()), this, SLOT(viewRight()));
connect(actionViewOrientationTop, SIGNAL(triggered()), this, SLOT(viewTop()));
connect(actionViewOrientationBottom, SIGNAL(triggered()), this, SLOT(viewBottom()));
connect(actionViewOrientationIsometric, SIGNAL(triggered()), this, SLOT(viewIsometric()));
connect(actionViewColor, SIGNAL(triggered()), this, SLOT(viewColor()));
// Select
connect(actionSelectVertices, SIGNAL(triggered()), this, SLOT(selectVertices()));
connect(actionSelectEdges, SIGNAL(triggered()), this, SLOT(selectEdges()));
connect(actionSelectWires, SIGNAL(triggered()), this, SLOT(selectWires()));
connect(actionSelectFaces, SIGNAL(triggered()), this, SLOT(selectFaces()));
connect(actionSelectSolids, SIGNAL(triggered()), this, SLOT(selectSolids()));
connect(actionSelectAll, SIGNAL(triggered()), this, SLOT(selectAll()));
// Shape
connect(actionShapeDecompose, SIGNAL(triggered()), this, SLOT(decomposeShape()));
connect(actionShapeFuse, SIGNAL(triggered()), this, SLOT(fuseShape()));
connect(actionShapeOffset, SIGNAL(triggered()), this, SLOT(offsetShape()));
connect(actionShapeBuild, SIGNAL(triggered()), this, SLOT(buildShape()));
// Mesh
connect(actionMeshSurface, SIGNAL(triggered()), this, SLOT(meshSurface()));
connect(actionMeshVolume, SIGNAL(triggered()), this, SLOT(meshVolume()));
connect(actionMeshStitch, SIGNAL(triggered()), this, SLOT(meshStitch()));
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::createProgressBar()
{
try
{
// Progress bar
m_progressBar.setVisible(true);
m_progressBar.setTextVisible(true);
m_progressBar.setMinimum(0);
m_progressBar.setMaximum(100);
infoBar->addPermanentWidget(&m_progressBar);
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::readSettings()
{
try
{
// Read settings INI file
QSettings settings(QApplication::applicationDirPath().append(QDir::separator()).append("ACTiVE.ini"), QSettings::IniFormat);
settings.beginGroup("GUI");
m_curDir = settings.value("CurDir").toString();
int x = settings.value("PosX").toInt();
int y = settings.value("PosY").toInt();
int w = settings.value("Width").toInt();
int h = settings.value("Height").toInt();
this->setGeometry(x, y, w, h);
this->resize(w, h);
settings.endGroup();
settings.beginGroup("Mesh");
m_interval = settings.value("Interval").toInt();
m_maxElem = settings.value("MaxElem").toInt();
settings.endGroup();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::writeSettings()
{
try
{
// Write settings INI file
QSettings settings(QApplication::applicationDirPath().append(QDir::separator()).append("ACTiVE.ini"), QSettings::IniFormat);
settings.beginGroup("GUI");
settings.setValue("CurDir", m_curDir);
settings.setValue("PosX", this->geometry().x());
settings.setValue("PosY", this->geometry().y());
settings.setValue("Width", this->geometry().width());
settings.setValue("Height", this->geometry().height());
settings.endGroup();
settings.sync();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::fileNew()
{
try
{
m_manager->reset();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::fileOpen()
{
}
void QtMainWindow::fileSaveAs()
{
}
void QtMainWindow::fileImport()
{
try
{
QString selfilter = tr("STEP files (*.stp *.step)");
QString fileName = QFileDialog::getOpenFileName(this, tr("Import"), m_curDir,
tr("All files (*.*);;STEP files (*.stp *.step);;IGES files (*.igs *.iges);;STL files (*.stl)"),
&selfilter);
if (fileName == QString::null) return;
QFileInfo fileInfo(fileName);
m_curDir = fileInfo.absolutePath();
if (!QFileInfo(fileName).exists())
{
qDebug() << "Error: file does not exist: " << fileName;
return;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
QString fileExt = QFileInfo(QString(fileName)).completeSuffix();
if (QString::compare(fileExt, "stp", Qt::CaseInsensitive) == 0 || QString::compare(fileExt, "step", Qt::CaseInsensitive) == 0)
{
// Import STEP file
m_manager->importGeometry(OccTranslator::FormatSTEP, fileName);
}
else if (QString::compare(fileExt, "iges", Qt::CaseInsensitive) == 0 || QString::compare(fileExt, "igs", Qt::CaseInsensitive) == 0)
{
// Import IGES file
m_manager->importGeometry(OccTranslator::FormatIGES, fileName);
}
else if (QString::compare(fileExt, "brep", Qt::CaseInsensitive) == 0)
{
// Import BREP file
m_manager->importGeometry(OccTranslator::FormatBREP, fileName);
}
else if (QString::compare(fileExt, "csfdb", Qt::CaseInsensitive) == 0)
{
// Import CSFDB file
m_manager->importGeometry(OccTranslator::FormatCSFDB, fileName);
}
else if (QString::compare(fileExt, "stl", Qt::CaseInsensitive) == 0)
{
// Import STL file
m_manager->importMesh(OccTranslator::FormatSTL, fileName);
}
else
return;
QApplication::restoreOverrideCursor();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::fileExport()
{
try
{
QString selfilter = tr("STL files (*.stl)");
QString fileName = QFileDialog::getSaveFileName(this, tr("Export"), m_curDir,
tr("STL files (*.stl);;Gmsh files (*.msh);;Vtk files (*.vtk)"),
&selfilter);
if (fileName == QString::null) return;
QString fileExt = QFileInfo(QString(fileName)).completeSuffix();
if (QString::compare(fileExt, "stl", Qt::CaseInsensitive) == 0)
{
// Export STL
m_manager->exportMesh(OccTranslator::FormatSTL, fileName);
}
else if (QString::compare(fileExt, "msh", Qt::CaseInsensitive) == 0)
{
// Export mesh
m_manager->exportMesh(OccTranslator::FormatGmsh, fileName);
}
else if (QString::compare(fileExt, "vtk", Qt::CaseInsensitive) == 0)
{
// Export mesh
m_manager->exportMesh(OccTranslator::FormatVtk, fileName);
}
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::applicationExit()
{
try
{
m_app->quit();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
// Select
void QtMainWindow::selectVertices()
{
try
{
m_manager->selectVertices();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::selectEdges()
{
try
{
m_manager->selectEdges();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::selectWires()
{
try
{
m_manager->selectWires();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::selectFaces()
{
try
{
m_manager->selectFaces();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::selectSolids()
{
try
{
m_manager->selectSolids();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::selectAll()
{
try
{
m_manager->selectAll();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
// Edit
void QtMainWindow::editDelete()
{
try
{
m_manager->deleteSelected();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
// View
void QtMainWindow::viewWireframe()
{
try
{
m_manager->viewWireframe();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewShaded()
{
try
{
m_manager->viewShaded();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewFront()
{
try
{
m_manager->viewFront();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewBack()
{
try
{
m_manager->viewBack();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewLeft()
{
try
{
m_manager->viewLeft();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewRight()
{
try
{
m_manager->viewRight();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewTop()
{
try
{
m_manager->viewTop();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewBottom()
{
try
{
m_manager->viewBottom();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewIsometric()
{
try
{
m_manager->viewIsometric();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::viewColor()
{
try
{
QColor color = QColorDialog::getColor();
if (color.isValid())
{
m_manager->setColor(color);
}
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
// Shape
void QtMainWindow::decomposeShape()
{
try
{
m_manager->decomposeShape();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::fuseShape()
{
try
{
m_manager->fuseShape();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::offsetShape()
{
try
{
QString text = QInputDialog::getText(this, "Input", "Enter offset", QLineEdit::Normal, "1.0");
if (text == QString::null)
return;
m_manager->offsetShape(text.toDouble());
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::buildShape()
{
try
{
m_manager->buildShape();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
// Mesh
void QtMainWindow::meshSurface()
{
try
{
QString text = QInputDialog::getText(this, "Input", "Enter mesh size", QLineEdit::Normal, "2.0");
if (text == QString::null)
return;
m_manager->meshSurface(text.toDouble());
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::meshVolume()
{
try
{
QString text = QInputDialog::getText(this, "Input", "Enter mesh size", QLineEdit::Normal, "2.0");
if (text == QString::null)
return;
m_manager->meshVolume(text.toDouble());
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::meshStitch()
{
try
{
m_manager->meshStitch();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::setManager(QSharedPointer<OccManager> aManager)
{
try
{
m_manager = aManager;
treeView->setModel(m_manager->treeViewModel());
treeView->setSelectionModel(m_manager->treeViewSelectionModel());
connect(m_manager.data(), SIGNAL(onSelectionChanged()), this, SLOT(selectionChanged()));
// Graphics window
mdiArea->addSubWindow(m_manager->window());
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
void QtMainWindow::selectionChanged()
{
try
{
this->showProperties();
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << tr("Unknown exception:") << QString(this->metaObject()->className());
}
}
void QtMainWindow::showProperties()
{
try
{
}
catch(const std::exception & ex)
{
qDebug() << QString(ex.what());
}
catch(...)
{
qDebug() << "Unknown exception: " + QString(this->metaObject()->className());
}
}
| bjaraujo/ENigMA | trunk/examples/occactive/src/qt/MainWindow.cpp | C++ | gpl-2.0 | 20,808 |
/**
* @author jesus
*
*/
public class Principal {
public static void main(String[] args) {
Persona alumno1 = new Alumno("03181199T","Jesus","Ortega Vilchez",true,true,8);
Persona profesor1 = new Profesor("0156478M","Jose Carlos","Villar",true,false,1500.50);
Persona profesorFP1 = new ProfesorFP("02314566G","Javier","Olmedo Garcia",true,false,7);
Persona profesorESO1 = new ProfesorESO("02415874M","Jose Luis","Fernandez Pérez",true,false,"Informatica");
System.out.println("DATOS: "+alumno1.toString());
System.out.println("Es miembro? "+alumno1.esMiembro());
System.out.println("DATOS: "+profesor1.toString());
System.out.println("Es miembro? "+profesor1.esMiembro());
System.out.println("DATOS: "+profesorFP1.toString());
System.out.println("DATOS: "+profesorESO1.toString());
}
}
| JesusOrtegaVilchez/JAVA | Ejercicio_Herencia/Principal.java | Java | gpl-2.0 | 822 |
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2015 Dominik Reichl <dominik.reichl@t-online.de>
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.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using KeePass.App;
using KeePass.UI;
using KeePass.Resources;
using KeePass.Ecas;
using KeePassLib;
using KeePassLib.Utility;
namespace KeePass.Forms
{
public partial class EcasTriggerForm : Form
{
private EcasTrigger m_triggerInOut = null;
private EcasTrigger m_trigger = null;
private bool m_bEditing = false;
private ImageList m_ilIcons = null;
public void InitEx(EcasTrigger trigger, bool bEditing, ImageList ilIcons)
{
m_triggerInOut = trigger;
m_trigger = trigger.CloneDeep();
m_bEditing = bEditing;
m_ilIcons = ilIcons;
}
public EcasTriggerForm()
{
InitializeComponent();
Program.Translation.ApplyTo(this);
}
private void OnFormLoad(object sender, EventArgs e)
{
GlobalWindowManager.AddWindow(this);
string strTitle = (m_bEditing ? KPRes.TriggerEdit : KPRes.TriggerAdd);
string strDesc = (m_bEditing ? KPRes.TriggerEditDesc : KPRes.TriggerAddDesc);
BannerFactory.CreateBannerEx(this, m_bannerImage,
Properties.Resources.B48x48_Run, strTitle, strDesc);
this.Text = strTitle;
this.Icon = Properties.Resources.KeePass;
m_lvEvents.SmallImageList = m_ilIcons;
m_lvConditions.SmallImageList = m_ilIcons;
m_lvActions.SmallImageList = m_ilIcons;
Debug.Assert((m_lvEvents.Width == m_lvConditions.Width) &&
(m_lvEvents.Width == m_lvActions.Width));
int nColWidth = ((m_lvEvents.ClientSize.Width - UIUtil.GetVScrollBarWidth()) / 2);
m_lvEvents.Columns.Add(KPRes.Event, nColWidth);
m_lvEvents.Columns.Add(string.Empty, nColWidth);
m_lvConditions.Columns.Add(KPRes.Condition, nColWidth);
m_lvConditions.Columns.Add(string.Empty, nColWidth);
m_lvActions.Columns.Add(KPRes.Action, nColWidth);
m_lvActions.Columns.Add(string.Empty, nColWidth);
m_tbName.Text = m_trigger.Name;
UIUtil.SetMultilineText(m_tbComments, m_trigger.Comments);
m_cbEnabled.Checked = m_trigger.Enabled;
m_cbInitiallyOn.Checked = m_trigger.InitiallyOn;
m_cbTurnOffAfterAction.Checked = m_trigger.TurnOffAfterAction;
UpdateListsEx(false);
EnableControlsEx();
UIUtil.SetFocus(m_tbName, this);
}
private void CleanUpEx()
{
// Detach event handlers
m_lvEvents.SmallImageList = null;
m_lvConditions.SmallImageList = null;
m_lvActions.SmallImageList = null;
}
private void OnFormClosed(object sender, FormClosedEventArgs e)
{
CleanUpEx();
GlobalWindowManager.RemoveWindow(this);
}
private void OnBtnOK(object sender, EventArgs e)
{
m_triggerInOut.Name = m_tbName.Text;
m_triggerInOut.Comments = m_tbComments.Text;
m_triggerInOut.Enabled = m_cbEnabled.Checked;
m_triggerInOut.InitiallyOn = m_cbInitiallyOn.Checked;
m_triggerInOut.TurnOffAfterAction = m_cbTurnOffAfterAction.Checked;
m_triggerInOut.EventCollection = m_trigger.EventCollection;
m_triggerInOut.ConditionCollection = m_trigger.ConditionCollection;
m_triggerInOut.ActionCollection = m_trigger.ActionCollection;
}
private void OnBtnCancel(object sender, EventArgs e)
{
}
private void OnBtnPrev(object sender, EventArgs e)
{
if(m_tabMain.SelectedIndex > 0)
m_tabMain.SelectedIndex = (m_tabMain.SelectedIndex - 1);
}
private void OnBtnNext(object sender, EventArgs e)
{
if(m_tabMain.SelectedIndex < (m_tabMain.TabCount - 1))
m_tabMain.SelectedIndex = (m_tabMain.SelectedIndex + 1);
}
private void EnableControlsEx()
{
int nTab = m_tabMain.SelectedIndex;
m_btnPrev.Enabled = (nTab > 0);
m_btnNext.Enabled = (nTab < (m_tabMain.TabCount - 1));
int nEventsSel = m_lvEvents.SelectedIndices.Count;
m_btnEventEdit.Enabled = (nEventsSel == 1);
m_btnEventDelete.Enabled = m_btnEventMoveUp.Enabled =
m_btnEventMoveDown.Enabled = (nEventsSel > 0);
int nConditionsSel = m_lvConditions.SelectedIndices.Count;
m_btnConditionEdit.Enabled = (nConditionsSel == 1);
m_btnConditionDelete.Enabled = m_btnConditionMoveUp.Enabled =
m_btnConditionMoveDown.Enabled = (nConditionsSel > 0);
int nActionsSel = m_lvActions.SelectedIndices.Count;
m_btnActionEdit.Enabled = (nActionsSel == 1);
m_btnActionDelete.Enabled = m_btnActionMoveUp.Enabled =
m_btnActionMoveDown.Enabled = (nActionsSel > 0);
}
private void UpdateListsEx(bool bRestoreSelected)
{
UpdateEventListEx(bRestoreSelected);
UpdateConditionListEx(bRestoreSelected);
UpdateActionListEx(bRestoreSelected);
}
private void UpdateEventListEx(bool bRestoreSelected)
{
object[] vSelected = (bRestoreSelected ?
UIUtil.GetSelectedItemTags(m_lvEvents) : null);
UIScrollInfo s = UIUtil.GetScrollInfo(m_lvEvents, true);
List<EcasEvent> lToRemove = new List<EcasEvent>();
m_lvEvents.BeginUpdate();
m_lvEvents.Items.Clear();
foreach(EcasEvent e in m_trigger.EventCollection)
{
EcasEventType t = Program.EcasPool.FindEvent(e.Type);
if(t == null) { Debug.Assert(false); lToRemove.Add(e); continue; }
ListViewItem lvi = m_lvEvents.Items.Add(t.Name);
lvi.SubItems.Add(EcasUtil.ParametersToString(e, t.Parameters));
lvi.Tag = e;
lvi.ImageIndex = (int)t.Icon;
}
foreach(EcasEvent e in lToRemove)
m_trigger.EventCollection.Remove(e);
if(vSelected != null) UIUtil.SelectItems(m_lvEvents, vSelected);
UIUtil.Scroll(m_lvEvents, s, true);
m_lvEvents.EndUpdate();
}
private void UpdateConditionListEx(bool bRestoreSelected)
{
object[] vSelected = (bRestoreSelected ?
UIUtil.GetSelectedItemTags(m_lvConditions) : null);
UIScrollInfo s = UIUtil.GetScrollInfo(m_lvConditions, true);
List<EcasCondition> lToRemove = new List<EcasCondition>();
m_lvConditions.BeginUpdate();
m_lvConditions.Items.Clear();
foreach(EcasCondition c in m_trigger.ConditionCollection)
{
EcasConditionType t = Program.EcasPool.FindCondition(c.Type);
if(t == null) { Debug.Assert(false); lToRemove.Add(c); continue; }
ListViewItem lvi = m_lvConditions.Items.Add(t.Name);
lvi.SubItems.Add(EcasUtil.ParametersToString(c, t.Parameters));
lvi.Tag = c;
lvi.ImageIndex = (int)t.Icon;
}
foreach(EcasCondition c in lToRemove)
m_trigger.ConditionCollection.Remove(c);
if(vSelected != null) UIUtil.SelectItems(m_lvConditions, vSelected);
UIUtil.Scroll(m_lvConditions, s, true);
m_lvConditions.EndUpdate();
}
private void UpdateActionListEx(bool bRestoreSelected)
{
object[] vSelected = (bRestoreSelected ?
UIUtil.GetSelectedItemTags(m_lvActions) : null);
UIScrollInfo s = UIUtil.GetScrollInfo(m_lvActions, true);
List<EcasAction> lToRemove = new List<EcasAction>();
m_lvActions.BeginUpdate();
m_lvActions.Items.Clear();
foreach(EcasAction a in m_trigger.ActionCollection)
{
EcasActionType t = Program.EcasPool.FindAction(a.Type);
if(t == null) { Debug.Assert(false); lToRemove.Add(a); continue; }
ListViewItem lvi = m_lvActions.Items.Add(t.Name);
lvi.SubItems.Add(EcasUtil.ParametersToString(a, t.Parameters));
lvi.Tag = a;
lvi.ImageIndex = (int)t.Icon;
}
foreach(EcasAction a in lToRemove)
m_trigger.ActionCollection.Remove(a);
if(vSelected != null) UIUtil.SelectItems(m_lvActions, vSelected);
UIUtil.Scroll(m_lvActions, s, true);
m_lvActions.EndUpdate();
}
private void OnEventsSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnConditionsSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnActionsSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
private void OnEventAdd(object sender, EventArgs e)
{
EcasEvent eNew = new EcasEvent();
eNew.Type = EcasEventIDs.AppLoadPost;
EcasEventForm dlg = new EcasEventForm();
dlg.InitEx(eNew);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
{
m_trigger.EventCollection.Add(eNew);
UpdateEventListEx(false);
}
}
private void OnEventEdit(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection lvsic = m_lvEvents.SelectedItems;
if((lvsic == null) || (lvsic.Count == 0)) return;
EcasEventForm dlg = new EcasEventForm();
dlg.InitEx(lvsic[0].Tag as EcasEvent);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
UpdateEventListEx(true);
}
private void OnEventDelete(object sender, EventArgs e)
{
UIUtil.DeleteSelectedItems(m_lvEvents, m_trigger.EventCollection);
}
private void OnConditionAdd(object sender, EventArgs e)
{
EcasCondition eNew = new EcasCondition();
EcasConditionForm dlg = new EcasConditionForm();
dlg.InitEx(eNew);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
{
m_trigger.ConditionCollection.Add(eNew);
UpdateConditionListEx(false);
}
}
private void OnConditionEdit(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection lvsic = m_lvConditions.SelectedItems;
if((lvsic == null) || (lvsic.Count == 0)) return;
EcasConditionForm dlg = new EcasConditionForm();
dlg.InitEx(lvsic[0].Tag as EcasCondition);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
UpdateConditionListEx(true);
}
private void OnConditionDelete(object sender, EventArgs e)
{
UIUtil.DeleteSelectedItems(m_lvConditions, m_trigger.ConditionCollection);
}
private void OnActionAdd(object sender, EventArgs e)
{
EcasAction eNew = new EcasAction();
EcasActionForm dlg = new EcasActionForm();
dlg.InitEx(eNew);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
{
m_trigger.ActionCollection.Add(eNew);
UpdateActionListEx(false);
}
}
private void OnActionEdit(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection lvsic = m_lvActions.SelectedItems;
if((lvsic == null) || (lvsic.Count == 0)) return;
EcasActionForm dlg = new EcasActionForm();
dlg.InitEx(lvsic[0].Tag as EcasAction);
if(UIUtil.ShowDialogAndDestroy(dlg) == DialogResult.OK)
UpdateActionListEx(true);
}
private void OnActionDelete(object sender, EventArgs e)
{
UIUtil.DeleteSelectedItems(m_lvActions, m_trigger.ActionCollection);
}
private void OnBtnEventMoveUp(object sender, EventArgs e)
{
UIUtil.MoveSelectedItemsInternalOne(m_lvEvents,
m_trigger.EventCollection, true);
UpdateEventListEx(true);
}
private void OnBtnEventMoveDown(object sender, EventArgs e)
{
UIUtil.MoveSelectedItemsInternalOne(m_lvEvents,
m_trigger.EventCollection, false);
UpdateEventListEx(true);
}
private void OnBtnConditionMoveUp(object sender, EventArgs e)
{
UIUtil.MoveSelectedItemsInternalOne(m_lvConditions,
m_trigger.ConditionCollection, true);
UpdateConditionListEx(true);
}
private void OnBtnConditionMoveDown(object sender, EventArgs e)
{
UIUtil.MoveSelectedItemsInternalOne(m_lvConditions,
m_trigger.ConditionCollection, false);
UpdateConditionListEx(true);
}
private void OnBtnActionMoveUp(object sender, EventArgs e)
{
UIUtil.MoveSelectedItemsInternalOne(m_lvActions,
m_trigger.ActionCollection, true);
UpdateActionListEx(true);
}
private void OnBtnActionMoveDown(object sender, EventArgs e)
{
UIUtil.MoveSelectedItemsInternalOne(m_lvActions,
m_trigger.ActionCollection, false);
UpdateActionListEx(true);
}
private void OnBtnHelp(object sender, EventArgs e)
{
AppHelp.ShowHelp(AppDefs.HelpTopics.Triggers, null);
}
private void OnEventsItemActivate(object sender, EventArgs e)
{
OnEventEdit(sender, e);
}
private void OnConditionsItemActivate(object sender, EventArgs e)
{
OnConditionEdit(sender, e);
}
private void OnActionsItemActivate(object sender, EventArgs e)
{
OnActionEdit(sender, e);
}
private void OnTabMainSelectedIndexChanged(object sender, EventArgs e)
{
EnableControlsEx();
}
}
}
| kusuriya/PasswordKeeper | KeePass/Forms/EcasTriggerForm.cs | C# | gpl-2.0 | 13,199 |
<?php
/**
* @version $Id: mod_banners.php 2176 2011-07-12 14:08:26Z johanjanssens $
* @category Nooku
* @package Nooku_Server
* @subpackage Articles
* @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Module Users
*
* @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
* @category Nooku
* @package Nooku_Server
* @subpackage Articles
*/
echo KFactory::get('mod://admin/latest.html')
->module($module)
->attribs($attribs)
->display(); | raeldc/com_learn | administrator/modules/mod_latest/mod_latest.php | PHP | gpl-2.0 | 658 |
/***************************************************************************
* Copyright (C) 2009 by Tamino Dauth *
* tamino@cdauth.eu *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef WC3LIB_MDLX_TEXTUREANIMATIONTRANSLATION_HPP
#define WC3LIB_MDLX_TEXTUREANIMATIONTRANSLATION_HPP
#include "mdlxtranslation.hpp"
#include "textureanimationtranslations.hpp"
namespace wc3lib
{
namespace mdlx
{
class TextureAnimationTranslation : public MdlxTranslation
{
public:
TextureAnimationTranslation(class TextureAnimationTranslations *translations);
class TextureAnimationTranslations* translations() const;
};
inline class TextureAnimationTranslations* TextureAnimationTranslation::translations() const
{
return boost::polymorphic_cast<class TextureAnimationTranslations*>(this->mdlxScalings());
}
}
}
#endif
| CruzR/wc3lib | src/mdlx/textureanimationtranslation.hpp | C++ | gpl-2.0 | 2,103 |
<?php
/**
*
* MemberMouse(TM) (http://www.membermouse.com)
* (c) MemberMouse, LLC. All rights reserved.
*/
?>
<div id="mm-custom-fields-dialog"></div>
<div id="mm-smarttags-dialog"></div>
<script>
jQuery("#mm-custom-fields-dialog").dialog({autoOpen: false});
jQuery("#mm-smarttags-dialog").dialog({autoOpen: false});
</script> | 414digital/414digital.org | wp-content/plugins/membermouse/modules/custom_field.firstrun.php | PHP | gpl-2.0 | 332 |
angular.module('bhima.controllers')
.controller('ConfirmDonationController', ConfirmDonationController);
ConfirmDonationController.$inject = [
'$scope', '$q', '$http', 'validate', 'connect', '$location', 'uuid', 'SessionService'
];
function ConfirmDonationController($scope, $q, $http, validate, connect, $location, uuid, Session) {
var vm = this,
dependencies = {},
session = $scope.session = {};
dependencies.donations = {
query : {
identifier : 'uuid',
tables : {
donations : {columns : ['uuid', 'date', 'is_received', 'confirmed_by']},
donor : {columns : ['id', 'name']},
employee : {columns : ['prenom', 'name::nom_employee', 'postnom']}
},
join : ['donor.id=donations.donor_id', 'donations.employee_id=employee.id'],
where : ['donations.is_received=1', 'AND', 'donations.is_confirmed=0']
}
};
$scope.project = Session.project;
$scope.user = Session.user;
function initialise(model) {
angular.extend($scope, model);
}
function confirmDonation(donationId) {
session.selected = $scope.donations.get(donationId);
loadDetails(donationId);
}
function loadDetails(donationId) {
dependencies.donationDetails = {
query : {
identifier : 'inventory_uuid',
tables : {
donations : {columns : ['uuid', 'donor_id', 'employee_id', 'date', 'is_received']},
donation_item : {columns : ['uuid::donationItemUuid']},
stock : {columns : ['inventory_uuid', 'tracking_number', 'purchase_order_uuid', 'quantity::stockQuantity', 'lot_number', 'entry_date']},
purchase : {columns : ['uuid::purchaseUuid', 'cost', 'currency_id', 'note']},
purchase_item : {columns : ['uuid::purchaseItemUuid', 'unit_price', 'quantity']}
},
join : [
'donations.uuid=donation_item.donation_uuid',
'donation_item.tracking_number=stock.tracking_number',
'stock.purchase_order_uuid=purchase.uuid',
'stock.inventory_uuid=purchase_item.inventory_uuid',
'purchase.uuid=purchase_item.purchase_uuid',
],
where : ['donations.uuid=' + donationId]
}
};
validate.refresh(dependencies, ['donationDetails'])
.then(initialise);
}
function confirmReception() {
writeToJournal()
.then(updateDonation)
.then(generateDocument)
.then(resetSelected)
.catch(handleError);
}
function updatePurchase () {
var purchase = {
uuid : session.selected.uuid,
confirmed : 1,
confirmed_by : $scope.user.id,
paid : 1
};
return connect.put('purchase', [purchase], ['uuid']);
}
function updateDonation () {
var donation = {
uuid : session.selected.uuid,
is_confirmed : 1,
confirmed_by : $scope.user.id
};
return connect.put('donations', [donation], ['uuid']);
}
function writeToJournal() {
var document_id = uuid();
var synthese = [];
// Distinct inventory
var unique = {};
var distinctInventory = [];
$scope.donationDetails.data.forEach(function (x) {
if (!unique[x.inventory_uuid]) {
distinctInventory.push(x);
unique[x.inventory_uuid] = true;
}
});
// End Distinct inventory
// Grouping by lot
var inventoryByLot = [];
distinctInventory.forEach(function (x) {
var lot = [];
lot = $scope.donationDetails.data.filter(function (item) {
return item.inventory_uuid === x.inventory_uuid;
});
inventoryByLot.push({
inventory_uuid : x.inventory_uuid,
purchase_price : x.unit_price,
currency_id : x.currency_id,
quantity : x.quantity,
lots : lot
});
});
// End Grouping by lot
inventoryByLot.forEach(function (item) {
var donation = { uuid : item.lots[0].uuid },
inventory_lots = [];
item.lots.forEach(function (lot) {
inventory_lots.push(lot.tracking_number);
});
synthese.push({
movement : { document_id : document_id },
inventory_uuid : item.inventory_uuid,
donation : donation,
tracking_numbers : inventory_lots,
quantity : item.quantity,
purchase_price : item.purchase_price,
currency_id : item.currency_id,
project_id : $scope.project.id
});
});
return $q.all(synthese.map(function (postingEntry) {
// REM : Stock Account (3) in Debit and Donation Account (?) in credit
// OBJECTIF : Ecrire pour chaque inventory de la donation comme une transaction dans le journal
return $http.post('posting_donation/', postingEntry);
}));
}
function paymentSuccess(result) {
var purchase = {
uuid : session.selected.uuid,
paid : 1
};
return connect.put('purchase', [purchase], ['uuid']);
}
function generateDocument(res) {
$location.path('/invoice/confirm_donation/' + session.selected.uuid);
}
function handleError(error) {
console.log(error);
}
function resetSelected() {
session.selected = null;
validate.refresh(dependencies, ['donations'])
.then(initialise);
}
$scope.confirmDonation = confirmDonation;
$scope.confirmReception = confirmReception;
$scope.resetSelected = resetSelected;
// start the module up
validate.process(dependencies)
.then(initialise);
}
| IMA-WorldHealth/bhima-1.X | client/src/partials/stock/donation_management/confirm_donation.js | JavaScript | gpl-2.0 | 5,472 |
/*
* CINELERRA
* Copyright (C) 2008 Adam Williams <broadcast at earthling dot net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#define GL_GLEXT_PROTOTYPES
#include "bcresources.h"
#include "bcsignals.h"
#include "bcsynchronous.h"
#include "bcwindowbase.h"
#include "condition.h"
#include "mutex.h"
#ifdef HAVE_GL
#include <GL/gl.h>
#endif
#include <string.h>
#include <unistd.h>
#include <string.h>
TextureID::TextureID(int window_id, int id, int w, int h, int components)
{
this->window_id = window_id;
this->id = id;
this->w = w;
this->h = h;
this->components = components;
in_use = 1;
}
ShaderID::ShaderID(int window_id, unsigned int handle, char *source)
{
this->window_id = window_id;
this->handle = handle;
this->source = strdup(source);
}
ShaderID::~ShaderID()
{
free(source);
}
#ifdef HAVE_GL
PBufferID::PBufferID(int window_id,
GLXPbuffer pbuffer,
GLXContext gl_context,
int w,
int h)
{
this->pbuffer = pbuffer;
this->gl_context = gl_context;
this->window_id = window_id;
this->w = w;
this->h = h;
in_use = 1;
}
#endif
BC_SynchronousCommand::BC_SynchronousCommand()
{
command = BC_SynchronousCommand::NONE;
frame = 0;
frame_return = 0;
result = 0;
command_done = new Condition(0, "BC_SynchronousCommand::command_done", 0);
}
BC_SynchronousCommand::~BC_SynchronousCommand()
{
delete command_done;
}
void BC_SynchronousCommand::copy_from(BC_SynchronousCommand *command)
{
this->command = command->command;
this->colormodel = command->colormodel;
this->window = command->window;
this->frame = command->frame;
this->window_id = command->window_id;
this->frame_return = command->frame_return;
this->id = command->id;
this->w = command->w;
this->h = command->h;
}
BC_Synchronous::BC_Synchronous()
: Thread(1, 0, 0)
{
next_command = new Condition(0, "BC_Synchronous::next_command", 0);
command_lock = new Mutex("BC_Synchronous::command_lock");
table_lock = new Mutex("BC_Synchronous::table_lock");
done = 0;
is_running = 0;
current_window = 0;
process_group = setpgid(getpid(), 0);
BC_WindowBase::get_resources()->set_synchronous(this);
}
BC_Synchronous::~BC_Synchronous()
{
commands.remove_all_objects();
}
BC_SynchronousCommand* BC_Synchronous::new_command()
{
return new BC_SynchronousCommand;
}
void BC_Synchronous::create_objects()
{
}
void BC_Synchronous::start()
{
run();
}
void BC_Synchronous::quit()
{
command_lock->lock("BC_Synchronous::quit");
BC_SynchronousCommand *command = new_command();
commands.append(command);
command->command = BC_SynchronousCommand::QUIT;
command_lock->unlock();
next_command->unlock();
}
int BC_Synchronous::send_command(BC_SynchronousCommand *command)
{
command_lock->lock("BC_Synchronous::send_command");
BC_SynchronousCommand *command2 = new_command();
commands.append(command2);
command2->copy_from(command);
command_lock->unlock();
next_command->unlock();
//printf("BC_Synchronous::send_command 1 %d\n", next_command->get_value());
// Wait for completion
command2->command_done->lock("BC_Synchronous::send_command");
int result = command2->result;
delete command2;
return result;
}
void BC_Synchronous::run()
{
is_running = 1;
while(!done)
{
next_command->lock("BC_Synchronous::run");
command_lock->lock("BC_Synchronous::run");
BC_SynchronousCommand *command = 0;
if(commands.total)
{
command = commands.values[0];
commands.remove_number(0);
}
// Prevent executing the same command twice if spurious unlock.
command_lock->unlock();
//printf("BC_Synchronous::run %d\n", command->command);
handle_command_base(command);
// delete command;
}
is_running = 0;
killpg(process_group, SIGUSR1);
}
void BC_Synchronous::handle_command_base(BC_SynchronousCommand *command)
{
if(command)
{
//printf("BC_Synchronous::handle_command_base 1 %d\n", command->command);
switch(command->command)
{
case BC_SynchronousCommand::QUIT:
done = 1;
break;
default:
handle_command(command);
break;
}
}
handle_garbage();
if(command)
{
command->command_done->unlock();
}
}
void BC_Synchronous::handle_command(BC_SynchronousCommand *command)
{
}
void BC_Synchronous::handle_garbage()
{
while(1)
{
table_lock->lock("BC_Synchronous::handle_garbage");
if(!garbage.total)
{
table_lock->unlock();
return;
}
BC_SynchronousCommand *command = garbage.values[0];
garbage.remove_number(0);
table_lock->unlock();
switch(command->command)
{
case BC_SynchronousCommand::DELETE_WINDOW:
delete_window_sync(command);
break;
case BC_SynchronousCommand::DELETE_PIXMAP:
delete_pixmap_sync(command);
break;
}
delete command;
}
}
void BC_Synchronous::put_texture(int id, int w, int h, int components)
{
if(id >= 0)
{
table_lock->lock("BC_Resources::put_texture");
// Search for duplicate
for(int i = 0; i < texture_ids.total; i++)
{
TextureID *ptr = texture_ids.values[i];
if(ptr->window_id == current_window->get_id() &&
ptr->id == id)
{
printf("BC_Synchronous::push_texture: texture exists\n"
"exists: window=%d id=%d w=%d h=%d\n"
"new: window=%d id=%d w=%d h=%d\n",
ptr->window_id,
ptr->id,
ptr->w,
ptr->h,
current_window->get_id(),
id,
w,
h);
table_lock->unlock();
return;
}
}
TextureID *new_id = new TextureID(current_window->get_id(),
id,
w,
h,
components);
texture_ids.append(new_id);
table_lock->unlock();
}
}
int BC_Synchronous::get_texture(int w, int h, int components)
{
table_lock->lock("BC_Resources::get_texture");
for(int i = 0; i < texture_ids.total; i++)
{
if(texture_ids.values[i]->w == w &&
texture_ids.values[i]->h == h &&
texture_ids.values[i]->components == components &&
!texture_ids.values[i]->in_use &&
texture_ids.values[i]->window_id == current_window->get_id())
{
int result = texture_ids.values[i]->id;
texture_ids.values[i]->in_use = 1;
table_lock->unlock();
return result;
}
}
table_lock->unlock();
return -1;
}
void BC_Synchronous::release_texture(int window_id, int id)
{
table_lock->lock("BC_Resources::release_texture");
for(int i = 0; i < texture_ids.total; i++)
{
if(texture_ids.values[i]->id == id &&
texture_ids.values[i]->window_id == window_id)
{
texture_ids.values[i]->in_use = 0;
table_lock->unlock();
return;
}
}
table_lock->unlock();
}
unsigned int BC_Synchronous::get_shader(char *source, int *got_it)
{
table_lock->lock("BC_Resources::get_shader");
for(int i = 0; i < shader_ids.total; i++)
{
if(shader_ids.values[i]->window_id == current_window->get_id() &&
!strcmp(shader_ids.values[i]->source, source))
{
unsigned int result = shader_ids.values[i]->handle;
table_lock->unlock();
*got_it = 1;
return result;
}
}
table_lock->unlock();
*got_it = 0;
return 0;
}
void BC_Synchronous::put_shader(unsigned int handle,
char *source)
{
table_lock->lock("BC_Resources::put_shader");
shader_ids.append(new ShaderID(current_window->get_id(), handle, source));
table_lock->unlock();
}
void BC_Synchronous::dump_shader(unsigned int handle)
{
int got_it = 0;
table_lock->lock("BC_Resources::dump_shader");
for(int i = 0; i < shader_ids.total; i++)
{
if(shader_ids.values[i]->handle == handle)
{
printf("BC_Synchronous::dump_shader\n"
"%s", shader_ids.values[i]->source);
got_it = 1;
break;
}
}
table_lock->unlock();
if(!got_it) printf("BC_Synchronous::dump_shader couldn't find %d\n", handle);
}
void BC_Synchronous::delete_window(BC_WindowBase *window)
{
#ifdef HAVE_GL
BC_SynchronousCommand *command = new_command();
command->command = BC_SynchronousCommand::DELETE_WINDOW;
command->window_id = window->get_id();
command->display = window->get_display();
command->win = window->win;
command->gl_context = window->gl_win_context;
send_garbage(command);
#endif
}
void BC_Synchronous::delete_window_sync(BC_SynchronousCommand *command)
{
#ifdef HAVE_GL
int window_id = command->window_id;
Display *display = command->display;
Window win = command->win;
GLXContext gl_context = command->gl_context;
int debug = 0;
// texture ID's are unique to different contexts
glXMakeCurrent(display,
win,
gl_context);
table_lock->lock("BC_Resources::release_textures");
for(int i = 0; i < texture_ids.total; i++)
{
if(texture_ids.values[i]->window_id == window_id)
{
GLuint id = texture_ids.values[i]->id;
glDeleteTextures(1, &id);
if(debug)
printf("BC_Synchronous::delete_window_sync texture_id=%d window_id=%d\n",
id,
window_id);
texture_ids.remove_object_number(i);
i--;
}
}
for(int i = 0; i < shader_ids.total; i++)
{
if(shader_ids.values[i]->window_id == window_id)
{
glDeleteShader(shader_ids.values[i]->handle);
if(debug)
printf("BC_Synchronous::delete_window_sync shader_id=%d window_id=%d\n",
shader_ids.values[i]->handle,
window_id);
shader_ids.remove_object_number(i);
i--;
}
}
for(int i = 0; i < pbuffer_ids.total; i++)
{
if(pbuffer_ids.values[i]->window_id == window_id)
{
glXDestroyPbuffer(display, pbuffer_ids.values[i]->pbuffer);
glXDestroyContext(display, pbuffer_ids.values[i]->gl_context);
if(debug)
printf("BC_Synchronous::delete_window_sync pbuffer_id=%p window_id=%d\n",
pbuffer_ids.values[i]->pbuffer,
window_id);
pbuffer_ids.remove_object_number(i);
i--;
}
}
table_lock->unlock();
XDestroyWindow(display, win);
if(gl_context) glXDestroyContext(display, gl_context);
#endif
}
#ifdef HAVE_GL
void BC_Synchronous::put_pbuffer(int w,
int h,
GLXPbuffer pbuffer,
GLXContext gl_context)
{
int exists = 0;
table_lock->lock("BC_Resources::release_textures");
for(int i = 0; i < pbuffer_ids.total; i++)
{
PBufferID *ptr = pbuffer_ids.values[i];
if(ptr->w == w &&
ptr->h == h &&
ptr->pbuffer == pbuffer)
{
// Exists
exists = 1;
break;
}
}
if(!exists)
{
PBufferID *ptr = new PBufferID(current_window->get_id(),
pbuffer,
gl_context,
w,
h);
pbuffer_ids.append(ptr);
}
table_lock->unlock();
}
GLXPbuffer BC_Synchronous::get_pbuffer(int w,
int h,
int *window_id,
GLXContext *gl_context)
{
table_lock->lock("BC_Resources::release_textures");
for(int i = 0; i < pbuffer_ids.total; i++)
{
PBufferID *ptr = pbuffer_ids.values[i];
if(ptr->w == w &&
ptr->h == h &&
ptr->window_id == current_window->get_id() &&
!ptr->in_use)
{
GLXPbuffer result = ptr->pbuffer;
*gl_context = ptr->gl_context;
*window_id = ptr->window_id;
ptr->in_use = 1;
table_lock->unlock();
return result;
}
}
table_lock->unlock();
return 0;
}
void BC_Synchronous::release_pbuffer(int window_id, GLXPbuffer pbuffer)
{
table_lock->lock("BC_Resources::release_textures");
for(int i = 0; i < pbuffer_ids.total; i++)
{
PBufferID *ptr = pbuffer_ids.values[i];
if(ptr->window_id == window_id)
{
ptr->in_use = 0;
}
}
table_lock->unlock();
}
void BC_Synchronous::delete_pixmap(BC_WindowBase *window,
GLXPixmap pixmap,
GLXContext context)
{
BC_SynchronousCommand *command = new_command();
command->command = BC_SynchronousCommand::DELETE_PIXMAP;
command->window_id = window->get_id();
command->display = window->get_display();
command->win = window->win;
command->gl_pixmap = pixmap;
command->gl_context = context;
send_garbage(command);
}
#endif
void BC_Synchronous::delete_pixmap_sync(BC_SynchronousCommand *command)
{
#ifdef HAVE_GL
Display *display = command->display;
Window win = command->win;
glXMakeCurrent(display,
win,
command->gl_context);
glXDestroyContext(display, command->gl_context);
glXDestroyGLXPixmap(display, command->gl_pixmap);
#endif
}
void BC_Synchronous::send_garbage(BC_SynchronousCommand *command)
{
table_lock->lock("BC_Synchronous::delete_window");
garbage.append(command);
table_lock->unlock();
next_command->unlock();
}
BC_WindowBase* BC_Synchronous::get_window()
{
return current_window;
}
| petterreinholdtsen/cinelerra-hv | guicast/bcsynchronous.C | C++ | gpl-2.0 | 12,673 |
(function () {
'use strict';
var module = angular.module('memosWebApp', []);
}());
| tmorin/memos | app/scripts/modules/memosWebApp/module.js | JavaScript | gpl-2.0 | 95 |
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Lang = imports.lang;
const Meta = imports.gi.Meta;
const Shell = imports.gi.Shell;
const Dialog = imports.ui.dialog;
const Main = imports.ui.main;
const Tweener = imports.ui.tweener;
var FROZEN_WINDOW_BRIGHTNESS = -0.3
var DIALOG_TRANSITION_TIME = 0.15
var ALIVE_TIMEOUT = 5000;
var CloseDialog = new Lang.Class({
Name: 'CloseDialog',
Extends: GObject.Object,
Implements: [ Meta.CloseDialog ],
Properties: {
'window': GObject.ParamSpec.override('window', Meta.CloseDialog)
},
_init(window) {
this.parent();
this._window = window;
this._dialog = null;
this._timeoutId = 0;
},
get window() {
return this._window;
},
set window(window) {
this._window = window;
},
_createDialogContent() {
let tracker = Shell.WindowTracker.get_default();
let windowApp = tracker.get_window_app(this._window);
/* Translators: %s is an application name */
let title = _("“%s” is not responding.").format(windowApp.get_name());
let subtitle = _("You may choose to wait a short while for it to " +
"continue or force the application to quit entirely.");
let icon = new Gio.ThemedIcon({ name: 'dialog-warning-symbolic' });
return new Dialog.MessageDialogContent({ icon, title, subtitle });
},
_initDialog() {
if (this._dialog)
return;
let windowActor = this._window.get_compositor_private();
this._dialog = new Dialog.Dialog(windowActor, 'close-dialog');
this._dialog.width = windowActor.width;
this._dialog.height = windowActor.height;
this._dialog.addContent(this._createDialogContent());
this._dialog.addButton({ label: _('Force Quit'),
action: this._onClose.bind(this),
default: true });
this._dialog.addButton({ label: _('Wait'),
action: this._onWait.bind(this),
key: Clutter.Escape });
global.focus_manager.add_group(this._dialog);
},
_addWindowEffect() {
// We set the effect on the surface actor, so the dialog itself
// (which is a child of the MetaWindowActor) does not get the
// effect applied itself.
let windowActor = this._window.get_compositor_private();
let surfaceActor = windowActor.get_first_child();
let effect = new Clutter.BrightnessContrastEffect();
effect.set_brightness(FROZEN_WINDOW_BRIGHTNESS);
surfaceActor.add_effect_with_name("gnome-shell-frozen-window", effect);
},
_removeWindowEffect() {
let windowActor = this._window.get_compositor_private();
let surfaceActor = windowActor.get_first_child();
surfaceActor.remove_effect_by_name("gnome-shell-frozen-window");
},
_onWait() {
this.response(Meta.CloseDialogResponse.WAIT);
},
_onClose() {
this.response(Meta.CloseDialogResponse.FORCE_CLOSE);
},
vfunc_show() {
if (this._dialog != null)
return;
Meta.disable_unredirect_for_display(global.display);
this._timeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, ALIVE_TIMEOUT,
() => {
this._window.check_alive(global.display.get_current_time_roundtrip());
return GLib.SOURCE_CONTINUE;
});
this._addWindowEffect();
this._initDialog();
this._dialog.scale_y = 0;
this._dialog.set_pivot_point(0.5, 0.5);
Tweener.addTween(this._dialog,
{ scale_y: 1,
transition: 'linear',
time: DIALOG_TRANSITION_TIME,
onComplete: () => {
Main.layoutManager.trackChrome(this._dialog, { affectsInputRegion: true });
}
});
},
vfunc_hide() {
if (this._dialog == null)
return;
Meta.enable_unredirect_for_display(global.display);
GLib.source_remove(this._timeoutId);
this._timeoutId = 0;
let dialog = this._dialog;
this._dialog = null;
this._removeWindowEffect();
Tweener.addTween(dialog,
{ scale_y: 0,
transition: 'linear',
time: DIALOG_TRANSITION_TIME,
onComplete: () => {
dialog.destroy();
}
});
},
vfunc_focus() {
if (this._dialog)
this._dialog.grab_key_focus();
}
});
| halfline/gnome-shell | js/ui/closeDialog.js | JavaScript | gpl-2.0 | 4,964 |
# This function runs a .bat file that job handles multiple GridLAB-D files
import subprocess
#C:\Projects\GridLAB-D_Builds\trunk\test\input\batch test\13_node_fault2.glm
def create_batch_file(glm_folder,batch_name):
batch_file = open('{:s}'.format(batch_name),'w')
batch_file.write('gridlabd.exe -T 0 --job\n')
#batch_file.write('pause\n')
batch_file.close()
return None
def run_batch_file(glm_folder,batch_name):
p = subprocess.Popen('{:s}'.format(batch_name),cwd=glm_folder)
code = p.wait()
#print(code)
return None
def main():
#tests here
glm_folder = 'C:\\Projects\\GridLAB-D_Builds\\trunk\\test\\input\\batch_test'
batch_name = 'C:\\Projects\\GridLAB-D_Builds\\trunk\\test\\input\\batch_test\\calibration_batch_file.bat'
create_batch_file(glm_folder,batch_name)
run_batch_file(batch_name)
if __name__ == '__main__':
main()
| NREL/glmgen | glmgen/run_gridlabd_batch_file.py | Python | gpl-2.0 | 850 |